Files
reverse-engineering-anything/tests/boundary/mcp/nativeViewPredicateMcp.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

202 lines
7.1 KiB
TypeScript

import { fileSubjectTarget } from "../../fixtures/evidenceSubject.js";
import { unknownTarget } from "../../../src/domain/targetIdentity.js";
import {
canonicalOutputSchema,
withCanonicalOutputSchema,
} from "../../fixtures/canonicalOutputSchema.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
import {
createEvidence,
parseEvidence,
type Evidence,
} from "../../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
const fixture = FUNCTION_COMPARISON_EXAMPLE.left;
const subject = fileSubjectTarget(fixture.subject);
const selected = (
operation: string,
result: Evidence["normalized_result"],
predicateType: string,
) =>
createEvidence(subject, fixture.provider, {
operation,
parameters: {},
result,
predicateType,
confidence: "observed",
authority: "shipped-artifact",
});
const wrongMatchingPredicate = (matching: Evidence) =>
createEvidence(unknownTarget("not-observed"), matching.provider, {
operation: matching.operation,
parameters: matching.parameters,
result: matching.normalized_result,
predicateType: "rea.analysis",
confidence: matching.confidence,
authority: matching.authority,
evidenceLinks: matching.evidence_links,
});
it.each(["compact"] as const)(
"validates native parent predicates across public sources (%s schema)",
async (profile) => {
const session = createTestBinarySession(() => {
throw new Error("No provider should start");
});
const server = createServer(
{ kind: "session", session },
{
environment: { ...process.env, REA_MCP_OUTPUT_SCHEMA_PROFILE: profile },
},
);
const client = new Client(
{ name: "native-view-identity", version: "1" },
{ jsonSchemaValidator: createMcpSchemaValidation() },
);
const validation = createMcpSchemaValidation();
const [ct, st] = InMemoryTransport.createLinkedPair();
const root = await createTestTempDirectory("rea-native-view-identity-");
try {
await server.connect(st);
await client.connect(ct);
const definitions = new Map(
(await client.listTools()).tools.map((tool) => [tool.name, tool]),
);
const viewTool = definitions.get("inspect_analysis_view");
if (viewTool === undefined)
throw new Error("Missing advertised view schema");
expect(
validation.assertions.validateSchema(
canonicalOutputSchema(viewTool.name),
),
).toBe(true);
const call = (name: string, args: Record<string, unknown>) => {
const toolDefinition = definitions.get(name);
if (toolDefinition === undefined) throw new Error(`Missing ${name}`);
return client.callTool(
{ name, arguments: args },
{ toolDefinition: withCanonicalOutputSchema(toolDefinition) },
);
};
const inventory = selected(
"list_procedures",
[{ address: "0x1000", value: "main" }],
"rea.analysis",
);
const matchingResult = await call("match_native_functions", {
left: inventory,
right: inventory,
detail: "complete",
});
expect(
matchingResult.isError,
JSON.stringify(matchingResult.content),
).not.toBe(true);
const matching = parseEvidence(matchingResult.structuredContent);
expect(matching.predicate_type).toBe("rea.native-function-matching");
const wrongMatching = wrongMatchingPredicate(matching);
const graph = {
graph: {
"0": [
{
address: "0x1000",
status: "ok",
calls: [],
relationship_coverage: { status: "complete" },
},
],
},
limitations: [],
};
const cases = [
{
good: selected(
"analyze_function",
fixture.normalized_result,
"rea.analysis",
),
bad: selected(
"analyze_function",
fixture.normalized_result,
"rea.unrelated",
),
view: { kind: "summary" },
},
{
good: inventory,
bad: selected(
"list_procedures",
inventory.normalized_result,
"rea.unrelated",
),
view: { kind: "native-inventory", offset: 0, limit: 1 },
},
{
good: selected("procedure_address", "0x1000", "rea.analysis"),
bad: selected("procedure_address", "0x1000", "rea.unrelated"),
view: { kind: "native-observation", offset: 0, limit: 1 },
},
{
good: selected("get_call_graph", graph, "rea.analysis"),
bad: selected("get_call_graph", graph, "rea.unrelated"),
view: { kind: "native-observation", offset: 0, limit: 1 },
},
{ good: matching, bad: wrongMatching, view: { kind: "summary" } },
];
for (const [index, { good, bad, view }] of cases.entries()) {
expect(session.recordEvidence(good).ok).toBe(true);
expect(session.recordEvidence(bad).ok).toBe(true);
const goodReply = await call("inspect_analysis_view", {
source: { kind: "retained-evidence", evidence_id: good.evidence_id },
view,
});
expect(goodReply.isError, JSON.stringify(goodReply.content)).not.toBe(
true,
);
const goodView = parseEvidence(goodReply.structuredContent);
expect(goodView.evidence_links).toContain(good.evidence_id);
const raw = join(root, `${index}.json`),
bundle = join(root, `${index}-bundle.json`);
await writeFile(raw, JSON.stringify(bad));
await writeFile(bundle, JSON.stringify(createEvidenceBundle([bad])));
for (const source of [
{ kind: "inline", evidence: bad },
{ kind: "retained-evidence", evidence_id: bad.evidence_id },
{ kind: "evidence-file", path: raw },
{ kind: "evidence-file", path: bundle },
]) {
const reply = await call("inspect_analysis_view", { source, view });
expect(parseMcpToolError(reply).error).toMatchObject({
code: "invalid_request",
details: {
issues: [
expect.objectContaining({
path: ["source", "predicate_type"],
reason: "invalid_value",
}),
],
},
});
}
}
expect(session.activeTarget()).toBeUndefined();
} finally {
await client.close();
await server.close();
await session.close();
validation.clear();
}
},
);