Files
reverse-engineering-anything/tests/boundary/mcp/toolInputCapacityHttp.test.ts
T
morluto 858ff73880 perf(tests): give MCP test clients the shared lazy schema validation (#10960)
* perf(tests): give MCP test clients the shared lazy schema validation

The MCP SDK client compiles every listed tool's output schema on its
first tool call. With the SDK's default Ajv options, REA's catalog costs
gigabytes of allocation per client (inspect_analysis_view alone: 1.7 s and
~500 MiB retained), so native MCP files peaked at 1-2 GiB per worker.

tests/fixtures/mcpSchemaValidation already owns lazy, reference-preserving
validation. Route the native MCP, process-boundary and shared harness
clients through it, share compiled validators across clients in a worker
(bounded LRU keyed by schema text), and add a counted architecture guard so
default-validation test clients cannot spread; the remaining copies are the
baseline.

* fix(guards): read call arguments past parentheses inside string literals

* perf(tests): give MCP boundary test clients the shared schema validation (#11022)

* perf(tests): give MCP boundary test clients the shared schema validation

* perf(tests): give the remaining MCP test clients the shared schema validation (#11025)

* fix(guards): read an MCP client's validator option from parsed code

The default-validation counter searched each new Client(...) call's text for jsonSchemaValidator, so an inline comment, a string literal or a client name naming the option hid a default client. Parse the source with @babel/parser and count NewExpressions of Client whose object-literal arguments have no jsonSchemaValidator property; a source that does not parse counts every textual call. The guard reads raw test sources, and the generated-child-script allowlist entry, which no longer counts as a call, is removed.

* fix(guards): read an MCP client's options only from a whole object-literal argument

The default-validation counter skipped files without the text
'new Client(', so a comment between the tokens hid a client, and it took
any depth-two key as an option, so 'enabled ? { jsonSchemaValidator } : {}'
passed while its false branch uses the SDK default. The skip now only
requires the name Client, and the validator counts only when it is a key
of an object literal that is a whole argument; anything else counts as the
default.
2026-11-15 21:53:53 -05:00

231 lines
8.3 KiB
TypeScript

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";
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
const openHttp = async (
processes: TestProcesses,
maximum: string | undefined,
outputProfile: "compact" | "off" = "off",
) => {
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" },
{ jsonSchemaValidator: createMcpSchemaValidation() },
);
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);
}
},
);
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.
// Admitted source carriers reach the Evidence owner, which rejects
// the first invalid record without expanding every missing field.
expect(error).toMatchObject({
code: "evidence_integrity_mismatch",
category: "integrity_mismatch",
message: expect.stringContaining("at evidence_id"),
details: { diagnostics: { input_path: ["functions", 0] } },
});
} else {
expect(error.code).toBe("resource_constraint");
expect(error.remediation.action).toContain("retained-evidence");
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),
);
},
);
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.remediation.action).not.toContain(
"retained-evidence",
);
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,
}),
);
},
);