Skip to content
Merged
15 changes: 15 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,20 @@ history/
- ✅ Preserves planning history for archeological research
- ✅ Reduces noise when browsing the project

### Multi-Agent Collaboration

Multiple AI agents may work in the same repository simultaneously. Follow these rules:

- ⚠️ **NEVER revert unexpected changes without asking the user first**
- Other agents may have made those changes intentionally
- Ask: "I found unexpected changes in X. Should I keep or revert them?"
- ⚠️ **NEVER assume uncommitted changes are errors or accidents**
- Another agent may be mid-task on a different branch
- Check `git status` and ask before discarding work
- ✅ If you encounter merge conflicts, pause and ask for guidance
- ✅ Use bd to check if other work is `in_progress` before touching shared files
- ✅ Commit your work frequently to reduce conflict windows

### Important Rules

- ✅ Use bd for ALL task tracking
Expand All @@ -140,5 +154,6 @@ history/
- ❌ Do NOT use external issue trackers
- ❌ Do NOT duplicate tracking systems
- ❌ Do NOT clutter repo root with planning documents
- ❌ Do NOT revert unexpected changes without asking

For more details, see README.md and QUICKSTART.md.
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ When creating or modifying MCP tools:
**Null Handling:**
- `Optional<T>` for methods that may not return value
- Never return null collections - use `Collections.emptyList()` or empty collection
- `Optional.ofNullable(x).orElse(default)` over ternary `x != null ? x : default`
Comment thread
ChrisEdwards marked this conversation as resolved.
Resolved

**Testing:**
- Simplified `mock()`: `ClassName mock = mock()` not `mock(ClassName.class)`
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
<spring-ai.version>1.0.1</spring-ai.version>
<maven-release-plugin.version>3.1.1</maven-release-plugin.version>
<guava.version>33.4.7-jre</guava.version>
<contrast.sdk.version>3.5.0</contrast.sdk.version>
<contrast.sdk.version>3.6.0-SNAPSHOT</contrast.sdk.version>
<mockito-inline.version>5.2.0</mockito-inline.version>
<assertj.version>3.27.6</assertj.version>
<maven-failsafe-plugin.version>3.5.3</maven-failsafe-plugin.version>
Expand Down
165 changes: 122 additions & 43 deletions src/main/java/com/contrast/labs/ai/mcp/contrast/AssessService.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,15 @@
import com.contrast.labs.ai.mcp.contrast.sdkextension.data.sca.LibraryObservation;
import com.contrast.labs.ai.mcp.contrast.utils.PaginationHandler;
import com.contrastsecurity.http.TraceFilterForm;
import com.contrastsecurity.models.EventResource;
import com.contrastsecurity.models.MetadataFilterResponse;
import com.contrastsecurity.models.MetadataItem;
import com.contrastsecurity.models.Rules;
import com.contrastsecurity.models.SessionMetadata;
import com.contrastsecurity.models.Stacktrace;
import com.contrastsecurity.models.TraceFilterBody;
import com.contrastsecurity.models.Trace;
import com.contrastsecurity.models.Traces;
import com.contrastsecurity.sdk.ContrastSDK;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumSet;
Expand Down Expand Up @@ -101,21 +103,32 @@ public Vulnerability getVulnerabilityById(
log.debug("ContrastSDK initialized with host: {}", hostName);

try {
var trace =
contrastSDK.getTraces(orgID, appID, new TraceFilterBody()).getTraces().stream()
.filter(t -> t.getUuid().equalsIgnoreCase(vulnID))
.findFirst()
.orElseThrow();
// Use expand to include application, environments, and session metadata
var expand =
EnumSet.of(
TraceFilterForm.TraceExpandValue.APPLICATION,
TraceFilterForm.TraceExpandValue.SERVER_ENVIRONMENTS,
TraceFilterForm.TraceExpandValue.SESSION_METADATA);
var trace = contrastSDK.getTrace(orgID, appID, vulnID, expand);
if (trace == null) {
throw new IOException(
String.format(
"Vulnerability API returned null for vulnID %s in app %s. Please check API"
+ " connectivity, permissions, and that the vulnerability exists.",
vulnID, appID));
}
log.debug("Found trace with title: {} and rule: {}", trace.getTitle(), trace.getRule());

var recommendationResponse = contrastSDK.getRecommendation(orgID, vulnID);
var requestResponse = contrastSDK.getHttpRequest(orgID, vulnID);
var eventSummaryResponse = contrastSDK.getEventSummary(orgID, vulnID);

var triggerEvent =
eventSummaryResponse.getEvents().stream()
.filter(e -> e.getType().equalsIgnoreCase("trigger"))
.findFirst();
(eventSummaryResponse != null && eventSummaryResponse.getEvents() != null)
? eventSummaryResponse.getEvents().stream()
.filter(e -> e.getType().equalsIgnoreCase("trigger"))
.findFirst()
: Optional.<EventResource>empty();

var stackTraces = new ArrayList<String>();
if (triggerEvent.isPresent()) {
Expand Down Expand Up @@ -154,13 +167,18 @@ public Vulnerability getVulnerabilityById(
}

String httpRequestText = null;
if (requestResponse.getHttpRequest() != null) {
if (requestResponse != null && requestResponse.getHttpRequest() != null) {
httpRequestText = requestResponse.getHttpRequest().getText();
}

String recommendationText = null;
if (recommendationResponse != null && recommendationResponse.getRecommendation() != null) {
recommendationText = recommendationResponse.getRecommendation().getText();
}

var context =
VulnerabilityContext.builder()
.recommendation(recommendationResponse.getRecommendation().getText())
.recommendation(recommendationText)
.stackLibs(stackLibs)
.libraries(new ArrayList<>(libsToReturn)) // Convert Set to List
.httpRequest(httpRequestText)
Expand Down Expand Up @@ -458,7 +476,7 @@ public PaginatedResponse<VulnLight> searchVulnerabilities(
required = false)
String vulnTags)
throws IOException {
log.info(
log.debug(
"Searching org vulnerabilities - page: {}, pageSize: {}, filters: severities={},"
+ " statuses={}, vulnTypes={}, environments={}, lastSeenAfter={}, lastSeenBefore={},"
+ " vulnTags={}",
Expand Down Expand Up @@ -653,15 +671,15 @@ public PaginatedResponse<VulnLight> searchAppVulnerabilities(
if (!StringUtils.hasText(appId)) {
var errorMessage = "appId parameter is required";
log.error("Validation error: {}", errorMessage);
return PaginatedResponse.error(1, 50, errorMessage);
return PaginatedResponse.error(1, PaginationParams.DEFAULT_PAGE_SIZE, errorMessage);
}

// Validate incomplete parameters: sessionMetadataValue without sessionMetadataName
if (StringUtils.hasText(sessionMetadataValue) && !StringUtils.hasText(sessionMetadataName)) {
var errorMessage =
"sessionMetadataValue requires sessionMetadataName. Both must be provided together.";
log.error("Validation error: {}", errorMessage);
return PaginatedResponse.error(1, 50, errorMessage);
return PaginatedResponse.error(1, PaginationParams.DEFAULT_PAGE_SIZE, errorMessage);
}

// Parse and validate inputs
Expand Down Expand Up @@ -711,42 +729,48 @@ public PaginatedResponse<VulnLight> searchAppVulnerabilities(
}

// Make API call - always use app-specific endpoint
// Note: When using session filtering, we get all results (no SDK pagination)
// because we need to filter in-memory before paginating
Traces traces;
// Note: When using session filtering, we fetch ALL pages because we need
// the complete dataset before filtering in-memory
Traces traces = null;
List<VulnLight> vulnerabilities;

// Always set expand values for session metadata
filterForm.setExpand(
EnumSet.of(
TraceFilterForm.TraceExpandValue.SESSION_METADATA,
TraceFilterForm.TraceExpandValue.SERVER_ENVIRONMENTS,
TraceFilterForm.TraceExpandValue.APPLICATION));

if (needsInMemorySessionFiltering) {
// Get all results for in-memory filtering (no SDK pagination, no limit/offset)
filterForm.setExpand(
EnumSet.of(
TraceFilterForm.TraceExpandValue.SESSION_METADATA,
TraceFilterForm.TraceExpandValue.SERVER_ENVIRONMENTS,
TraceFilterForm.TraceExpandValue.APPLICATION));
traces = contrastSDK.getTraces(orgID, appId, filterForm);
// Fetch ALL pages for in-memory filtering (iterates through SDK pagination)
var allTraces = fetchAllTracesForSessionFiltering(contrastSDK, orgID, appId, filterForm);

if (allTraces.isEmpty()) {
log.debug("No traces found for app {} (all pages fetched)", appId);
}

// Convert to VulnLight directly from the list
vulnerabilities = allTraces.stream().map(vulnerabilityMapper::toVulnLight).toList();
} else {
// Use SDK pagination when no in-memory filtering needed
filterForm.setLimit(pagination.limit());
filterForm.setOffset(pagination.offset());
filterForm.setExpand(
EnumSet.of(
TraceFilterForm.TraceExpandValue.SESSION_METADATA,
TraceFilterForm.TraceExpandValue.SERVER_ENVIRONMENTS,
TraceFilterForm.TraceExpandValue.APPLICATION));
traces = contrastSDK.getTraces(orgID, appId, filterForm);
}

if (traces == null || traces.getTraces() == null) {
var errorMsg =
String.format(
"App-level vulnerability API returned null for app %s. Please check API"
+ " connectivity and permissions.",
appId);
log.error(errorMsg);
return PaginatedResponse.error(pagination.page(), pagination.pageSize(), errorMsg);
}
if (traces == null || traces.getTraces() == null) {
var errorMsg =
String.format(
"App-level vulnerability API returned null for app %s. Please check API"
+ " connectivity and permissions.",
appId);
log.error(errorMsg);
return PaginatedResponse.error(pagination.page(), pagination.pageSize(), errorMsg);
}

// Convert to VulnLight
var vulnerabilities =
traces.getTraces().stream().map(vulnerabilityMapper::toVulnLight).toList();
// Convert to VulnLight
vulnerabilities =
traces.getTraces().stream().map(vulnerabilityMapper::toVulnLight).toList();
}

// Apply in-memory agent session ID filtering if requested
if (agentSessionId != null) {
Expand Down Expand Up @@ -802,7 +826,9 @@ public PaginatedResponse<VulnLight> searchAppVulnerabilities(
}

// Apply pagination to in-memory filtered results
if (agentSessionId != null || StringUtils.hasText(sessionMetadataName)) {
// Use needsInMemorySessionFiltering to determine if we fetched all pages
// This handles the case where useLatestSession=true but no sessions were found
if (needsInMemorySessionFiltering) {
var startIndex = pagination.offset();
var endIndex = Math.min(startIndex + pagination.pageSize(), finalVulns.size());
var pagedVulns =
Expand Down Expand Up @@ -862,6 +888,59 @@ private List<Metadata> getMetadataFromApp(Application app) {
return metadata;
}

/**
* Fetches all traces from the SDK by iterating through all pages. This is needed when in-memory
* session filtering is required, because we must have the complete dataset before filtering.
*
* @param sdk The ContrastSDK instance
* @param orgId The organization ID
* @param appId The application ID
* @param filterForm The filter form (will be modified to set limit/offset for pagination)
* @return List of all traces across all pages
* @throws IOException If an API error occurs
*/
private List<Trace> fetchAllTracesForSessionFiltering(
ContrastSDK sdk, String orgId, String appId, TraceFilterForm filterForm) throws IOException {
final int PAGE_SIZE = 500;
Comment thread
ChrisEdwards marked this conversation as resolved.
Resolved
var allTraces = new ArrayList<Trace>();
int offset = 0;

while (true) {
filterForm.setLimit(PAGE_SIZE);
filterForm.setOffset(offset);

Traces pageResult;
try {
pageResult = sdk.getTraces(orgId, appId, filterForm);
} catch (Exception e) {
throw new IOException("Failed to fetch traces page at offset " + offset, e);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We may want log statement here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is logged in an upcoming overhaul of exception handling:

}

if (pageResult == null

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could use the apache collections lb to check size or array/list:

if (pageResult == null || CollectionUtils.isEmpty(pageResult.getTraces())) {
        break;
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll do a replace of all these in a single pass before release.

|| pageResult.getTraces() == null
|| pageResult.getTraces().isEmpty()) {
break;
}

allTraces.addAll(pageResult.getTraces());
log.debug(
"Fetched {} traces at offset {} (total so far: {})",
pageResult.getTraces().size(),
offset,
allTraces.size());

// If we got fewer than PAGE_SIZE, we've reached the last page
if (pageResult.getTraces().size() < PAGE_SIZE) {
break;
}

offset += PAGE_SIZE;
}

log.debug("Fetched total of {} traces for session filtering", allTraces.size());
return allTraces;
}

@Tool(
name = "list_vulnerability_types",
description =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@
*/
public record PaginationParams(
int page, int pageSize, int offset, int limit, List<String> warnings) {

/** Default page size when none specified. */
public static final int DEFAULT_PAGE_SIZE = 50;

/** Maximum allowed page size. */
public static final int MAX_PAGE_SIZE = 100;

/**
* Parse and validate pagination parameters. Invalid values are clamped to acceptable defaults
* with warnings.
Expand All @@ -48,14 +55,17 @@ public static PaginationParams of(Integer page, Integer pageSize) {
}

// Soft failure: invalid pageSize → clamp to range
int actualSize = pageSize != null && pageSize > 0 ? pageSize : 50;
int actualSize = pageSize != null && pageSize > 0 ? pageSize : DEFAULT_PAGE_SIZE;
if (pageSize != null && pageSize < 1) {
warnings.add(String.format("Invalid pageSize %d, using default 50", pageSize));
actualSize = 50;
} else if (pageSize != null && pageSize > 100) {
warnings.add(
String.format("Requested pageSize %d exceeds maximum 100, capped to 100", pageSize));
actualSize = 100;
String.format("Invalid pageSize %d, using default %d", pageSize, DEFAULT_PAGE_SIZE));
actualSize = DEFAULT_PAGE_SIZE;
} else if (pageSize != null && pageSize > MAX_PAGE_SIZE) {
warnings.add(
String.format(
"Requested pageSize %d exceeds maximum %d, capped to %d",
pageSize, MAX_PAGE_SIZE, MAX_PAGE_SIZE));
actualSize = MAX_PAGE_SIZE;
}

return new PaginationParams(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.contrast.labs.ai.mcp.contrast.sdkextension.data.routecoverage.RouteCoverageResponse;
import com.contrastsecurity.models.RouteCoverageMetadataLabelValues;
import java.io.IOException;
import java.util.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.beans.factory.annotation.Value;
Expand Down Expand Up @@ -61,9 +62,11 @@ public class RouteCoverageService {
+ " not exercised) or EXERCISED (received HTTP traffic). All filter parameters are"
+ " truly optional - if none provided (null or empty strings), returns all routes"
+ " across all sessions. Parameters: appId (required), sessionMetadataName"
+ " (optional), sessionMetadataValue (optional). NOTE: sessionMetadataName and"
+ " sessionMetadataValue must be provided together or both omitted - providing"
+ " only one will result in an error. useLatestSession (optional).")
+ " (optional), sessionMetadataValue (optional), useLatestSession (optional). NOTE:"
+ " sessionMetadataName and sessionMetadataValue must be provided together or both"
+ " omitted. IMPORTANT: useLatestSession and sessionMetadataName/Value are mutually"
+ " exclusive - if both are provided, useLatestSession takes precedence and the"
+ " session metadata filter is ignored.")
public RouteCoverageResponse getRouteCoverage(
String appId,
String sessionMetadataName,
Expand All @@ -87,6 +90,17 @@ public RouteCoverageResponse getRouteCoverage(
throw new IllegalArgumentException(errorMsg);
}

// Warn if mutually exclusive parameters are both provided
if (Boolean.TRUE.equals(useLatestSession) && StringUtils.hasText(sessionMetadataName)) {
log.atWarn()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why the spring structured logging use here but not other log statements? Just to get the key/value logging?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems so. This class is getting overhauled soon for consistent handling of validation. This will go away. AIML-303. Its in flight. New rules will apply. If you provide conflicting params it will warn the user in the response directly, no need to log. This is an intermediate state to get there.

.setMessage(
"Both useLatestSession and sessionMetadataName provided - these are mutually"
+ " exclusive. Using useLatestSession and ignoring sessionMetadataName/Value.")
.addKeyValue("sessionMetadataName", sessionMetadataName)
.addKeyValue("sessionMetadataValue", sessionMetadataValue)
.log();
}

// Initialize SDK
var contrastSDK =
SDKHelper.getSDK(hostName, apiKey, serviceKey, userName, httpProxyHost, httpProxyPort);
Expand Down Expand Up @@ -133,6 +147,20 @@ public RouteCoverageResponse getRouteCoverage(
// Call SDK to get route coverage
log.debug("Fetching route coverage data for application ID: {}", appId);
var response = sdkExtension.getRouteCoverage(orgID, appId, requestExtended);

// Defensive null checks - API may return null on errors or permission issues
if (response == null) {
log.error("Route coverage API returned null for app {}", appId);
var errorResponse = new RouteCoverageResponse();
errorResponse.setSuccess(false);
return errorResponse;
}

if (response.getRoutes() == null) {
log.warn("No routes returned for app {} - returning empty response", appId);
response.setRoutes(Collections.emptyList());
}

log.debug("Found {} routes for application", response.getRoutes().size());

// Fetch route details for each route
Expand Down
Loading
Loading