Skip to content
Merged
Next Next commit
fix(mcp)!: bound validation work before tool dispatch
Use the pinned SDK's element admission for eager and deferred MCP servers.
Share a finite configurable default across HTTP, stdio and saved setup env.
Normalize the SDK refusal with the configured limit and preserve canonical
schemas, ordinary diagnostics and admitted input values.

Fixes #7882

BREAKING CHANGE: MCP arguments now default to at most 65,536 combined array
elements and object members. Select REA_MCP_MAX_INPUT_ELEMENTS at launch for
workloads requiring a different finite allowance.

Assisted-by: Reimu (gensokyo-skills:reimu-incident-triage)
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
Assisted-by: Yukari (gensokyo-skills:yukari-boundary-analysis)
  • Loading branch information
gensokyo-dev committed Oct 28, 2026
commit fa183cd0753350c881249ab34c9dcfbdbe6a3872
2 changes: 1 addition & 1 deletion docs/client-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 26 additions & 0 deletions docs/mcp-contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,32 @@ 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 65,536 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.
This is a configurable transport admission policy, not a per-array `maxItems`
contract or an exact heap guarantee. On the pinned bundle schema, 65,537 scalar
failures added about 43 MiB of heap before SDK diagnostic formatting. The
default bounds this allocation source; 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
Expand Down
1 change: 1 addition & 0 deletions src/application/SetupRegistrationEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
18 changes: 18 additions & 0 deletions src/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions src/config/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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(),
Expand Down
46 changes: 46 additions & 0 deletions src/config/mcpInputBudget.test.ts
Original file line number Diff line number Diff line change
@@ -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"),
},
]);
});
34 changes: 34 additions & 0 deletions src/config/mcpInputBudget.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
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.
* 65,537 scalar failures on the pinned canonical bundle schema add about
* 43 MiB of heap before SDK formatting. Bound this expansion before parsing;
* operators may select a different finite allowance for their workload.
*/
export const DEFAULT_MCP_MAX_INPUT_ELEMENTS = 65_536;

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<number, ConfigurationError> => {
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 }],
}),
);
};
3 changes: 3 additions & 0 deletions src/config/parseConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }),
Expand Down
1 change: 1 addition & 0 deletions src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions src/main/deferredRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ export const runDeferred = async (
dependencies.setExitCode(1);
throw cause;
}),
config.mcpMaxInputElements,
);
return server;
});
Expand Down
29 changes: 29 additions & 0 deletions src/server/DeferredEvidenceMcpServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ const fixture = async (
readonly failLoad?: boolean;
readonly invalidOutput?: boolean;
readonly failAfterTool?: boolean;
readonly maximumInputElements?: number;
} = {},
) => {
const started = barrier();
Expand Down Expand Up @@ -138,6 +139,7 @@ const fixture = async (
);
});
},
options.maximumInputElements,
);
const client = new Client({ name: "deferred-fixture-client", version: "1" });
const [clientTransport, serverTransport] =
Expand All @@ -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 });
Expand Down
4 changes: 4 additions & 0 deletions src/server/DeferredEvidenceMcpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,16 @@ export class DeferredEvidenceMcpServer extends EvidenceMcpServerCore {
private readonly initialize: (
server: DeferredEvidenceMcpServer,
) => Promise<void>,
maximumInputElements?: number,
) {
super(
catalog.info,
{
capabilities: catalog.capabilities,
instructions: catalog.instructions,
...(maximumInputElements === undefined
? {}
: { maxToolInputElements: maximumInputElements }),
},
undefined,
delivery,
Expand Down
58 changes: 41 additions & 17 deletions src/server/EvidenceMcpServerCore.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -232,6 +233,7 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer {
private readonly compactPresentation:
| CompactInputSchemaPresentation
| undefined;
private readonly maximumInputElements: number;

constructor(
info: Implementation,
Expand All @@ -245,7 +247,10 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer {
| ReadonlySet<string>
| 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
Expand Down Expand Up @@ -334,6 +339,7 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer {
() => this.recordEvidence,
() => this.delivery,
this.outputSchemaProfile,
this.maximumInputElements,
),
);
}
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 &&
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading