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

197 lines
6.7 KiB
TypeScript

import {
canonicalOutputSchema,
withCanonicalOutputSchema,
} from "../../fixtures/canonicalOutputSchema.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, expect, it } from "vitest";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import type {
AnalysisClient,
AnalysisOperationPort,
} from "../../../src/ports/AnalysisProvider.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import { createServer } from "../../../src/server/createServer.js";
import { advertiseTool } from "../../../src/contracts/advertisedTool.js";
import { advertisedInputJsonSchema } from "../../../src/contracts/toolSchemaMetadata.js";
import {
TOOL_CONTRACTS,
toolContract,
} from "../../../src/contracts/toolContracts.js";
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { advertisedToolPresentation } from "../../../src/contracts/mcpSchemaPresentation.js";
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
const resources: Array<{ close(): Promise<void> }> = [];
afterEach(async () => {
await Promise.all(
resources.splice(0).map(async (resource) => resource.close()),
);
});
const connect = async (analysis: AnalysisOperationPort) => {
const server = createServer({ kind: "fixed", analysis });
const client = new Client(
{
name: "integration-test",
version: "1.0.0",
},
{ jsonSchemaValidator: createMcpSchemaValidation() },
);
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
return client;
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (result.isError === true) return parseMcpToolError(result);
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
)
throw new Error("missing structured result");
return Object.fromEntries(Object.entries(result.structuredContent));
};
it("executes a realistic workflow: list methods, decompile selected, get xrefs", async () => {
const client = await connect({
execute: (name, args) => {
switch (name) {
case "list_procedures":
return Promise.resolve(
ok([
{ address: "0x1000", value: "main" },
{ address: "0x2000", value: "helper" },
]),
);
case "procedure_pseudo_code":
return Promise.resolve(
ok(`pseudo for ${(args as { procedure: string }).procedure}`),
);
case "xrefs":
return Promise.resolve(ok(["0x1000"]));
default:
throw new Error(`Unexpected analysis operation: ${name}`);
}
},
});
const listResult = await client.callTool({
name: "list_procedures",
arguments: {},
});
expect(listResult.isError).not.toBe(true);
expect(structured(listResult)).toMatchObject({
normalized_result: [
{ address: "0x1000", value: "main" },
{ address: "0x2000", value: "helper" },
],
});
const decompileResult = await client.callTool({
name: "procedure_pseudo_code",
arguments: { procedure: "0x1000" },
});
expect(structured(decompileResult)).toMatchObject({
normalized_result: "pseudo for 0x1000",
});
const xrefResult = await client.callTool({
name: "xrefs",
arguments: {},
});
expect(structured(xrefResult)).toMatchObject({
normalized_result: ["0x1000"],
});
});
it("advertises the complete currently available inventory with a session", async () => {
const session = createTestBinarySession(
(_path) =>
({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(resultOk(null)),
}) satisfies AnalysisClient,
);
const server = createServer({ kind: "session", session });
const client = new Client(
{
name: "integration-test",
version: "1.0.0",
},
{ jsonSchemaValidator: createMcpSchemaValidation() },
);
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
const listed = await client.listTools();
const names = listed.tools.map((t) => t.name);
const sessionTool = listed.tools.find(
({ name }) => name === "binary_session",
);
if (sessionTool === undefined)
throw new Error("Missing advertised binary_session tool");
// Validate this reply with its canonical output schema. The SDK otherwise
// builds output validators for the entire catalog on the first cached call.
const status = structured(
await client.callTool(
{ name: "binary_session", arguments: {} },
{ toolDefinition: withCanonicalOutputSchema(sessionTool) },
),
);
const inventory = expandToolAvailability(
toolContract("binary_session").outputSchema.parse(status).result
.tool_availability,
);
for (const availability of inventory) {
if (availability.available) continue;
expect(availability.reason).not.toBe("available");
expect(
availability.remediation?.trim().length,
availability.name,
).toBeGreaterThan(0);
}
const available = new Set(
inventory.filter((item) => item.available).map(({ name }) => name),
);
expect(new Set(names)).toEqual(
new Set(TOOL_CONTRACTS.map(({ name }) => name)),
);
expect(available).not.toContain("binary_overview");
expect(available).not.toContain("batch_decompile");
const contracts = new Map<string, (typeof TOOL_CONTRACTS)[number]>(
TOOL_CONTRACTS.map((contract) => [contract.name, contract]),
);
for (const tool of listed.tools) {
const contract = contracts.get(tool.name);
expect(contract, tool.name).toBeDefined();
expect(tool.title, tool.name).toBe(contract?.title);
// The default compact input profile moves input guidance from the schema
// to the end of the contract description.
if (contract === undefined) continue;
expect(tool.description, tool.name).toBe(
advertiseTool(
{
description: contract.description,
inputSchema: advertisedInputJsonSchema(contract),
},
advertisedToolPresentation("off"),
).description,
);
expect(tool.annotations, tool.name).toEqual(contract?.annotations);
expect(tool.inputSchema, tool.name).toBeDefined();
expect(canonicalOutputSchema(tool.name), tool.name).toBeDefined();
}
});