mirror of
https://github.com/morluto/rea.git
synced 2026-11-21 06:04:03 +00:00
* 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.
273 lines
9.8 KiB
TypeScript
273 lines
9.8 KiB
TypeScript
import { withCanonicalOutputSchema } from "../../fixtures/canonicalOutputSchema.js";
|
|
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
|
import { createAnalysisExecution } from "../../../src/ports/AnalysisProvider.js";
|
|
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
|
import { createServer } from "../../../src/server/createServer.js";
|
|
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
|
|
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
|
import { ok } from "../../../src/domain/result.js";
|
|
import { z } from "zod";
|
|
import { afterAll, expect, it } from "vitest";
|
|
import { parseEvidence } from "../../../src/domain/evidence.js";
|
|
import { inspectAnalysisViewInputSchema } from "../../../src/domain/analysisView/analysisViewRequest.js";
|
|
import { analysisViewResultSchema } from "../../../src/domain/analysisView/analysisViewResult.js";
|
|
import { NATIVE_PRIMITIVE_OBSERVATION_OPERATIONS } from "../../../src/domain/native/nativeObservation.js";
|
|
import { connectGhidraMcp } from "./ghidraMcpHarness.js";
|
|
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
|
|
import { advertisedMcpToolSchemas } from "../../fixtures/advertisedMcpTool.js";
|
|
|
|
const validation = createMcpSchemaValidation();
|
|
afterAll(() => validation.clear());
|
|
|
|
it("delivers native primitive and graph summaries with exact retained parents and SDK-validated context pages", async () => {
|
|
const harness = await connectGhidraMcp("native-observation-views");
|
|
try {
|
|
const definitions = new Map(
|
|
(await harness.mcp.listTools()).tools.map((tool) => [tool.name, tool]),
|
|
);
|
|
const call = async (name: string, input: Record<string, unknown>) => {
|
|
const tool = definitions.get(name);
|
|
if (tool === undefined) throw new Error("Missing named contract");
|
|
const result = await harness.mcp.callTool(
|
|
{ name, arguments: input },
|
|
{ toolDefinition: withCanonicalOutputSchema(tool) },
|
|
);
|
|
expect(result.isError, JSON.stringify(result.content)).not.toBe(true);
|
|
return parseEvidence(result.structuredContent);
|
|
};
|
|
const viewSchemas = await advertisedMcpToolSchemas(
|
|
harness.mcp,
|
|
"inspect_analysis_view",
|
|
validation.assertions,
|
|
);
|
|
for (const operation of [
|
|
...NATIVE_PRIMITIVE_OBSERVATION_OPERATIONS,
|
|
"get_call_graph",
|
|
] as const) {
|
|
const input =
|
|
operation === "get_call_graph"
|
|
? { address: "fixture_main" }
|
|
: operation === "resolve_containing_procedure"
|
|
? { address: "0x401001" }
|
|
: { procedure: "fixture_main" };
|
|
const complete = await call(operation, input);
|
|
const summary = await call(operation, { ...input, detail: "summary" });
|
|
expect(complete.operation).toBe(operation);
|
|
expect(complete.parameters).not.toHaveProperty("detail");
|
|
expect(summary.normalized_result).toMatchObject({
|
|
kind: "summary",
|
|
parent_operation: operation,
|
|
parent_evidence_id: complete.evidence_id,
|
|
source_parameters: complete.parameters,
|
|
source_provider: complete.provider,
|
|
});
|
|
expect(harness.session.evidenceById(complete.evidence_id)).toEqual(
|
|
complete,
|
|
);
|
|
const calls = harness.calls.length;
|
|
const source = {
|
|
kind: "retained-evidence",
|
|
evidence_id: complete.evidence_id,
|
|
};
|
|
const page = await call("inspect_analysis_view", {
|
|
source,
|
|
view: { kind: "native-observation", offset: 0, limit: 1 },
|
|
});
|
|
const parsed = analysisViewResultSchema.parse(page.normalized_result);
|
|
expect(parsed).toMatchObject({
|
|
kind: "native-observation",
|
|
parent_evidence_id: complete.evidence_id,
|
|
});
|
|
for (const facet of [
|
|
"overview",
|
|
"analysis-profile",
|
|
"limitations",
|
|
"result-limitations",
|
|
]) {
|
|
const context = await call("inspect_analysis_view", {
|
|
source,
|
|
view: { kind: "native-context", facet, offset: 0, limit: 1 },
|
|
});
|
|
expect(context.relationship_coverage).toEqual(
|
|
complete.relationship_coverage,
|
|
);
|
|
expect(context.normalized_result).toMatchObject({
|
|
kind: "native-context",
|
|
facet,
|
|
parent_evidence_id: complete.evidence_id,
|
|
});
|
|
}
|
|
expect(harness.calls).toHaveLength(calls);
|
|
const invalid = {
|
|
source,
|
|
view: { kind: "native-context", facet: "unknown" },
|
|
};
|
|
expect(inspectAnalysisViewInputSchema.safeParse(invalid).success).toBe(
|
|
false,
|
|
);
|
|
const rejected = await harness.mcp.callTool(
|
|
{ name: "inspect_analysis_view", arguments: invalid },
|
|
{ toolDefinition: viewSchemas.toolDefinition },
|
|
);
|
|
expect(rejected.isError).toBe(true);
|
|
}
|
|
const references = await call("xrefs", { address: "0x401000" });
|
|
const source = {
|
|
kind: "retained-evidence",
|
|
evidence_id: references.evidence_id,
|
|
};
|
|
const before = harness.calls.length;
|
|
const page = await call("inspect_analysis_view", {
|
|
source,
|
|
view: { kind: "native-observation", offset: 0, limit: 1 },
|
|
});
|
|
expect(page.normalized_result).toMatchObject({
|
|
parent_evidence_id: references.evidence_id,
|
|
parent_operation: "xrefs",
|
|
items: {
|
|
type: "addresses",
|
|
rows: [{ source_index: 0, address: "0x401001" }],
|
|
},
|
|
coverage: { total: 1, exhausted: true },
|
|
});
|
|
expect(
|
|
analysisViewResultSchema.parse(page.normalized_result).unknowns,
|
|
).toEqual(
|
|
expect.arrayContaining([
|
|
expect.stringMatching(
|
|
/source addresses only.*reference kinds or provenance.*complete parent Evidence/iu,
|
|
),
|
|
]),
|
|
);
|
|
const caveats = await call("inspect_analysis_view", {
|
|
source,
|
|
view: { kind: "native-context", facet: "limitations" },
|
|
});
|
|
expect(caveats.normalized_result).toMatchObject({
|
|
parent_operation: "xrefs",
|
|
});
|
|
expect(harness.calls).toHaveLength(before);
|
|
} finally {
|
|
await harness.close();
|
|
}
|
|
});
|
|
|
|
it("follows native overflow continuations through MCP without repeating provider work", async () => {
|
|
let reads = 0;
|
|
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
|
const session = createTestBinarySession(() => ({
|
|
execute: async (operation) => {
|
|
reads++;
|
|
return ok(
|
|
createAnalysisExecution(
|
|
operation === "procedure_address"
|
|
? "0x1000"
|
|
: operation === "resolve_containing_procedure"
|
|
? {
|
|
query_address: "0x9999",
|
|
found: false,
|
|
procedure: null,
|
|
reason: "not_in_procedure",
|
|
}
|
|
: [],
|
|
provider,
|
|
{
|
|
limitations: ["Capacity fixture ".repeat(1500)],
|
|
relationshipCoverage: {
|
|
status: "partial",
|
|
limitations: ["Indirect edges unknown"],
|
|
discovery: {
|
|
callees: {
|
|
status: "partial",
|
|
reason: "Body was classified as data.",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
),
|
|
);
|
|
},
|
|
close: async () => ok(null),
|
|
}));
|
|
// Exercise the real delivery/SDK path with a small injected response budget.
|
|
const server = createServer(
|
|
{ kind: "session", session },
|
|
{ delivery: createToolResultDelivery(32 * 1024) },
|
|
);
|
|
const client = new Client(
|
|
{
|
|
name: "native-observation-capacity",
|
|
version: "1",
|
|
},
|
|
{ jsonSchemaValidator: createMcpSchemaValidation() },
|
|
);
|
|
const [clientTransport, serverTransport] =
|
|
InMemoryTransport.createLinkedPair();
|
|
try {
|
|
await server.connect(serverTransport);
|
|
await client.connect(clientTransport);
|
|
const opened = await client.callTool({
|
|
name: "open_binary",
|
|
arguments: { path: process.execPath },
|
|
});
|
|
expect(opened.isError).not.toBe(true);
|
|
for (const name of [
|
|
...NATIVE_PRIMITIVE_OBSERVATION_OPERATIONS,
|
|
"get_call_graph",
|
|
"xrefs",
|
|
] as const) {
|
|
const input =
|
|
name === "get_call_graph" ||
|
|
name === "resolve_containing_procedure" ||
|
|
name === "xrefs"
|
|
? { address: "0x1000" }
|
|
: { procedure: "fixture_main" };
|
|
const complete = await client.callTool({ name, arguments: input });
|
|
const error = parseMcpToolError(complete).error;
|
|
expect(error.code).toBe("resource_constraint");
|
|
const continuation = z
|
|
.object({
|
|
reported_limits: z.object({
|
|
continuation: z.object({
|
|
name: z.literal("inspect_analysis_view"),
|
|
arguments: inspectAnalysisViewInputSchema,
|
|
}),
|
|
}),
|
|
})
|
|
.parse(error.details).reported_limits.continuation;
|
|
expect(continuation.arguments.view.kind).toBe("native-observation");
|
|
const before = reads;
|
|
const page = await client.callTool(continuation);
|
|
expect(page.isError, JSON.stringify(page.content)).not.toBe(true);
|
|
const evidence = parseEvidence(page.structuredContent);
|
|
expect(evidence.normalized_result).toMatchObject({
|
|
kind: "native-observation",
|
|
parent_operation: name,
|
|
});
|
|
if (name === "get_call_graph")
|
|
expect(evidence.normalized_result).toMatchObject({
|
|
items: {
|
|
type: "graph-nodes",
|
|
rows: [
|
|
{
|
|
relationship_coverage: {
|
|
discovery: {
|
|
callees: {
|
|
status: "partial",
|
|
reason: "Body was classified as data.",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
],
|
|
},
|
|
});
|
|
expect(reads).toBe(before);
|
|
}
|
|
} finally {
|
|
await Promise.all([client.close(), server.close()]);
|
|
const closed = await session.close();
|
|
if (!closed.ok) throw closed.error;
|
|
}
|
|
});
|