diff --git a/docs/client-configuration.md b/docs/client-configuration.md index 5e7ab056cf8..1c674bc68da 100644 --- a/docs/client-configuration.md +++ b/docs/client-configuration.md @@ -273,7 +273,7 @@ This headroom is a practical default, not a guarantee for every analysis duration. Setup preserves positive timeout values already in the `rea` entry. Setup also forwards explicitly selected input/output schema profiles, -`REA_MCP_MAX_RESPONSE_BYTES`, provider paths and supported Ghidra, JADX and Kuna +`REA_MCP_MAX_RESPONSE_BYTES`, `REA_MCP_MAX_INPUT_ELEMENTS`, provider paths and supported Ghidra, JADX and Kuna settings. It also forwards explicit executable and resource selections for ADB, apktool, packet capture, GDB/Rizin/objdump, Cutter, WABT, Wakaru, firmware and signal tools, browser inspection, and pwntools/pwndbg. This includes their diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md index 3871cc0835b..24c845dbb79 100644 --- a/docs/mcp-contracts.md +++ b/docs/mcp-contracts.md @@ -364,6 +364,38 @@ that buffer. It does not raise REA's reserved single-string limit, which is raise that Node ceiling. It does not change analysis coverage or retained content. Ordinary responses keep their existing complete result contract. +### Input validation resource allowance + +Both HTTP and stdio admit at most 1,024 combined array elements and object +members in one tool's arguments by default. The pinned SDK counts them before +canonical schema validation or lazy runtime materialization. Oversized calls +return a bounded, nonretryable `resource_constraint` with resource `transport` +and `reported_limits.max_input_elements`; the full element count is not claimed. +No provider or tool handler starts for a refused call. Subsequent calls remain +usable. + +Set `REA_MCP_MAX_INPUT_ELEMENTS` to a positive decimal safe integer and restart +REA to select another allowance for a larger complete observation or batch. +Where a tool supports retained-Evidence or Evidence-file selectors, prefer +those selectors to resending large inline records. Admission never truncates +the caller's selected input or removes retained Evidence. +This is a configurable transport admission policy, not a per-array `maxItems` +contract or an exact heap guarantee. Missing required fields can amplify one +input element into many issues: on the pinned Evidence array schema, +1,024 empty objects produced 16,384 issues and about 26 MiB heapUsed delta +before SDK formatting. The default therefore admits at most 1,023 such objects +plus the root member, rather than extrapolating the scalar case to larger batches; +actual memory also depends on schema branches, runtime state and concurrent +work. HTTP's separate request-byte limit and the client's receive limit still +apply. + +Canonical schemas and CLI/application analysis semantics remain shared and +unchanged. Admitted arguments retain the same values and ordinary validation +diagnostics. SDK embedders can select `maxToolInputElements` in the server +options; the common REA MCP server supplies the finite default to eager and +deferred registrations alike. This does not impose the separate semantic +batch-workload limit tracked in issue #5930. + ### Error recovery and deadline ownership Initialization instructions and the static JavaScript tool description teach diff --git a/docs/testing.md b/docs/testing.md index 386a694f510..57390a6564d 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -480,6 +480,18 @@ and retain representative compiled CLI parity checks. Every distinct source scenario still runs through the public workflow; session-lifecycle scenarios need their own sessions and cleanup assertions. +Complete-inline-Evidence conformance uses +`scripts/lib/mcp-verification-environment.mjs`: a finite 65,536-element +allowance selected by the application harness, file-owned CLI/MCP session and +artifact verifiers. +Explicit harness environment selections take precedence. This keeps canonical +workflow assertions reachable for large retained observations. Admission-policy +tests launch the public server with the resource setting unset or explicitly +selected, including the default structured-input boundary and continued-service +checks. Downstream capacity fixtures select enough finite transport allowance +to reach their original memory, depth, cycle or representation boundary; retain +those stronger assertions. + When a matrix already holds a named tool definition from live `tools/list`, pass that definition through the SDK's `toolDefinition` call option. This keeps the selected output-schema validation without eagerly compiling unrelated diff --git a/scripts/lib/artifact-e2e.mjs b/scripts/lib/artifact-e2e.mjs index 9d49cb7a811..15d5915fb3c 100644 --- a/scripts/lib/artifact-e2e.mjs +++ b/scripts/lib/artifact-e2e.mjs @@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url"; import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { withVerifierCleanup } from "./verifier-cleanup.mjs"; +import { INLINE_EVIDENCE_MCP_ENVIRONMENT } from "./mcp-verification-environment.mjs"; // REA registers process-static tool contracts. Bind their parsed definitions to // the SDK's negotiated connection identity, including when a Client reconnects. @@ -123,7 +124,7 @@ const withOpenedArtifactMcp = async (target, openTool, verify) => { const transport = new StdioClientTransport({ command: process.execPath, args: [fileURLToPath(new URL("../rea.mjs", import.meta.url)), "mcp"], - env: environment(), + env: { ...environment(), ...INLINE_EVIDENCE_MCP_ENVIRONMENT }, stderr: "pipe", }); const client = new Client({ name: "artifact-real-e2e", version: "1" }); diff --git a/scripts/lib/mcp-verification-environment.d.mts b/scripts/lib/mcp-verification-environment.d.mts new file mode 100644 index 00000000000..8bc6d2a8b08 --- /dev/null +++ b/scripts/lib/mcp-verification-environment.d.mts @@ -0,0 +1,3 @@ +export const INLINE_EVIDENCE_MCP_ENVIRONMENT: { + readonly REA_MCP_MAX_INPUT_ELEMENTS: "65536"; +}; diff --git a/scripts/lib/mcp-verification-environment.mjs b/scripts/lib/mcp-verification-environment.mjs new file mode 100644 index 00000000000..602719f1b60 --- /dev/null +++ b/scripts/lib/mcp-verification-environment.mjs @@ -0,0 +1,6 @@ +/** Finite allowance for conformance workflows that resend complete Evidence. + * Admission-policy regressions exercise the production default separately. + */ +export const INLINE_EVIDENCE_MCP_ENVIRONMENT = Object.freeze({ + REA_MCP_MAX_INPUT_ELEMENTS: "65536", +}); diff --git a/src/application/SetupRegistrationEnvironment.ts b/src/application/SetupRegistrationEnvironment.ts index 4eb04d06d1d..ad629fb595c 100644 --- a/src/application/SetupRegistrationEnvironment.ts +++ b/src/application/SetupRegistrationEnvironment.ts @@ -72,6 +72,7 @@ const SELECTED_REGISTRATION_SETTINGS = [ "REA_MCP_TOOL_FAMILIES", "REA_MCP_OUTPUT_SCHEMA_PROFILE", "REA_MCP_MAX_RESPONSE_BYTES", + "REA_MCP_MAX_INPUT_ELEMENTS", "REA_NATIVE_MATCHING_REPRESENTATION_BYTES", "REA_REGEX_MATCHING_DEADLINE_MS", "REA_REGEX_WORKER_HEAP_REQUEST_MIB", diff --git a/src/config.test.ts b/src/config.test.ts index 939fcc4e882..7abcf113ebe 100644 --- a/src/config.test.ts +++ b/src/config.test.ts @@ -56,6 +56,24 @@ it("accepts ordinary custom environment strings and omitted values", () => { }); describe("runtime configuration", () => { + it("preserves a selected MCP input allowance for deferred startup and refuses disabling values", () => { + expect(parseConfig({ REA_MCP_MAX_INPUT_ELEMENTS: "8192" })).toMatchObject({ + ok: true, + value: { mcpMaxInputElements: 8192 }, + }); + const invalid = parseConfig({ REA_MCP_MAX_INPUT_ELEMENTS: "Infinity" }); + expect(invalid.ok).toBe(false); + if (invalid.ok) + throw new Error( + "Infinite MCP input allowance must not be accepted from the environment", + ); + expect(invalid.error.settings).toEqual([ + { + setting: "REA_MCP_MAX_INPUT_ELEMENTS", + constraint: expect.stringContaining("positive decimal safe integer"), + }, + ]); + }); it("allows target-free startup and applies runtime defaults", () => { const empty = parseConfig({}); expect(empty.ok).toBe(true); diff --git a/src/config/environment.ts b/src/config/environment.ts index fbc771dbea3..65e2a08fd38 100644 --- a/src/config/environment.ts +++ b/src/config/environment.ts @@ -3,6 +3,7 @@ import { ghidraProgramNameSchema, } from "./ghidraExistingProject.js"; import { z } from "zod"; +import { mcpInputBudgetSchema } from "./mcpInputBudget.js"; import { isAbsolute } from "node:path"; import { ConfigurationError } from "../domain/configurationErrors.js"; @@ -45,6 +46,7 @@ const environmentSchema = z.object({ REA_ANALYSIS_PROVIDER: analysisProviderSelectorSchema.default("auto"), REA_BRIDGE_MAX_REQUEST_BYTES: bridgeMaxRequestBytesSchema.optional(), REA_MCP_MAX_RESPONSE_BYTES: mcpResponseBudgetSchema.optional(), + REA_MCP_MAX_INPUT_ELEMENTS: mcpInputBudgetSchema.optional(), REA_ASAR_MAX_HEADER_BYTES: asarMaxHeaderBytesSchema.optional(), REA_CAPTURE_DECODER_OLD_GENERATION_MIB: captureDecoderOldGenerationMiBSchema.optional(), diff --git a/src/config/mcpInputBudget.test.ts b/src/config/mcpInputBudget.test.ts new file mode 100644 index 00000000000..993ca2e08bb --- /dev/null +++ b/src/config/mcpInputBudget.test.ts @@ -0,0 +1,46 @@ +import { expect, it } from "vitest"; +import { ConfigurationError } from "../domain/configurationErrors.js"; +import { + DEFAULT_MCP_MAX_INPUT_ELEMENTS, + parseMcpInputBudget, +} from "./mcpInputBudget.js"; + +it("defaults to the finite MCP input admission allowance", () => { + expect(parseMcpInputBudget(undefined)).toEqual({ + ok: true, + value: DEFAULT_MCP_MAX_INPUT_ELEMENTS, + }); +}); + +it.each(["1", "8192", "65536", String(Number.MAX_SAFE_INTEGER)])( + "preserves the selected safe decimal allowance %s", + (value) => { + expect(parseMcpInputBudget(value)).toEqual({ + ok: true, + value: Number(value), + }); + }, +); + +it.each([ + "", + "0", + "-1", + "1.5", + "Infinity", + "1e5", + "0x100", + " 42", + "9007199254740992", +])("refuses invalid allowance %s without disabling admission", (value) => { + const parsed = parseMcpInputBudget(value); + expect(parsed.ok).toBe(false); + if (parsed.ok) throw new Error("Invalid admission setting was accepted"); + expect(parsed.error).toBeInstanceOf(ConfigurationError); + expect(parsed.error.settings).toEqual([ + { + setting: "REA_MCP_MAX_INPUT_ELEMENTS", + constraint: expect.stringContaining("positive decimal safe integer"), + }, + ]); +}); diff --git a/src/config/mcpInputBudget.ts b/src/config/mcpInputBudget.ts new file mode 100644 index 00000000000..4a417ad7033 --- /dev/null +++ b/src/config/mcpInputBudget.ts @@ -0,0 +1,36 @@ +import { positiveDecimalIntegerSchema } from "./positiveDecimalInteger.js"; +import { ConfigurationError } from "../domain/configurationErrors.js"; +import { err, ok, type Result } from "../domain/result.js"; + +/** Per-call MCP admission policy, not a byte or heap-size guarantee. + * Missing fields amplify too: 1,024 empty Evidence objects create + * 16,384 issues and about 26 MiB heapUsed delta before error formatting. Use + * an allowance no larger than that measured structured case, rather than + * extrapolating the scalar-only measurements to larger batches; + * operators may select another finite allowance for their workload. + */ +export const DEFAULT_MCP_MAX_INPUT_ELEMENTS = 1_024; + +const setting = "REA_MCP_MAX_INPUT_ELEMENTS"; +const constraint = `${setting} must be a positive decimal safe integer counting combined array elements and object members; the default is ${String(DEFAULT_MCP_MAX_INPUT_ELEMENTS)}.`; + +export const mcpInputBudgetSchema = positiveDecimalIntegerSchema( + 1, + Number.MAX_SAFE_INTEGER, + constraint, +); + +/** Invalid resource settings fail explicitly rather than disabling admission. */ +export const parseMcpInputBudget = ( + value: string | undefined, +): Result => { + if (value === undefined) return ok(DEFAULT_MCP_MAX_INPUT_ELEMENTS); + const parsed = mcpInputBudgetSchema.safeParse(value); + return parsed.success + ? ok(parsed.data) + : err( + new ConfigurationError(constraint, { + settings: [{ setting, constraint }], + }), + ); +}; diff --git a/src/config/parseConfig.ts b/src/config/parseConfig.ts index 7905af5a333..3f8c3254932 100644 --- a/src/config/parseConfig.ts +++ b/src/config/parseConfig.ts @@ -109,6 +109,9 @@ export const parseConfig = ( ...(env.REA_MCP_MAX_RESPONSE_BYTES === undefined ? {} : { mcpMaxResponseBytes: env.REA_MCP_MAX_RESPONSE_BYTES }), + ...(env.REA_MCP_MAX_INPUT_ELEMENTS === undefined + ? {} + : { mcpMaxInputElements: env.REA_MCP_MAX_INPUT_ELEMENTS }), ...(env.REA_MCP_INPUT_SCHEMA_PROFILE === undefined ? {} : { mcpInputSchemaProfile: env.REA_MCP_INPUT_SCHEMA_PROFILE }), diff --git a/src/config/types.ts b/src/config/types.ts index 880b03674b0..d735fc5d83a 100644 --- a/src/config/types.ts +++ b/src/config/types.ts @@ -14,6 +14,7 @@ import type { RegexWorkerHeapRequest } from "./regexWorkerHeapRequest.js"; export interface AppConfig { readonly mcpToolFamilies?: readonly McpToolFamilies[number][]; readonly mcpMaxResponseBytes?: number; + readonly mcpMaxInputElements?: number; readonly mcpInputSchemaProfile?: McpInputSchemaProfile; readonly mcpOutputSchemaProfile?: McpOutputSchemaProfile; readonly analysisProvider: AnalysisProviderSelector; diff --git a/src/main/deferredRuntime.ts b/src/main/deferredRuntime.ts index 3888cdfab0d..c54aa924acc 100644 --- a/src/main/deferredRuntime.ts +++ b/src/main/deferredRuntime.ts @@ -205,6 +205,7 @@ export const runDeferred = async ( dependencies.setExitCode(1); throw cause; }), + config.mcpMaxInputElements, ); return server; }); diff --git a/src/server/DeferredEvidenceMcpServer.test.ts b/src/server/DeferredEvidenceMcpServer.test.ts index 0713e387782..6094693ff17 100644 --- a/src/server/DeferredEvidenceMcpServer.test.ts +++ b/src/server/DeferredEvidenceMcpServer.test.ts @@ -77,6 +77,7 @@ const fixture = async ( readonly failLoad?: boolean; readonly invalidOutput?: boolean; readonly failAfterTool?: boolean; + readonly maximumInputElements?: number; } = {}, ) => { const started = barrier(); @@ -138,6 +139,7 @@ const fixture = async ( ); }); }, + options.maximumInputElements, ); const client = new Client({ name: "deferred-fixture-client", version: "1" }); const [clientTransport, serverTransport] = @@ -159,6 +161,33 @@ const fixture = async ( }; }; +it("refuses excess input before loading a deferred runtime, then admits a valid call", async () => { + const f = await fixture({ maximumInputElements: 2 }); + const result = await f.client.callTool({ + name: "fixture", + arguments: { n: 3, other: [0] }, + }); + expect(result.isError).toBe(true); + const text = result.content.find((part) => part.type === "text")?.text; + expect(JSON.parse(text ?? "null")).toMatchObject({ + error: { + code: "resource_constraint", + details: { reported_limits: { max_input_elements: 2 } }, + }, + }); + expect(f.loads()).toBe(0); + expect(f.calls).not.toHaveBeenCalled(); + await f.client.ping(); + const admitted = await f.client.callTool({ + name: "fixture", + arguments: { n: 4 }, + }); + expect(admitted.isError).not.toBe(true); + expect(admitted.structuredContent).toEqual({ n: 4 }); + expect(f.loads()).toBe(1); + expect(f.calls).toHaveBeenCalledOnce(); +}); + it("discovers without initialization, then shares one canonical runtime and preserves request metadata", async () => { const hold = barrier(); const f = await fixture({ hold }); diff --git a/src/server/DeferredEvidenceMcpServer.ts b/src/server/DeferredEvidenceMcpServer.ts index 438a8d6aa45..31361fef693 100644 --- a/src/server/DeferredEvidenceMcpServer.ts +++ b/src/server/DeferredEvidenceMcpServer.ts @@ -60,12 +60,16 @@ export class DeferredEvidenceMcpServer extends EvidenceMcpServerCore { private readonly initialize: ( server: DeferredEvidenceMcpServer, ) => Promise, + maximumInputElements?: number, ) { super( catalog.info, { capabilities: catalog.capabilities, instructions: catalog.instructions, + ...(maximumInputElements === undefined + ? {} + : { maxToolInputElements: maximumInputElements }), }, undefined, delivery, diff --git a/src/server/EvidenceMcpServerCore.ts b/src/server/EvidenceMcpServerCore.ts index 534e2627a51..185bbca1583 100644 --- a/src/server/EvidenceMcpServerCore.ts +++ b/src/server/EvidenceMcpServerCore.ts @@ -1,5 +1,6 @@ import type { AnalysisSettings } from "../application/AnalysisSettings.js"; import { AsyncLocalStorage } from "node:async_hooks"; +import { DEFAULT_MCP_MAX_INPUT_ELEMENTS } from "../config/mcpInputBudget.js"; import { specTypeSchemas, @@ -232,6 +233,7 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer { private readonly compactPresentation: | CompactInputSchemaPresentation | undefined; + private readonly maximumInputElements: number; constructor( info: Implementation, @@ -245,7 +247,10 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer { | ReadonlySet | undefined = undefined, ) { - super(info, options); + const maximumInputElements = + options.maxToolInputElements ?? DEFAULT_MCP_MAX_INPUT_ELEMENTS; + super(info, { ...options, maxToolInputElements: maximumInputElements }); + this.maximumInputElements = maximumInputElements; this.compactPresentation = compactPresentation === undefined ? undefined @@ -334,6 +339,7 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer { () => this.recordEvidence, () => this.delivery, this.outputSchemaProfile, + this.maximumInputElements, ), ); } @@ -369,6 +375,7 @@ class ErrorEvidenceTransport implements Transport { | undefined, private readonly currentDelivery: () => ToolResultDelivery, private readonly outputSchemaProfile: McpOutputSchemaProfile, + private readonly maximumInputElements: number, ) { if (transport.hasPerRequestStream !== undefined) this.hasPerRequestStream = transport.hasPerRequestStream; @@ -572,12 +579,7 @@ class ErrorEvidenceTransport implements Transport { ? encodeToolResult(structured, budget, "error-text", targetContent) : measureMcpResultWithinBudget(sdkResultWithMarker, budget); const normalized = encoded.ok - ? this.normalizeSdkValidationError( - message, - tool, - targetContent, - sdkInputValidationDiagnostic(sdkDiagnostic, tool), - ) + ? this.normalizeSdkInputError(message, tool, targetContent, sdkDiagnostic) : undefined; if ( normalized !== undefined && @@ -735,26 +737,48 @@ class ErrorEvidenceTransport implements Transport { : fitted; } - private normalizeSdkValidationError( + private normalizeSdkInputError( message: JSONRPCMessage, tool: string | undefined, targetContent: boolean, - diagnostic: string | undefined, + text: string | undefined, ): JSONRPCMessage | undefined { if ( tool === undefined || - diagnostic === undefined || + text === undefined || !isJSONRPCResultResponse(message) || !isCallToolResult(message.result) ) return undefined; - const error = new AnalysisInputError( - tool, - { - userMessage: `The arguments for MCP tool ${tool} do not match its advertised input schema.`, - }, - [{ path: [], reason: "invalid_value", message: diagnostic }], - ); + let error: AnalysisInputError | AnalysisResourceConstraintError; + // The SDK owns counting and refusal before Standard Schema validation. + // Recognize its exact wire refusal using our configured fact, without + // reparsing the arguments or manufacturing a complete element count. + if ( + text === + `Invalid arguments for tool ${tool}: arguments contain more than the maximum of ${String(this.maximumInputElements)} elements` + ) { + error = new AnalysisResourceConstraintError( + tool, + "transport", + "The MCP tool arguments exceed the configured input element allowance; schema validation and tool execution did not start.", + { max_input_elements: this.maximumInputElements }, + { + remediationAction: + "Reduce the combined array elements and object members in the arguments, or restart REA with a larger REA_MCP_MAX_INPUT_ELEMENTS allowance for this workload.", + }, + ); + } else { + const diagnostic = sdkInputValidationDiagnostic(text, tool); + if (diagnostic === undefined) return undefined; + error = new AnalysisInputError( + tool, + { + userMessage: `The arguments for MCP tool ${tool} do not match its advertised input schema.`, + }, + [{ path: [], reason: "invalid_value", message: diagnostic }], + ); + } const result = this.delivery.toErrorToolResult(error, targetContent); return { ...message, diff --git a/src/server/McpInputCapacity.test.ts b/src/server/McpInputCapacity.test.ts new file mode 100644 index 00000000000..9ab1afd14b4 --- /dev/null +++ b/src/server/McpInputCapacity.test.ts @@ -0,0 +1,154 @@ +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; +import { expect, it, onTestFinished } from "vitest"; +import { z } from "zod"; +import { EvidenceMcpServerCore } from "./EvidenceMcpServerCore.js"; +import { createToolResultDelivery } from "./toolResult.js"; +import { DEFAULT_MCP_MAX_INPUT_ELEMENTS } from "../config/mcpInputBudget.js"; +import { evidenceSchema } from "../domain/evidence.js"; + +const defaultElements = DEFAULT_MCP_MAX_INPUT_ELEMENTS; + +const fixture = async (maximum?: number, element: z.ZodType = z.unknown()) => { + let validations = 0; + let calls = 0; + const canonical = z.strictObject({ values: z.array(element) }); + const server = new EvidenceMcpServerCore( + { name: "input-capacity-fixture", version: "1" }, + { ...(maximum === undefined ? {} : { maxToolInputElements: maximum }) }, + undefined, + createToolResultDelivery(16_384), + ); + server.registerTool( + "capacity_probe", + { + inputSchema: { + "~standard": { + ...canonical["~standard"], + validate: (value: unknown) => { + validations++; + return canonical["~standard"].validate(value); + }, + }, + }, + }, + async (input) => { + calls++; + return { + content: [{ type: "text", text: String(input.values.length) }], + }; + }, + ); + const client = new Client({ name: "input-capacity-client", version: "1" }); + onTestFinished(async () => { + try { + await client.close(); + } finally { + await server.close(); + } + }); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + return { client, validations: () => validations, calls: () => calls }; +}; + +const refusal = (result: Awaited>): unknown => { + expect(result.isError).toBe(true); + const text = result.content.find((part) => part.type === "text")?.text; + return JSON.parse(text ?? "null"); +}; + +it("bounds default MCP arguments before invoking their canonical validator", async () => { + const f = await fixture(); + const result = await f.client.callTool({ + name: "capacity_probe", + arguments: { values: Array.from({ length: 1_024 }, () => 0) }, + }); + expect(f.validations()).toBe(0); + expect(f.calls()).toBe(0); + expect(refusal(result)).toMatchObject({ + error: { + code: "resource_constraint", + retryable: false, + details: { + operation: "capacity_probe", + resource: "transport", + reported_limits: { max_input_elements: defaultElements }, + }, + }, + }); + expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThan(4096); + await f.client.ping(); +}); + +it("counts nested object members as well as array elements before validation", async () => { + const f = await fixture(8); + const result = await f.client.callTool({ + name: "capacity_probe", + arguments: { + values: [ + { a: 0, b: 1, c: 2 }, + { a: 0, b: 1, c: 2 }, + ], + }, + }); + expect(f.validations()).toBe(0); + expect(f.calls()).toBe(0); + expect(refusal(result)).toMatchObject({ + error: { details: { reported_limits: { max_input_elements: 8 } } }, + }); +}); + +it("refuses missing-field Evidence arrays before their per-field issues are allocated", async () => { + const f = await fixture(undefined, evidenceSchema); + const result = await f.client.callTool({ + name: "capacity_probe", + arguments: { values: Array.from({ length: 1_024 }, () => ({})) }, + }); + expect(f.validations()).toBe(0); + expect(f.calls()).toBe(0); + expect(refusal(result)).toMatchObject({ + error: { + code: "resource_constraint", + details: { reported_limits: { max_input_elements: 1_024 } }, + }, + }); +}); + +it("admits the exact selected allowance without altering the values or schema", async () => { + const f = await fixture(4); + const result = await f.client.callTool({ + name: "capacity_probe", + arguments: { values: ["one", "two", "three"] }, + }); + expect(result.isError).not.toBe(true); + expect(result.content).toEqual([{ type: "text", text: "3" }]); + expect(f.validations()).toBe(1); + expect(f.calls()).toBe(1); + const { tools } = await f.client.listTools(); + expect( + tools.find((tool) => tool.name === "capacity_probe")?.inputSchema, + ).toMatchObject({ + type: "object", + properties: { values: { type: "array" } }, + }); +}); + +it("preserves ordinary canonical refusals and advertised schemas across allowances", async () => { + const bounded = await fixture(4); + const selected = await fixture(Infinity); + const request = { + name: "capacity_probe", + arguments: { values: "not-an-array" }, + }; + const boundedError = refusal(await bounded.client.callTool(request)); + const selectedError = refusal(await selected.client.callTool(request)); + expect(boundedError).toEqual(selectedError); + expect(boundedError).toMatchObject({ error: { code: "invalid_request" } }); + expect(bounded.validations()).toBe(1); + expect(bounded.calls()).toBe(0); + expect((await bounded.client.listTools()).tools).toEqual( + (await selected.client.listTools()).tools, + ); +}); diff --git a/src/server/createServer.ts b/src/server/createServer.ts index 1c521b91ad1..178983b57e5 100644 --- a/src/server/createServer.ts +++ b/src/server/createServer.ts @@ -1,4 +1,5 @@ import { AnalysisSettings } from "../application/AnalysisSettings.js"; +import { parseMcpInputBudget } from "../config/mcpInputBudget.js"; import { registerAnalysisSettingsTools } from "./registerAnalysisSettingsTools.js"; import type { DevicetreeService } from "../application/binaryDiagnostics/DevicetreeService.js"; import { registerDevicetreeTool } from "./registerDevicetreeTool.js"; @@ -407,14 +408,18 @@ const createMcpServer = ( compactPresentation: CompactInputSchemaPresentation | undefined, outputSchemaProfile: McpOutputSchemaProfile, advertisedToolFamilies: ReadonlySet | undefined, -): EvidenceMcpServer => - new EvidenceMcpServer( + inputElementBudget: string | undefined, +): EvidenceMcpServer => { + const configured = parseMcpInputBudget(inputElementBudget); + if (!configured.ok) throw configured.error; + return new EvidenceMcpServer( { name: PRODUCT_IDENTITY.mcpServerKey, version: PRODUCT_IDENTITY.packageVersion, }, { capabilities: {}, + maxToolInputElements: configured.value, instructions: serverInstructions( session !== undefined, advertisedToolFamilies, @@ -433,6 +438,7 @@ const createMcpServer = ( ), advertisedToolFamilies, ); +}; /** * Construct one MCP server without acquiring subprocess resources. @@ -521,6 +527,7 @@ export const createServer = ( compactInputPresentation, selectedOutputSchemaProfile, advertisedToolFamilies, + environment.REA_MCP_MAX_INPUT_ELEMENTS, ); server.analysisSettings = analysisSettings; registerAnalysisSettingsTools(server, analysisSettings); diff --git a/tests/acceptance/analysisSettingsMcp.test.ts b/tests/acceptance/analysisSettingsMcp.test.ts index a4238937786..6acbd7fe4e3 100644 --- a/tests/acceptance/analysisSettingsMcp.test.ts +++ b/tests/acceptance/analysisSettingsMcp.test.ts @@ -6,6 +6,7 @@ import { writeFile } from "node:fs/promises"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; import { join } from "node:path"; import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js"; +import { INLINE_EVIDENCE_MCP_ENVIRONMENT } from "../../scripts/lib/mcp-verification-environment.mjs"; import { asarHeaderBytes } from "../fixtures/asarHeader.js"; import { nativeMatchingNamedInventory } from "../fixtures/nativeFunctionMatching.js"; @@ -189,7 +190,7 @@ it("lowers, restores and seeds the native matching allowance over MCP", async () if (text === undefined) throw new Error("Missing projected error"); return JSON.parse(text).error.details.limit as unknown; }; - const runtime = await connectLocalToolsMcp(); + const runtime = await connectLocalToolsMcp(INLINE_EVIDENCE_MCP_ENVIRONMENT); try { expect( (await runtime.call("match_native_functions", request)).isError, @@ -223,6 +224,7 @@ it("lowers, restores and seeds the native matching allowance over MCP", async () await runtime.client.close(); } const seeded = await connectLocalToolsMcp({ + ...INLINE_EVIDENCE_MCP_ENVIRONMENT, REA_NATIVE_MATCHING_REPRESENTATION_BYTES: "4096", }); try { @@ -256,6 +258,7 @@ it("lowers, restores and seeds the native matching allowance over MCP", async () // An invalid seed is refused by matching alone; MCP stays available and a // runtime override repairs the effective allowance. const invalid = await connectLocalToolsMcp({ + ...INLINE_EVIDENCE_MCP_ENVIRONMENT, REA_NATIVE_MATCHING_REPRESENTATION_BYTES: "0", }); try { diff --git a/tests/acceptance/applications/applicationWorkflowCli.test.ts b/tests/acceptance/applications/applicationWorkflowCli.test.ts index 2a25b876c21..9ae9548b146 100644 --- a/tests/acceptance/applications/applicationWorkflowCli.test.ts +++ b/tests/acceptance/applications/applicationWorkflowCli.test.ts @@ -1,4 +1,5 @@ import { execFile } from "node:child_process"; +import { INLINE_EVIDENCE_MCP_ENVIRONMENT } from "../../../scripts/lib/mcp-verification-environment.mjs"; import { createHash } from "node:crypto"; import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises"; import { createRequire } from "node:module"; @@ -48,7 +49,11 @@ const mcpTransport = new StdioClientTransport({ command: process.execPath, args: [resolve("scripts/rea.mjs"), "mcp"], cwd: process.cwd(), - env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" }, + env: { + PATH: process.env.PATH ?? "", + REA_LOG_LEVEL: "silent", + ...INLINE_EVIDENCE_MCP_ENVIRONMENT, + }, stderr: "pipe", }); mcpTransport.stderr?.on("data", () => undefined); diff --git a/tests/acceptance/applications/electronIpcListenerCallsiteCli.test.ts b/tests/acceptance/applications/electronIpcListenerCallsiteCli.test.ts index 472603cf719..037291d1a33 100644 --- a/tests/acceptance/applications/electronIpcListenerCallsiteCli.test.ts +++ b/tests/acceptance/applications/electronIpcListenerCallsiteCli.test.ts @@ -7,6 +7,7 @@ import { z } from "zod"; import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js"; import { applicationFeatureTraceResultSchema } from "../../../src/domain/javascript/javascriptFeatureTraceSchemas.js"; import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; +import { INLINE_EVIDENCE_MCP_ENVIRONMENT } from "../../../scripts/lib/mcp-verification-environment.mjs"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; import { @@ -48,7 +49,9 @@ cliTest.for(["CLI", "stdio MCP"] as const)( ]); const mcp = - surface === "stdio MCP" ? await connectLocalToolsMcp() : undefined; + surface === "stdio MCP" + ? await connectLocalToolsMcp(INLINE_EVIDENCE_MCP_ENVIRONMENT) + : undefined; let applicationEvidence: unknown; if (surface === "CLI") { const response = await cli.run({ diff --git a/tests/acceptance/applications/exportedFunctionBindingsCli.test.ts b/tests/acceptance/applications/exportedFunctionBindingsCli.test.ts index bc9a6b3ca5c..98141180395 100644 --- a/tests/acceptance/applications/exportedFunctionBindingsCli.test.ts +++ b/tests/acceptance/applications/exportedFunctionBindingsCli.test.ts @@ -1,4 +1,5 @@ import { execFile } from "node:child_process"; +import { INLINE_EVIDENCE_MCP_ENVIRONMENT } from "../../../scripts/lib/mcp-verification-environment.mjs"; import { createHash } from "node:crypto"; import { mkdir, writeFile } from "node:fs/promises"; import { createRequire } from "node:module"; @@ -1310,7 +1311,11 @@ const getMcpClient = async (): Promise => { command: process.execPath, args: [resolve("scripts/rea.mjs"), "mcp"], cwd: process.cwd(), - env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" }, + env: { + PATH: process.env.PATH ?? "", + REA_LOG_LEVEL: "silent", + ...INLINE_EVIDENCE_MCP_ENVIRONMENT, + }, stderr: "pipe", }); transport.stderr?.on("data", () => undefined); diff --git a/tests/acceptance/mcpInputCapacityPcap.test.ts b/tests/acceptance/mcpInputCapacityPcap.test.ts new file mode 100644 index 00000000000..4d2bbc1f9e0 --- /dev/null +++ b/tests/acceptance/mcpInputCapacityPcap.test.ts @@ -0,0 +1,96 @@ +import { existsSync } from "node:fs"; +import { readFile, writeFile } from "node:fs/promises"; +import { createHash } from "node:crypto"; +import { join } from "node:path"; +import { expect, it, onTestFinished } from "vitest"; +import { bundleComparisonResultSchema } from "../../src/domain/bundleComparison.js"; +import { parseEvidence } from "../../src/domain/evidence.js"; +import { parseEvidenceBundle } from "../../src/domain/evidenceBundle.js"; +import { pcapResultSchemas } from "../../src/domain/pcap/pcapAnalysis.js"; +import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js"; +import { offlineHttpCapture } from "../fixtures/pcap/offlineHttpCapture.js"; +import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; + +it.skipIf( + process.platform !== "linux" || + !existsSync("/usr/bin/tshark") || + !existsSync("/usr/bin/capinfos"), +)( + "admits real TShark Evidence and explicit bundle pairs without losing identity or source bytes", + async () => { + const root = await createTestTempDirectory("rea-input-capacity-pcap-"); + const path = join(root, "owned.pcap"); + const uri = "http://example.test/a?value=keep%2Fthis"; + const bytes = offlineHttpCapture(uri); + const digest = createHash("sha256").update(bytes).digest("hex"); + await writeFile(path, bytes); + const { client } = await connectLocalToolsMcp( + { + HOME: root, + USERPROFILE: root, + XDG_CONFIG_HOME: join(root, "config"), + XDG_CACHE_HOME: join(root, "cache"), + XDG_DATA_HOME: join(root, "data"), + REA_TSHARK_COMMAND: "/usr/bin/tshark", + REA_CAPINFOS_COMMAND: "/usr/bin/capinfos", + REA_MCP_OUTPUT_SCHEMA_PROFILE: "off", + NODE_OPTIONS: "--max-old-space-size=3072", + }, + onTestFinished, + ); + const captured = await client.callTool({ + name: "inspect_pcap_capture", + arguments: { path }, + }); + expect(captured.isError).not.toBe(true); + const record = parseEvidence(captured.structuredContent); + const facts = pcapResultSchemas.inspect_pcap_capture.parse( + record.normalized_result, + ); + expect(facts.http_request_uris).toEqual([uri]); + expect(facts.target.path).toBe(path); + const bundlePath = join(root, "recorded.json"); + const exported = await client.callTool({ + name: "export_evidence_bundle", + arguments: { path: bundlePath }, + }); + expect(exported.isError).not.toBe(true); + const bundle = parseEvidenceBundle( + JSON.parse(await readFile(bundlePath, "utf8")), + ); + expect( + bundle.records.find((item) => item.evidence_id === record.evidence_id), + ).toEqual(record); + const response = await client.callTool({ + name: "compare_bundles", + arguments: { + left_bundle_path: bundlePath, + right_bundle_path: bundlePath, + record_pairs: [ + { + left_evidence_id: record.evidence_id, + right_evidence_id: record.evidence_id, + }, + ], + }, + }); + expect(response.isError).not.toBe(true); + const comparison = bundleComparisonResultSchema.parse( + parseEvidence(response.structuredContent).normalized_result, + ); + expect(comparison.summary).toMatchObject({ + records_unchanged: bundle.records.length, + records_changed: 0, + records_added: 0, + records_removed: 0, + }); + expect(comparison.left_bundle_sha256).toBe(comparison.right_bundle_sha256); + expect(comparison.changes).toEqual([]); + expect( + createHash("sha256") + .update(await readFile(path)) + .digest("hex"), + ).toBe(digest); + }, + 90_000, +); diff --git a/tests/acceptance/sqliteDatabaseCli.test.ts b/tests/acceptance/sqliteDatabaseCli.test.ts index 5c7a5ce226f..d0c738ea5f8 100644 --- a/tests/acceptance/sqliteDatabaseCli.test.ts +++ b/tests/acceptance/sqliteDatabaseCli.test.ts @@ -919,7 +919,6 @@ cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)( producer.close(); } const before = await sourceState(path); - const { call } = await connectLocalToolsMcp(); const control = await cli.run({ arguments: [ "inspect-sqlite-database", @@ -965,13 +964,21 @@ cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)( ], environment: { REA_LOG_LEVEL: "silent" }, }); - const response = await call("inspect_sqlite_database", { + const input = { path, schema_scope: "inventory", table: "records", columns, row_limit: 1, + }; + // Admit this fixture's array elements and root members so the test still + // reaches SQLite's own capacity boundary rather than transport admission. + const { call } = await connectLocalToolsMcp({ + REA_MCP_MAX_INPUT_ELEMENTS: String( + columns.length + Object.keys(input).length, + ), }); + const response = await call("inspect_sqlite_database", input); const expectedError = { code: "resource_constraint", category: "resource_constraint", diff --git a/tests/acceptance/tools/nativeFunctionMatching.test.ts b/tests/acceptance/tools/nativeFunctionMatching.test.ts index 20405c47466..5437eff8688 100644 --- a/tests/acceptance/tools/nativeFunctionMatching.test.ts +++ b/tests/acceptance/tools/nativeFunctionMatching.test.ts @@ -563,7 +563,11 @@ cliTest( cliTest( "native matching admits the request representation before authenticating observation carriers", async () => { - const { call } = await connectLocalToolsMcp(); + // Reach the native matching representation boundary with this intentionally + // oversized carrier fixture, rather than stopping at MCP's lower default. + const { call } = await connectLocalToolsMcp({ + REA_MCP_MAX_INPUT_ELEMENTS: "1048576", + }); const left = nativeMatchingInventory("1", [ { address: "0x10", value: "main" }, ]); diff --git a/tests/boundary/cli/workflowInputIdentities.test.ts b/tests/boundary/cli/workflowInputIdentities.test.ts index 6ad72d5cc38..ade06a0736d 100644 --- a/tests/boundary/cli/workflowInputIdentities.test.ts +++ b/tests/boundary/cli/workflowInputIdentities.test.ts @@ -1,5 +1,6 @@ import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { INLINE_EVIDENCE_MCP_ENVIRONMENT } from "../../../scripts/lib/mcp-verification-environment.mjs"; import { Ajv2020 } from "ajv/dist/2020.js"; import { mkdir, writeFile } from "node:fs/promises"; import { join, resolve } from "node:path"; @@ -53,6 +54,7 @@ const connectMcp = async (root: string) => { XDG_CONFIG_HOME: join(root, "config"), XDG_CACHE_HOME: join(root, "cache"), REA_LOG_LEVEL: "silent", + ...INLINE_EVIDENCE_MCP_ENVIRONMENT, }, }); onTestFinished(async () => { diff --git a/tests/boundary/mcp/analysisViewMcp.test.ts b/tests/boundary/mcp/analysisViewMcp.test.ts index ba0ea9d6ede..f288e1c5e58 100644 --- a/tests/boundary/mcp/analysisViewMcp.test.ts +++ b/tests/boundary/mcp/analysisViewMcp.test.ts @@ -75,6 +75,7 @@ afterAll(() => schemaValidation.clear()); const connect = async ( binaryLayout?: BinaryLayoutService, webNetworkCapture?: WebNetworkCaptureService, + maximumInputElements?: number, ) => { const session = createTestBinarySession(() => { throw new Error("selected views must not start a deep provider"); @@ -83,7 +84,13 @@ const connect = async ( { kind: "session", session }, { // These schema conformance cases exercise full nested constraints. - environment: { ...process.env, REA_MCP_INPUT_SCHEMA_PROFILE: "full" }, + environment: { + ...process.env, + REA_MCP_INPUT_SCHEMA_PROFILE: "full", + ...(maximumInputElements === undefined + ? {} + : { REA_MCP_MAX_INPUT_ELEMENTS: String(maximumInputElements) }), + }, ...(binaryLayout === undefined ? {} : { binaryLayout }), ...(webNetworkCapture === undefined ? {} : { webNetworkCapture }), }, @@ -812,7 +819,9 @@ it("rejects self-contained WASM and EVM Evidence views when the subject format d }); it("admits portable captures before SDK Evidence parsing and preserves capture caveats", async () => { - const { client } = await connect(); + // Reach portable-capture memory admission with the 100,000-header fixture; + // the lower transport default has separate coverage. + const { client } = await connect(undefined, undefined, 524_288); const dense = analysisViewCaptureEvidence(analysisViewObjectDenseCapture()); const refused = await client.callTool({ name: "inspect_analysis_view", @@ -1652,7 +1661,8 @@ it("advertises Mach-O pages whose selected facet owns their exact rows", async ( }); it("extracts an environment state identically from retained, portable and file MCP Evidence", async () => { - const { client, session } = await connect(); + // Full inline capture conformance explicitly selects its transport allowance. + const { client, session } = await connect(undefined, undefined, 8_192); const { ajv, inputSchema, outputSchema } = await advertisedMcpToolSchemas( client, "inspect_analysis_view", @@ -1726,7 +1736,7 @@ it("extracts an environment state identically from retained, portable and file M }); it("reports environment coverage identically from retained, portable and file MCP Evidence", async () => { - const { client, session } = await connect(); + const { client, session } = await connect(undefined, undefined, 8_192); const { ajv, inputSchema, outputSchema } = await advertisedMcpToolSchemas( client, "inspect_analysis_view", @@ -1772,7 +1782,7 @@ it("reports environment coverage identically from retained, portable and file MC }); it("projects an environment manifest identically from retained, portable and file MCP Evidence", async () => { - const { client, session } = await connect(); + const { client, session } = await connect(undefined, undefined, 8_192); const { ajv, inputSchema, outputSchema } = await advertisedMcpToolSchemas( client, "inspect_analysis_view", diff --git a/tests/boundary/mcp/artifactMcp.inlineInventory.test.ts b/tests/boundary/mcp/artifactMcp.inlineInventory.test.ts index 842c086e180..c5550c70471 100644 --- a/tests/boundary/mcp/artifactMcp.inlineInventory.test.ts +++ b/tests/boundary/mcp/artifactMcp.inlineInventory.test.ts @@ -1,4 +1,5 @@ import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { INLINE_EVIDENCE_MCP_ENVIRONMENT } from "../../../scripts/lib/mcp-verification-environment.mjs"; import { readFile, unlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; @@ -350,7 +351,11 @@ it.each(["full", "compact"] as const)( const server = createServer( { kind: "session", session }, { - environment: { ...process.env, REA_MCP_INPUT_SCHEMA_PROFILE: profile }, + environment: { + ...process.env, + ...INLINE_EVIDENCE_MCP_ENVIRONMENT, + REA_MCP_INPUT_SCHEMA_PROFILE: profile, + }, }, ); const client = new Client({ name: "artifact-inline-test", version: "1" }); diff --git a/tests/boundary/mcp/electronMcp.test.ts b/tests/boundary/mcp/electronMcp.test.ts index 7ab719aa3b6..8a45fff203b 100644 --- a/tests/boundary/mcp/electronMcp.test.ts +++ b/tests/boundary/mcp/electronMcp.test.ts @@ -20,6 +20,7 @@ import type { ElectronObservationPort } from "../../../src/application/javascrip import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js"; import { CdpElectronProvider } from "../../../src/browser/CdpElectronProvider.js"; import { createServer } from "../../../src/server/createServer.js"; +import { INLINE_EVIDENCE_MCP_ENVIRONMENT } from "../../../scripts/lib/mcp-verification-environment.mjs"; import { observed } from "../../fixtures/analysisExecution.js"; import { startFakeCdpBrowser, @@ -313,6 +314,7 @@ it("exposes endpoint-scoped Electron discovery and inspection as Evidence", asyn { kind: "session", session }, { electronObservation: new CdpElectronProvider(), + environment: { ...process.env, ...INLINE_EVIDENCE_MCP_ENVIRONMENT }, availabilityPolicy: () => ({ processCaptureEnabled: false, investigationInputRoots: 1, diff --git a/tests/boundary/mcp/processComparisonDiagnosticsMcp.test.ts b/tests/boundary/mcp/processComparisonDiagnosticsMcp.test.ts index d9554cd390d..8e2d88eca3b 100644 --- a/tests/boundary/mcp/processComparisonDiagnosticsMcp.test.ts +++ b/tests/boundary/mcp/processComparisonDiagnosticsMcp.test.ts @@ -64,8 +64,19 @@ const connect = async ( session = createTestBinarySession(() => { throw new Error("Process comparison must not launch a provider"); }), + maximumInputElements?: number, ) => { - const server = createServer({ kind: "session", session }); + const server = createServer( + { kind: "session", session }, + { + environment: { + ...process.env, + ...(maximumInputElements === undefined + ? {} + : { REA_MCP_MAX_INPUT_ELEMENTS: String(maximumInputElements) }), + }, + }, + ); const client = new Client({ name: "process-comparison-test", version: "1" }); onTestFinished(async () => { await Promise.allSettled([client.close(), server.close(), session.close()]); @@ -434,7 +445,9 @@ it("rejects a deep trace cycle as an input error through CLI and MCP", async () details: { issues: [issue] }, }); - const client = await connect(); + // This 6,000-event graph intentionally exercises cycle validation beyond + // ordinary transport admission. Keep a finite explicit fixture allowance. + const client = await connect(undefined, 131_072); const response = await client.callTool({ name: "compare_process_captures", arguments: { left: capture, right: capture, trace_spec: trace }, diff --git a/tests/boundary/mcp/processTraceAdaptersParity.test.ts b/tests/boundary/mcp/processTraceAdaptersParity.test.ts index e781ee9c302..89d8c899def 100644 --- a/tests/boundary/mcp/processTraceAdaptersParity.test.ts +++ b/tests/boundary/mcp/processTraceAdaptersParity.test.ts @@ -3,6 +3,7 @@ import { rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; +import { INLINE_EVIDENCE_MCP_ENVIRONMENT } from "../../../scripts/lib/mcp-verification-environment.mjs"; import { afterEach, describe, expect, it } from "vitest"; import { createTestBinarySession } from "../../fixtures/binarySession.js"; @@ -44,7 +45,10 @@ const comparisonClient = async ( ); expect(session.recordEvidence(left).ok).toBe(true); expect(session.recordEvidence(right).ok).toBe(true); - const server = createServer({ kind: "session", session }); + const server = createServer( + { kind: "session", session }, + { environment: { ...process.env, ...INLINE_EVIDENCE_MCP_ENVIRONMENT } }, + ); const client = new Client({ name: "trace-parity", version: "1" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/tests/boundary/mcp/sessionMcp.test.ts b/tests/boundary/mcp/sessionMcp.test.ts index 5a9d0278cd8..2ee8dd5bd78 100644 --- a/tests/boundary/mcp/sessionMcp.test.ts +++ b/tests/boundary/mcp/sessionMcp.test.ts @@ -719,6 +719,7 @@ describe("json depth bounds over MCP", () => { directory, provider, resources, + 4_096, ); const input = INVESTIGATION_EXAMPLES.compare_process_captures.input; const baseline = await mcp.callTool({ diff --git a/tests/boundary/mcp/sessionMcpHarness.ts b/tests/boundary/mcp/sessionMcpHarness.ts index f1bca7b54ce..c4e1ee7b977 100644 --- a/tests/boundary/mcp/sessionMcpHarness.ts +++ b/tests/boundary/mcp/sessionMcpHarness.ts @@ -71,6 +71,7 @@ export const createSessionMcpHarness = async ( root: string, provider: (closed: string[]) => AnalysisProvider, resources: Array<{ close(): Promise }>, + maximumInputElements?: number, ): Promise => { const first = join(root, "first.hop"); const second = join(root, "second.hop"); @@ -87,6 +88,14 @@ export const createSessionMcpHarness = async ( adbDeviceAnalysis, apktoolAnalysis, logger: silentLogger, + ...(maximumInputElements === undefined + ? {} + : { + environment: { + ...process.env, + REA_MCP_MAX_INPUT_ELEMENTS: String(maximumInputElements), + }, + }), }, ); const mcp = new Client({ name: "session-test", version: "1.0.0" }); diff --git a/tests/boundary/mcp/toolInputCapacityHttp.test.ts b/tests/boundary/mcp/toolInputCapacityHttp.test.ts new file mode 100644 index 00000000000..eb605eb8bab --- /dev/null +++ b/tests/boundary/mcp/toolInputCapacityHttp.test.ts @@ -0,0 +1,219 @@ +import { + Client, + StreamableHTTPClientTransport, +} from "@modelcontextprotocol/client"; +import { performance } from "node:perf_hooks"; +import { join } from "node:path"; +import { expect, onTestFinished } from "vitest"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { startListeningProcess } from "../../support/mcp/streamableHttpProcess.js"; +import { + processTest, + type TestProcesses, +} from "../../support/process/processFixture.js"; + +const openHttp = async ( + processes: TestProcesses, + maximum: string | undefined, + outputProfile: "full" | "off" = "full", +) => { + const root = await createTestTempDirectory("rea-input-capacity-http-"); + const { url, stderr, child } = await startListeningProcess( + processes, + ["mcp", "--http", "--port", "0"], + { + HOME: root, + USERPROFILE: root, + XDG_CONFIG_HOME: join(root, "config"), + XDG_CACHE_HOME: join(root, "cache"), + XDG_DATA_HOME: join(root, "data"), + NODE_OPTIONS: "--max-old-space-size=3072", + REA_MCP_OUTPUT_SCHEMA_PROFILE: outputProfile, + ...(maximum === undefined ? {} : { REA_MCP_MAX_INPUT_ELEMENTS: maximum }), + }, + ); + const client = new Client({ name: "input-capacity-http", version: "1" }); + const transport = new StreamableHTTPClientTransport(url, { + // SDK output-schema compilation can outlive an idle pooled socket on two + // CPUs. Keep this admission test independent of that client-side race. + requestInit: { headers: { Connection: "close" } }, + }); + onTestFinished(() => client.close()); + await client.connect(transport); + return { root, client, stderr, child }; +}; + +processTest( + "bounds HTTP validation before building amplified diagnostics and keeps serving", + async ({ processes }) => { + const { root, client, stderr, child } = await openHttp(processes, "8192"); + const catalog = await client.listTools(); + const declared = catalog.tools.find( + (tool) => tool.name === "compare_bundles", + ); + expect(declared?.inputSchema).toMatchObject({ type: "object" }); + const arguments_ = { + left_bundle_path: join(root, "absent-left"), + right_bundle_path: join(root, "absent-right"), + record_pairs: Array.from({ length: 8192 }, () => 0), + }; + const before = await client.callTool({ + name: "binary_session", + arguments: {}, + }); + expect(before.isError).not.toBe(true); + const observations: { code: string; bytes: number; elapsed_ms: number }[] = + []; + for (let repeat = 0; repeat < 2; repeat++) { + const start = performance.now(); + const result = await client + .callTool({ name: "compare_bundles", arguments: arguments_ }) + .catch((cause: unknown) => { + throw new Error( + `HTTP capacity probe failed; exit=${String(child.exitCode)} signal=${String(child.signalCode)}; listener diagnostic tail:\n${stderr().slice(-3000)}`, + { cause }, + ); + }); + const elapsed_ms = performance.now() - start; + const { error } = parseMcpToolError(result); + observations.push({ + code: error.code, + bytes: Buffer.byteLength(JSON.stringify(result)), + elapsed_ms, + }); + await client.ping(); + } + const healthy = await client.callTool({ + name: "binary_session", + arguments: {}, + }); + expect(healthy.isError).not.toBe(true); + console.info( + "MCP capacity completed-task observations", + JSON.stringify({ + request_json_bytes: Buffer.byteLength(JSON.stringify(arguments_)), + catalog_json_bytes: Buffer.byteLength(JSON.stringify(catalog)), + calls: observations, + model_tokens: "unmeasured", + }), + ); + for (const observed of observations) { + expect(observed.code).toBe("resource_constraint"); + expect(observed.bytes).toBeLessThan(4096); + } + }, + 90_000, +); + +processTest( + "bounds missing-field Evidence expansion at the default admission boundary", + async ({ processes }) => { + const { client } = await openHttp(processes, undefined, "off"); + const observations = []; + for (const count of [1_019, 1_020]) { + const arguments_ = { + functions: Array.from({ length: count }, () => ({})), + start: { address: "0x1" }, + goal: { address: "0x2" }, + }; + const start = performance.now(); + const result = await client.callTool({ + name: "build_call_path", + arguments: arguments_, + }); + const elapsed_ms = performance.now() - start; + const error = parseMcpToolError(result).error; + if (count === 1_019) { + // Three root members and two address members fill the remaining five. + // Keep ordinary canonical validation observable at the admitted edge. + expect(error.code).toBe("invalid_request"); + } else { + expect(error.code).toBe("resource_constraint"); + expect(error.details).toMatchObject({ + resource: "transport", + reported_limits: { max_input_elements: 1_024 }, + }); + expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThan(4096); + } + observations.push({ + count, + code: error.code, + argument_json_bytes: Buffer.byteLength(JSON.stringify(arguments_)), + response_json_bytes: Buffer.byteLength(JSON.stringify(result)), + elapsed_ms, + }); + await client.ping(); + } + const healthy = await client.callTool({ + name: "inspect_analysis_settings", + arguments: {}, + }); + expect(healthy.isError).not.toBe(true); + console.info( + "MCP structured admission boundary observations", + JSON.stringify(observations), + ); + }, + 90_000, +); + +processTest( + "refuses a sub-4MiB HTTP payload under the default allowance without expanded diagnostics", + async ({ processes }) => { + const { root, client } = await openHttp(processes, undefined, "off"); + const paths = { + left_bundle_path: join(root, "absent-left"), + right_bundle_path: join(root, "absent-right"), + }; + // Prove this exact server is guarded before constructing the larger probe. + // A missing/regressed guard therefore fails on the bounded small fixture. + const calibration = await client.callTool({ + name: "compare_bundles", + arguments: { + ...paths, + record_pairs: Array.from({ length: 1_024 }, () => 0), + }, + }); + const calibratedError = parseMcpToolError(calibration).error; + expect(calibratedError.code).toBe("resource_constraint"); + expect(calibratedError.details).toMatchObject({ + resource: "transport", + reported_limits: { max_input_elements: 1_024 }, + }); + const arguments_ = { + ...paths, + record_pairs: Array.from({ length: 2_090_000 }, () => 0), + }; + const argumentBytes = Buffer.byteLength(JSON.stringify(arguments_)); + expect(argumentBytes).toBeLessThan(4 * 1024 * 1024 - 4096); + const start = performance.now(); + const result = await client.callTool({ + name: "compare_bundles", + arguments: arguments_, + }); + const elapsed_ms = performance.now() - start; + const { error } = parseMcpToolError(result); + expect(error.code).toBe("resource_constraint"); + expect(error.details).toMatchObject({ + resource: "transport", + reported_limits: { max_input_elements: 1_024 }, + }); + expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThan(4096); + await client.ping(); + const healthy = await client.callTool({ + name: "inspect_analysis_settings", + arguments: {}, + }); + expect(healthy.isError).not.toBe(true); + console.info( + "MCP capacity guarded large probe", + JSON.stringify({ + argument_json_bytes: argumentBytes, + response_json_bytes: Buffer.byteLength(JSON.stringify(result)), + elapsed_ms, + }), + ); + }, + 90_000, +); diff --git a/tests/boundary/mcp/toolInputCapacityStdio.test.ts b/tests/boundary/mcp/toolInputCapacityStdio.test.ts new file mode 100644 index 00000000000..e766ed57ab9 --- /dev/null +++ b/tests/boundary/mcp/toolInputCapacityStdio.test.ts @@ -0,0 +1,58 @@ +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { join, resolve } from "node:path"; +import { expect, it, onTestFinished } from "vitest"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +it("applies the selected input allowance through the public deferred stdio entry point", async () => { + const root = await createTestTempDirectory("rea-input-capacity-stdio-"); + const transport = new StdioClientTransport({ + command: process.execPath, + args: [resolve("scripts/rea.mjs"), "mcp"], + env: { + PATH: process.env.PATH ?? "", + HOME: root, + USERPROFILE: root, + XDG_CONFIG_HOME: join(root, "config"), + XDG_CACHE_HOME: join(root, "cache"), + XDG_DATA_HOME: join(root, "data"), + HOPPER_LAUNCHER_PATH: "/rea-unconfigured-deep-provider/hopper", + NODE_OPTIONS: "--max-old-space-size=3072", + REA_LOG_LEVEL: "silent", + REA_MCP_MAX_INPUT_ELEMENTS: "8192", + }, + stderr: "pipe", + }); + transport.stderr?.on("data", () => undefined); + const client = new Client({ name: "input-capacity-stdio", version: "1" }); + onTestFinished(async () => { + try { + await client.close(); + } finally { + await transport.close(); + } + }); + await client.connect(transport); + const result = await client.callTool({ + name: "compare_bundles", + arguments: { + left_bundle_path: join(root, "absent-left"), + right_bundle_path: join(root, "absent-right"), + record_pairs: Array.from({ length: 8192 }, () => 0), + }, + }); + const { error } = parseMcpToolError(result); + expect(error.code).toBe("resource_constraint"); + expect(error.details).toMatchObject({ + resource: "transport", + reported_limits: { max_input_elements: 8192 }, + }); + expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThan(4096); + await client.ping(); + const healthy = await client.callTool({ + name: "inspect_analysis_settings", + arguments: {}, + }); + expect(healthy.isError).not.toBe(true); +}, 90_000); diff --git a/tests/fixtures/applicationMcpHarness.ts b/tests/fixtures/applicationMcpHarness.ts index 03ef8320df0..368a237d276 100644 --- a/tests/fixtures/applicationMcpHarness.ts +++ b/tests/fixtures/applicationMcpHarness.ts @@ -6,6 +6,7 @@ import { ok as resultOk } from "../../src/domain/result.js"; import { createTestBinarySession } from "./binarySession.js"; import type { BinarySession } from "../../src/application/binary/BinarySession.js"; import { observed } from "./analysisExecution.js"; +import { INLINE_EVIDENCE_MCP_ENVIRONMENT } from "../../scripts/lib/mcp-verification-environment.mjs"; import { createServer } from "../../src/server/createServer.js"; import { createTestMcp, @@ -19,7 +20,7 @@ export interface ApplicationMcpHarness { readonly close: () => Promise; } -/** Connect application workflows through the production MCP registration. */ +/** Connect complete-Evidence workflow fixtures through production registration. */ export async function createApplicationMcpHarness( options: { readonly session?: BinarySession; @@ -60,7 +61,13 @@ export async function createApplicationMcpHarness( options.registerCleanup?.(close); const server = createServer( { kind: "session", session }, - options.serverOptions, + { + ...options.serverOptions, + environment: { + ...INLINE_EVIDENCE_MCP_ENVIRONMENT, + ...(options.serverOptions?.environment ?? process.env), + }, + }, ); const client = await mcp.connect( server, diff --git a/tests/support/cli/cliFixture.ts b/tests/support/cli/cliFixture.ts index 545ac465a06..db955c3ca3d 100644 --- a/tests/support/cli/cliFixture.ts +++ b/tests/support/cli/cliFixture.ts @@ -1,5 +1,6 @@ import { resolve } from "node:path"; import { tmpdir } from "node:os"; +import { INLINE_EVIDENCE_MCP_ENVIRONMENT } from "../../../scripts/lib/mcp-verification-environment.mjs"; import { createTestWorkspace, @@ -196,7 +197,10 @@ const createFileMcpSession = ( await import("../../fixtures/localToolsMcp.js"); if (isClosed()) throw sharedMcpSessionClosed(); const mcp = await connectLocalToolsMcp( - { NODE_COMPILE_CACHE: compileCache }, + { + ...INLINE_EVIDENCE_MCP_ENVIRONMENT, + NODE_COMPILE_CACHE: compileCache, + }, registerCleanup, ); return mcp.call; diff --git a/tests/support/cli/javascriptApplication.ts b/tests/support/cli/javascriptApplication.ts index 186953cb91c..7d8ac90fe76 100644 --- a/tests/support/cli/javascriptApplication.ts +++ b/tests/support/cli/javascriptApplication.ts @@ -6,6 +6,7 @@ import { z } from "zod"; import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js"; import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; +import { INLINE_EVIDENCE_MCP_ENVIRONMENT } from "../../../scripts/lib/mcp-verification-environment.mjs"; import type { SharedMcpCall, TestCli } from "./cliFixture.js"; const execute = promisify(execFile); @@ -32,7 +33,7 @@ export const resolveJavaScriptApplicationMcpCall = async ( ): Promise => { if (mcpCall !== undefined) return mcpCall; if (cli.sharedMcpCall !== undefined) return cli.sharedMcpCall(); - return (await connectLocalToolsMcp()).call; + return (await connectLocalToolsMcp(INLINE_EVIDENCE_MCP_ENVIRONMENT)).call; }; /**