mirror of
https://github.com/morluto/rea.git
synced 2026-11-16 19:53:50 +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.
178 lines
6.5 KiB
TypeScript
178 lines
6.5 KiB
TypeScript
import { unknownTarget } from "../../../src/domain/targetIdentity.js";
|
|
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
|
import type { CallToolResult } from "@modelcontextprotocol/server";
|
|
import { access, mkdir, rm, writeFile } from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
import { expect, it, vi } from "vitest";
|
|
import { createAnalysisExecution } from "../../../src/ports/AnalysisProvider.js";
|
|
import { BinarySession } from "../../../src/application/binary/BinarySession.js";
|
|
import { InvestigationRecords } from "../../../src/application/investigation/InvestigationRecords.js";
|
|
import { createEvidence } from "../../../src/domain/evidence.js";
|
|
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
|
|
import { err, ok } from "../../../src/domain/result.js";
|
|
import { createServer } from "../../../src/server/createServer.js";
|
|
import { createTestProviderRouter } from "../../fixtures/binarySession.js";
|
|
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
|
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
|
import { phaseGate } from "../../support/lifecycleHarness.js";
|
|
import { releaseOwnedCleanup } from "../../support/cleanupRelease.js";
|
|
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
|
|
|
|
const expectRecoveredBatch = (response: CallToolResult, owned: string) => {
|
|
expect(parseMcpToolError(response).error).toMatchObject({
|
|
code: "cleanup_incomplete",
|
|
details: {
|
|
resources: [owned],
|
|
partial_observation: {
|
|
evidence: {
|
|
normalized_result: { items: [{ status: "ok" }], total: 1 },
|
|
},
|
|
},
|
|
secondary_failures: expect.arrayContaining([
|
|
{
|
|
code: "resource_constraint",
|
|
category: "resource_constraint",
|
|
message: expect.any(String),
|
|
retryable: true,
|
|
remediation: expect.any(Object),
|
|
details: expect.objectContaining({ operation: "record_evidence" }),
|
|
},
|
|
]),
|
|
},
|
|
});
|
|
};
|
|
|
|
it("keeps a batch cleanup owner and its completed prefix after source retention fails", async () => {
|
|
const root = await createTestTempDirectory("rea-batch-owned-cleanup-");
|
|
const target = join(root, "fixture.com"),
|
|
owned = join(root, "owned");
|
|
await writeFile(target, Buffer.from([0xb8, 0, 0x4c, 0xcd, 0x21]));
|
|
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
|
const source = createEvidence(unknownTarget("not-observed"), provider, {
|
|
operation: "health",
|
|
parameters: {},
|
|
result: "source",
|
|
});
|
|
const failure = new ProviderCleanupError(provider.id, [owned], {
|
|
reason: "controlled cleanup failure",
|
|
});
|
|
let count = 0,
|
|
pending = false,
|
|
allow = false,
|
|
closes = 0;
|
|
const finalCleanup = phaseGate();
|
|
const session = new BinarySession(
|
|
createTestProviderRouter(() => ({
|
|
execute: async (operation) => {
|
|
if (operation === "procedure_pseudo_code" && ++count === 2) {
|
|
await mkdir(owned);
|
|
pending = true;
|
|
return err(failure);
|
|
}
|
|
return ok(
|
|
createAnalysisExecution(
|
|
operation === "procedure_address"
|
|
? "0x100"
|
|
: operation === "address_name"
|
|
? "example"
|
|
: operation === "health"
|
|
? null
|
|
: "int example(void) { return 1; }",
|
|
provider,
|
|
),
|
|
);
|
|
},
|
|
close: async () => {
|
|
closes++;
|
|
if (!pending) return ok(null);
|
|
if (closes === 2) {
|
|
await finalCleanup.hold();
|
|
return err(failure);
|
|
}
|
|
if (!allow) return err(failure);
|
|
await rm(owned, { recursive: true });
|
|
pending = false;
|
|
releaseOwnedCleanup(failure);
|
|
return ok(null);
|
|
},
|
|
})),
|
|
new InvestigationRecords({ maximumRepresentationBytes: 0 }),
|
|
);
|
|
const admit = session.withAdmittedAnalysis.bind(session);
|
|
vi.spyOn(session, "withAdmittedAnalysis").mockImplementation(
|
|
(operation, signal, run) =>
|
|
admit(operation, signal, (analysis) =>
|
|
run({
|
|
...analysis,
|
|
execute: async (...args) => {
|
|
const result = await analysis.execute(...args);
|
|
if (args[0] === "procedure_pseudo_code" && result.ok)
|
|
return {
|
|
...result,
|
|
value: { ...result.value, sourceEvidence: [source] },
|
|
};
|
|
return result;
|
|
},
|
|
}),
|
|
),
|
|
);
|
|
const server = createServer({ kind: "session", session });
|
|
const client = new Client(
|
|
{ name: "batch-owned-cleanup", version: "1" },
|
|
{ jsonSchemaValidator: createMcpSchemaValidation() },
|
|
);
|
|
const [ct, st] = InMemoryTransport.createLinkedPair();
|
|
try {
|
|
await server.connect(st);
|
|
await client.connect(ct);
|
|
const call = (name: string, args: Record<string, unknown> = {}) =>
|
|
client.callTool({ name, arguments: args }, { timeout: 120000 });
|
|
expect(
|
|
(await call("open_binary", { path: target, format: "dos-com" })).isError,
|
|
).not.toBe(true);
|
|
const response = await call("batch_decompile", {
|
|
addresses: ["first", "second"],
|
|
});
|
|
expectRecoveredBatch(response, owned);
|
|
expect(pending).toBe(true);
|
|
expect(failure.cleanupIncomplete).toBe(true);
|
|
await expect(access(owned)).resolves.toBeUndefined();
|
|
const close1 = await call("close_binary");
|
|
expect(close1.isError).toBe(true);
|
|
expect(parseMcpToolError(close1).error).toMatchObject({
|
|
code: "cleanup_incomplete",
|
|
recovery: { kind: "retry_cleanup", operation: "close_binary" },
|
|
details: { resources: [owned] },
|
|
});
|
|
expect(pending).toBe(true);
|
|
const controller = new AbortController();
|
|
const cancelledClose = client.callTool(
|
|
{ name: "close_binary", arguments: {} },
|
|
{ signal: controller.signal, timeout: 120000 },
|
|
);
|
|
try {
|
|
await finalCleanup.reached(cancelledClose, "final cleanup");
|
|
controller.abort();
|
|
await expect(cancelledClose).rejects.toThrow();
|
|
} finally {
|
|
controller.abort();
|
|
finalCleanup.release();
|
|
await Promise.allSettled([cancelledClose]);
|
|
}
|
|
allow = true;
|
|
const close2 = await call("close_binary");
|
|
expect(close2.isError).not.toBe(true);
|
|
expect(pending).toBe(false);
|
|
expect(failure.cleanupIncomplete).toBe(false);
|
|
expect(closes).toBe(3);
|
|
await expect(access(owned)).rejects.toThrow();
|
|
} finally {
|
|
allow = true;
|
|
finalCleanup.release();
|
|
await client.close();
|
|
await server.close();
|
|
await session.close();
|
|
vi.restoreAllMocks();
|
|
}
|
|
});
|