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

506 lines
17 KiB
TypeScript

import { unknownTarget } from "../../../src/domain/targetIdentity.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it, onTestFinished } from "vitest";
import { compareProcessCaptureFiles } from "../../support/cli/processComparisonCli.js";
import { PROCESS_PROVIDER } from "../../../src/domain/process/processEvidenceProvider.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
import {
FUNCTION_COMPARISON_EVIDENCE,
INVESTIGATION_EXAMPLES,
PROCESS_COMPARISON_EVIDENCE,
} from "../../../src/contracts/investigationExamples.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/domain/process/processCaptureExample.js";
import { findChangedBehavior } from "../../../src/domain/changedBehavior.js";
import {
createEvidence,
parseEvidence,
type Evidence,
evidenceSubjectInput,
} from "../../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { correlateStaticAndRuntime } from "../../../src/domain/staticRuntimeCorrelation.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { verifyReconstruction } from "../../../src/domain/reconstructionVerification.js";
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
const providerNames = [
"REA process capture",
"REA deterministic process harness",
];
const captureEvidence = (
side: "left" | "right",
result: Evidence["normalized_result"] = EMPTY_PROCESS_CAPTURE_EXAMPLE,
) =>
createEvidence(unknownTarget("not-observed"), PROCESS_PROVIDER, {
predicateType: "rea.process-capture",
operation: "capture_process_scenario",
parameters: { side },
result,
confidence: "observed",
authority: "controlled-replay",
environment: {
id: "fixture-process",
platform: "fixture",
architecture: "fixture",
isolation: "process",
},
});
const inlineEvidence = (response: { structuredContent?: unknown }) =>
parseEvidence(response.structuredContent);
const connectedComparison = async () => {
const session = createTestBinarySession(() => {
throw new Error("Process comparison must not launch a provider");
});
const server = createServer({ kind: "session", session });
const client = new Client(
{
name: "process-evidence-identity",
version: "1",
},
{ jsonSchemaValidator: createMcpSchemaValidation() },
);
onTestFinished(async () => {
await Promise.allSettled([client.close(), server.close(), session.close()]);
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
for (const evidence of [
FUNCTION_COMPARISON_EXAMPLE.left,
FUNCTION_COMPARISON_EXAMPLE.right,
FUNCTION_COMPARISON_EVIDENCE,
])
expect(session.recordEvidence(evidence).ok).toBe(true);
const left = captureEvidence("left");
const right = captureEvidence("right");
const response = await client.callTool({
name: "compare_process_captures",
arguments: { left, right },
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const comparison = inlineEvidence(response);
expect(comparison.provider).toEqual({
id: "rea-process",
name: "REA process capture",
version: "3",
});
expect(comparison.normalized_result).toMatchObject({ status: "unchanged" });
return { session, client, left, right, comparison };
};
const correlationInput = (comparison: Evidence) => {
const mapping =
INVESTIGATION_EXAMPLES.correlate_static_and_runtime.mappings[0];
if (mapping === undefined) throw new Error("Missing correlation mapping");
return {
static_comparisons: [FUNCTION_COMPARISON_EVIDENCE],
runtime_comparisons: [comparison],
mappings: [
{
...mapping,
runtime: {
...mapping.runtime,
comparison_evidence_id: comparison.evidence_id,
},
},
],
};
};
const specification = (comparison: Evidence) => ({
name: "Terminal compatibility",
claims: [
{
kind: "behavioral",
claim_id: "terminal-output",
title: "Terminal output remains equivalent",
comparison_evidence_id: comparison.evidence_id,
dimension: "terminal",
},
],
});
const consumerCalls = (comparison: Evidence) => [
{
name: "find_changed_behavior",
arguments: { comparisons: [comparison] },
expected: { behavior_status: "observed_unchanged" },
},
{
name: "correlate_static_and_runtime",
arguments: correlationInput(comparison),
expected: { status: "correlated" },
},
{
name: "verify_reconstruction",
arguments: { specification: specification(comparison) },
expected: { status: "pass" },
},
];
const expectConsumerResults = async (client: Client, comparison: Evidence) => {
for (const { expected, ...call } of consumerCalls(comparison)) {
const response = await client.callTool(call);
expect(
response.isError,
`${call.name}: ${JSON.stringify(response)}`,
).not.toBe(true);
expect(inlineEvidence(response).normalized_result).toMatchObject(expected);
}
};
it("feeds the exact public CLI/MCP process comparison into all three MCP consumers", async () => {
const { client, left, right, comparison } = await connectedComparison();
const root = await createTestTempDirectory("rea-process-identity-");
const leftPath = join(root, "left.json");
const rightPath = join(root, "right.json");
await Promise.all([
writeFile(leftPath, JSON.stringify(left)),
writeFile(rightPath, JSON.stringify(right)),
]);
const cliComparison = parseEvidence(
await compareProcessCaptureFiles(leftPath, rightPath),
);
expect(cliComparison).toEqual(comparison);
await expectConsumerResults(client, comparison);
});
it("compares exact retained capture Evidence without resending its payloads", async () => {
const { client, left, right, comparison } = await connectedComparison();
const response = await client.callTool({
name: "compare_process_captures",
arguments: {
left: { kind: "retained-evidence", evidence_id: left.evidence_id },
right: { kind: "retained-evidence", evidence_id: right.evidence_id },
},
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
expect(inlineEvidence(response)).toEqual(comparison);
});
it("advertises the same process comparison Evidence that its example inputs produce", async () => {
const { client } = await connectedComparison();
const response = await client.callTool({
name: "compare_process_captures",
arguments: INVESTIGATION_EXAMPLES.compare_process_captures.input,
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
expect(inlineEvidence(response)).toEqual(PROCESS_COMPARISON_EVIDENCE);
});
type IdentityChange = Partial<
Pick<
Evidence,
| "provider"
| "predicate_type"
| "operation"
| "subject"
| "confidence"
| "authority"
>
>;
// Use the public Evidence builder so each admission control has a valid digest.
const rehashedComparison = (
base: Evidence,
change: IdentityChange,
): Evidence => {
const next = { ...base, ...change };
return createEvidence(evidenceSubjectInput(next.subject), next.provider, {
predicateType: next.predicate_type,
operation: next.operation,
parameters: next.parameters,
result: next.normalized_result,
rawResult: next.raw_result,
confidence: next.confidence,
authority: next.authority,
environment: next.environment,
limitations: next.limitations,
locations: next.locations,
evidenceLinks: next.evidence_links,
});
};
it.each(providerNames)(
"admits the exact v3 provider name %s in every MCP consumer",
async (name) => {
const { session, client, comparison } = await connectedComparison();
const admitted = rehashedComparison(comparison, {
provider: { ...comparison.provider, name },
});
expect(parseEvidence(admitted)).toEqual(admitted);
expect(session.recordEvidence(admitted).ok).toBe(true);
await expectConsumerResults(client, admitted);
},
);
const DIGEST_MISMATCH_REASON =
/evidence_id.*semantic identifier.*does not match/i;
const identityMismatchReason = (tool: string): RegExp => {
switch (tool) {
case "find_changed_behavior":
return /comparison Evidence.*operation.*predicate.*provider.*disagree/i;
case "correlate_static_and_runtime":
return /comparison Evidence.*operation.*predicate.*provider.*citations.*disagree/i;
case "verify_reconstruction":
return /comparison Evidence.*identity.*authority.*disagrees/i;
default:
throw new Error(`Unexpected comparison consumer ${tool}`);
}
};
const unsupportedOperationIssue = (
tool: string,
): {
readonly path: readonly (string | number)[];
readonly message: RegExp;
} => {
switch (tool) {
case "find_changed_behavior":
return {
path: ["comparisons", 0],
message:
/changed.behavior.*requires.*process.*artifact.*function comparison Evidence/i,
};
case "correlate_static_and_runtime":
return {
path: ["runtime_comparisons", 0],
message:
/static\/runtime correlation.*requires.*process comparison Evidence/i,
};
case "verify_reconstruction":
return {
path: ["claims", 0, "comparison_evidence_id"],
message:
/terminal-output.*requires compare_process_captures Evidence.*fixture_comparison/i,
};
default:
throw new Error(`Unexpected comparison consumer ${tool}`);
}
};
const expectComparisonRejection = (
response: Parameters<typeof parseMcpToolError>[0],
tool: string,
kind: "identity" | "operation" | "digest",
) => {
if (kind === "operation") {
const issue = unsupportedOperationIssue(tool);
const parsed = parseMcpToolError(response);
expect(parsed.error.message).toMatch(issue.message);
expect(parsed, tool).toMatchObject({
error: {
code: "invalid_request",
category: "invalid_input",
message: parsed.error.message,
recovery: { kind: "inspect_input_contract", operation: tool },
details: {
operation: tool,
issues: [
{
path: [...issue.path],
reason: "invalid_value",
message: parsed.error.message,
},
],
},
},
});
return;
}
const reason =
kind === "digest" ? DIGEST_MISMATCH_REASON : identityMismatchReason(tool);
const parsed = parseMcpToolError(response);
expect(parsed.error.message).toMatch(reason);
expect(parsed, tool).toMatchObject({
error: {
code: "evidence_integrity_mismatch",
category: "integrity_mismatch",
details: { reason: parsed.error.message },
},
});
};
const invalidIdentities: ReadonlyArray<{
label: string;
kind: "identity" | "operation";
change: (base: Evidence) => IdentityChange;
}> = [
{
label: "wrong name",
kind: "identity",
change: ({ provider }) => ({
provider: { ...provider, name: `${provider.name} extra` },
}),
},
{
label: "wrong id",
kind: "identity",
change: ({ provider }) => ({
provider: { ...provider, id: "fixture-process" },
}),
},
{
label: "old version",
kind: "identity",
change: ({ provider }) => ({ provider: { ...provider, version: "2" } }),
},
{
label: "future version",
kind: "identity",
change: ({ provider }) => ({ provider: { ...provider, version: "4" } }),
},
{
label: "missing version",
kind: "identity",
change: ({ provider }) => ({ provider: { ...provider, version: null } }),
},
{
label: "wrong predicate",
kind: "identity",
change: () => ({ predicate_type: "fixture.comparison" }),
},
{
label: "wrong operation",
kind: "operation",
change: () => ({ operation: "fixture_comparison" }),
},
{
label: "non-null subject",
kind: "identity",
change: () => ({ subject: FUNCTION_COMPARISON_EXAMPLE.left.subject }),
},
{
label: "wrong confidence",
kind: "identity",
change: () => ({ confidence: "observed" }),
},
{
label: "wrong authority",
kind: "identity",
change: () => ({ authority: "controlled-replay" }),
},
];
for (const name of providerNames)
it.each(invalidIdentities)(
`rejects independently rehashed $label for ${name} in every MCP consumer`,
async ({ change, kind }) => {
const { session, client, comparison } = await connectedComparison();
const named = rehashedComparison(comparison, {
provider: { ...comparison.provider, name },
});
const invalid = rehashedComparison(named, change(named));
expect(invalid.evidence_id).not.toBe(named.evidence_id);
expect(parseEvidence(invalid)).toEqual(invalid);
expect(session.recordEvidence(invalid).ok).toBe(true);
for (const { expected: _expected, ...call } of consumerCalls(invalid)) {
const response = await client.callTool(call);
expect(response.isError, call.name).toBe(true);
expectComparisonRejection(response, call.name, kind);
}
},
);
it("separately rejects a tampered digest before admission to any consumer or session", async () => {
const { session, client, comparison } = await connectedComparison();
const tampered = {
...comparison,
provider: {
...comparison.provider,
name: "REA deterministic process harness",
},
};
const digestMismatch = /semantic identifier does not match/u;
expect(() => parseEvidence(tampered)).toThrow(digestMismatch);
expect(() => findChangedBehavior({ comparisons: [tampered] })).toThrow(
digestMismatch,
);
expect(() => correlateStaticAndRuntime(correlationInput(tampered))).toThrow(
digestMismatch,
);
const records = session
.exportEvidenceBundle()
.records.map((record) =>
record.evidence_id === tampered.evidence_id ? tampered : record,
);
expect(() =>
verifyReconstruction(
specification(tampered),
createEvidenceBundle(records),
),
).toThrow(digestMismatch);
expect(session.recordEvidence(tampered).ok).toBe(false);
for (const { expected: _expected, ...call } of consumerCalls(tampered).filter(
({ name }) => name !== "verify_reconstruction",
)) {
const response = await client.callTool(call);
expect(response.isError, call.name).toBe(true);
expectComparisonRejection(response, call.name, "digest");
}
});
it("maps malformed changed-behavior Evidence to an integrity mismatch before closure lookup", async () => {
const { client, comparison } = await connectedComparison();
const malformed = { ...comparison, evidence_links: undefined } as unknown;
const response = await client.callTool({
name: "find_changed_behavior",
arguments: { comparisons: [malformed] },
});
expect(response.isError).toBe(true);
const reason =
"Evidence validation failed at evidence_links: Invalid input: expected array, received undefined";
expect(parseMcpToolError(response)).toMatchObject({
error: {
code: "evidence_integrity_mismatch",
category: "integrity_mismatch",
message: reason,
details: { reason },
},
});
});
it("keeps withheld ownership unknown through CLI and MCP comparison", async () => {
const { client, right } = await connectedComparison();
const left = captureEvidence("left", {
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
cleanup: {
...EMPTY_PROCESS_CAPTURE_EXAMPLE.cleanup,
unverified_processes: [
{ pid: 900, reason: "platform_binary_environment_withheld" },
],
},
residual_unknowns: [
{ scope: "process", reason: "Ownership of process 900 was withheld" },
],
});
const response = await client.callTool({
name: "compare_process_captures",
arguments: { left, right },
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const comparison = inlineEvidence(response);
expect(comparison.normalized_result).toMatchObject({ status: "unknown" });
const root = await createTestTempDirectory("rea-withheld-ownership-");
const leftPath = join(root, "left.json");
const rightPath = join(root, "right.json");
await writeFile(leftPath, JSON.stringify(left));
await writeFile(rightPath, JSON.stringify(right));
expect(
parseEvidence(await compareProcessCaptureFiles(leftPath, rightPath)),
).toEqual(comparison);
});