chore: integrate canonical Evidence changes for MCP error delivery

This commit is contained in:
N0zoM1z0
2026-10-09 12:43:17 +00:00
643 changed files with 12727 additions and 10243 deletions
+1 -10
View File
@@ -247,16 +247,7 @@ describe("source-produced parser comparison known answers", () => {
const resultEvidence = (result: {
readonly structuredContent?: unknown;
}): Evidence => {
const content = result.structuredContent;
if (
content === null ||
typeof content !== "object" ||
!("evidence" in content)
)
throw new TypeError("Missing produced MCP Evidence");
return parseEvidence(content.evidence);
};
}): Evidence => parseEvidence(result.structuredContent);
const toolEvent = (id: string, tool: string, result: unknown) => ({
type: "item.completed",
+11 -10
View File
@@ -100,16 +100,16 @@ it("advertises exact schemas and projects one layout section from retained Evide
const parsed = toolContract("inspect_analysis_view").outputSchema.parse(
response.structuredContent,
);
expect(parsed.result).toMatchObject({
expect(parsed.normalized_result).toMatchObject({
kind: "item",
parent_evidence_id: parent.evidence_id,
item: { name: { display: ".data" } },
});
expect(parsed.result).toEqual(
parseEvidence(parsed.evidence).normalized_result,
expect(parsed.normalized_result).toEqual(
parseEvidence(parsed).normalized_result,
);
expect(session.evidenceById(parsed.evidence_id)).toEqual(
parseEvidence(parsed.evidence),
parseEvidence(parsed),
);
});
@@ -118,7 +118,7 @@ it("retains an oversized selected observation and keeps subsequent views usable"
const analysis = analysisViewJavaScriptAnalysisWithSource();
const original = analysis.graph.nodes[0];
if (original === undefined) throw new Error("missing module");
const source = "\0".repeat(500_000);
const source = "\0".repeat(1_000_000);
const node = createJavaScriptApplicationNode({
kind: original.kind,
identity: original.identity,
@@ -207,12 +207,12 @@ it("returns a JavaScript summary without graph payloads from a retained referenc
const parsed = toolContract("inspect_analysis_view").outputSchema.parse(
response.structuredContent,
);
expect(parsed.result).toMatchObject({
expect(parsed.normalized_result).toMatchObject({
kind: "summary",
parent_operation: "analyze_javascript_application",
summary: { format: "directory" },
});
expect(parsed.result).not.toHaveProperty("summary.semantic_graph");
expect(parsed.normalized_result).not.toHaveProperty("summary.semantic_graph");
const stale = await client.callTool({
name: "inspect_analysis_view",
arguments: {
@@ -252,13 +252,14 @@ it("accepts a transport-constraint retained reference as the view source", async
const parsed = toolContract("inspect_analysis_view").outputSchema.parse(
response.structuredContent,
);
expect(parsed.result).toMatchObject({
expect(parsed.normalized_result).toMatchObject({
kind: "page",
parent_evidence_id: parent.evidence_id,
coverage: { exhausted: true },
});
if (parsed.result.kind !== "page") throw new Error("expected page view");
expect(parsed.result.items).toEqual([
if (parsed.normalized_result.kind !== "page")
throw new Error("expected page view");
expect(parsed.normalized_result.items).toEqual([
{
node_id: expect.any(String),
kind: "javascript-asset",
@@ -25,7 +25,7 @@ async function runInlineEvidenceScenarios(
});
expect(traced.isError).not.toBe(true);
expect(traced.structuredContent).toMatchObject({
result: {
normalized_result: {
seed: { kind: "module", value: "renderer.js", match: "exact" },
summary: { matched_seeds: 1, traced_nodes: 1, unknown_facts: 0 },
coverage: {
@@ -44,7 +44,7 @@ async function runInlineEvidenceScenarios(
});
expect(compared.isError).not.toBe(true);
expect(compared.structuredContent).toMatchObject({
result: {
normalized_result: {
summary: { unchanged: 0, added: 2, removed: 0, changed: 1, unknown: 0 },
coverage: {
left_graph_status: "complete",
@@ -63,7 +63,7 @@ async function runInlineEvidenceScenarios(
});
expect(sourceCompared.isError).not.toBe(true);
expect(sourceCompared.structuredContent).toMatchObject({
result: {
normalized_result: {
reference: {
root_sha256: SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference.root_sha256,
},
@@ -84,7 +84,7 @@ async function runInlineWorkflowScenarios(
});
expect(tracedInline.isError).not.toBe(true);
expect(tracedInline.structuredContent).toMatchObject({
result: {
normalized_result: {
seed: { kind: "module", value: "renderer.js", match: "exact" },
summary: { matched_seeds: 1, traced_nodes: 1, unknown_facts: 0 },
coverage: {
@@ -103,7 +103,7 @@ async function runInlineWorkflowScenarios(
});
expect(comparedInline).toMatchObject({
structuredContent: {
result: {
normalized_result: {
evidence_links: expect.arrayContaining([
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left.evidence_id,
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right.evidence_id,
@@ -131,7 +131,7 @@ async function runInlineWorkflowScenarios(
});
expect(sourceComparedById.isError).not.toBe(true);
expect(sourceComparedById.structuredContent).toMatchObject({
result: {
normalized_result: {
reference: {
root_sha256: SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference.root_sha256,
inventory_state: "complete",
@@ -41,7 +41,7 @@ it("executes the advertised export presence example with matching analyzed Evide
});
expect(response.isError).not.toBe(true);
expect(response.structuredContent).toMatchObject({
result: {
normalized_result: {
left: { status: "selected" },
right: { status: "selected" },
summary: { added: 1, removed: 1, changed: 0, unknown: 0 },
@@ -102,7 +102,7 @@ it("traces example semantic modules with their parsed artifact digests", async (
});
expect(response.isError).not.toBe(true);
expect(response.structuredContent).toMatchObject({
result: {
normalized_result: {
nodes: expect.arrayContaining([
expect.objectContaining({
node_id: module.node_id,
@@ -161,10 +161,8 @@ describe("application workflow MCP parity", () => {
expect(relativeApplication.isError).not.toBe(true);
expect(relativeApplication.structuredContent).toMatchObject({
evidence_id: left.value.evidence_id,
result: { input_path: leftAnalysis.input_path },
evidence: {
subject: { local_path: left.value.subject?.local_path },
},
normalized_result: { input_path: leftAnalysis.input_path },
subject: { local_path: left.value.subject?.local_path },
});
const full = await client.callTool({
name: "compare_javascript_export_shapes",
@@ -172,7 +170,7 @@ describe("application workflow MCP parity", () => {
});
expect(full.isError).not.toBe(true);
expect(full.structuredContent).toMatchObject({
result: {
normalized_result: {
summary: { added: 1, removed: 0, changed: 0, unknown: 0 },
property_inventories: expect.arrayContaining([
expect.objectContaining({
@@ -231,7 +229,7 @@ describe("application workflow MCP parity", () => {
});
expect(semantic.isError).not.toBe(true);
expect(semantic.structuredContent).toMatchObject({
result: {
normalized_result: {
source_evidence_id: left.value.evidence_id,
source_graph_id: analyzed.semantic_graph.graph_id,
summary: { total_seed_matches: 1 },
@@ -1,7 +1,11 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished } from "vitest";
import { z } from "zod";
import { parseEvidence } from "../../../src/domain/evidence.js";
import {
javaScriptExportShapeComparisonResultSchema,
projectedExportReturnShapesSchema,
} from "../../../src/domain/javascript/javascriptExportShapeComparisonSchemas.js";
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
@@ -28,6 +32,18 @@ it.each([
mutation: "result.count = query();",
uncertainPresence: true,
},
{
title: "a known property after an unknown spread",
initializer: '{ ...dynamic, kind: "r", count: 1 }',
mutation: "",
uncertainPresence: false,
},
{
title: "an unknown spread after a known property",
initializer: '{ count: 1, ...dynamic, kind: "r" }',
mutation: "",
uncertainPresence: false,
},
{
title: "an unresolved value with known presence",
initializer: '{ kind: "r", count: query() }',
@@ -83,9 +99,9 @@ it.each([
},
});
expect(response.isError).not.toBe(true);
const { result } = z
.object({ result: javaScriptSemanticTraceResultSchema })
.parse(response.structuredContent);
const result = javaScriptSemanticTraceResultSchema.parse(
parseEvidence(response.structuredContent).normalized_result,
);
const nodeIds = result.nodes.map(({ node_id }) => node_id);
expect(nodeIds).toContain(known.node_id);
expect(nodeIds.includes(uncertain.node_id)).toBe(
@@ -111,3 +127,192 @@ it.each([
}
},
);
const analyzedSource = async (source: string) => {
const root = await createTestTempDirectory("rea-property-facts-mcp-");
await writeFile(join(root, "parser.mjs"), source);
const analyzed = await analyzeJavaScriptApplication({ input_path: root });
if (!analyzed.ok) throw analyzed.error;
return {
evidence: analyzed.value,
...javascriptApplicationAnalysisResultSchema.parse(
analyzed.value.normalized_result,
),
};
};
it("selects full nested property paths through authenticated MCP semantic traces", async () => {
const application = await analyzedSource(`
const root = {a:{id:'left'}, b:{id:'right'}, 'a.id':'dotted', '': {'a/b~c':'escaped'}};
const left = root.a.id;
const right = root['b'].id;
const missing = root.id;
const dotted = root['a.id'];
const escaped = root['']['a/b~c'];
`);
const { client, close } = await createApplicationMcpHarness();
onTestFinished(close);
for (const [pointer, expected] of [
["/a/id", "left"],
["/b/id", "right"],
["/a.id", "dotted"],
["//a~1b~0c", "escaped"],
["/id", null],
]) {
const slot = application.semantic_graph.nodes.find(
({ kind, properties }) =>
kind === "property-slot" && properties.property_pointer === pointer,
);
if (slot === undefined) throw new Error(`Missing property ${pointer}`);
const response = await client.callTool({
name: "trace_javascript_semantics",
arguments: {
application: application.evidence,
query: {
seed: { kind: "semantic-node", node_id: slot.node_id },
direction: "backward-provenance",
allowed_relations: ["defines"],
},
},
});
expect(response.isError).not.toBe(true);
const trace = javaScriptSemanticTraceResultSchema.parse(
parseEvidence(response.structuredContent).normalized_result,
);
expect(
trace.nodes
.filter(({ kind }) => kind === "literal")
.map(({ properties }) => properties.value),
).toEqual(expected === null ? [] : [expected]);
const reads = application.semantic_graph.relations.filter(
({ source_node_id, relation }) =>
source_node_id === slot.node_id && relation === "reads-property",
);
expect(reads).toHaveLength(1);
expect(reads[0]?.resolution).toBe(
expected === null ? "candidate" : "resolved",
);
}
});
it.each([
{
title: "spread before an explicit field",
body: 'const result = {...dynamic, kind:"r", count:1};',
path: "/count",
presence: "present",
valueState: "literal",
change: "changed",
baseline: 'const result = {kind:"r",count:2};',
},
{
title: "spread after an explicit field",
body: 'const result = {count:1, ...dynamic, kind:"r"};',
path: "/count",
presence: "present",
valueState: "unknown",
change: "unknown",
baseline: 'const result = {kind:"r",count:2};',
},
{
title: "deletion",
body: 'const result = {kind:"r",count:1}; delete result.count;',
path: "/count",
presence: "unknown-coverage",
valueState: "unknown",
change: "unknown",
baseline: 'const result = {kind:"r",count:2};',
},
{
title: "uncertain mutation",
body: 'const result = {kind:"r"}; if(flag) result.count=2;',
path: "/count",
presence: "unknown-coverage",
valueState: "unknown",
change: "unknown",
baseline: 'const result = {kind:"r",count:2};',
},
{
title: "an array hole",
body: 'const result = {kind:"r",items:[,]};',
path: "/items/0",
presence: "absent",
valueState: "unknown",
change: "added",
baseline: 'const result = {kind:"r",items:[2]};',
},
])(
"agrees on slot presence across export comparison and semantic tracing for $title",
async ({ body, path, presence, valueState, change, baseline }) => {
const left = await analyzedSource(
`export default function make() { ${body} return result; }`,
);
const right = await analyzedSource(
`export default function make() { ${baseline} return result; }`,
);
const slot = left.semantic_graph.nodes.find(
({ kind, properties }) =>
kind === "property-slot" && properties.property_pointer === path,
);
if (slot === undefined) throw new Error(`Missing property ${path}`);
expect(slot.properties).toMatchObject({
presence,
value_status: valueState,
});
const observation = left.graph.nodes
.flatMap(({ observations }) => observations)
.find(
({ properties }) => properties.semantic_role === "export-return-shapes",
);
const projection = projectedExportReturnShapesSchema.parse(
observation?.properties,
);
expect(projection.static_return_shapes[0]?.fields).toContainEqual(
expect.objectContaining({ path, presence, state: valueState }),
);
const { client, close } = await createApplicationMcpHarness();
onTestFinished(close);
const traced = await client.callTool({
name: "trace_javascript_semantics",
arguments: {
application: left.evidence,
query: {
seed: { kind: "semantic-node", node_id: slot.node_id },
direction: "backward-provenance",
allowed_relations: ["defines"],
},
},
});
expect(traced.isError).not.toBe(true);
const trace = javaScriptSemanticTraceResultSchema.parse(
parseEvidence(traced.structuredContent).normalized_result,
);
expect(
trace.nodes
.filter(({ kind }) => kind === "literal")
.map(({ properties }) => properties.value),
).toEqual(valueState === "literal" ? [1] : []);
const compared = await client.callTool({
name: "compare_javascript_export_shapes",
arguments: {
left: left.evidence,
right: right.evidence,
left_module_path: "parser.mjs",
left_export_name: "default",
right_module_path: "parser.mjs",
right_export_name: "default",
},
});
expect(compared.isError).not.toBe(true);
const comparison = javaScriptExportShapeComparisonResultSchema.parse(
parseEvidence(compared.structuredContent).normalized_result,
);
expect(comparison.changes).toContainEqual(
expect.objectContaining({
path,
status: change,
presence: { left: presence, right: "present" },
}),
);
},
);
@@ -25,7 +25,7 @@ it("inspects a standalone keyed archive through MCP with original object identit
),
),
);
const session = createTestBinarySession(new ArtifactProvider());
const session = createTestBinarySession(new ArtifactProvider(process.env));
const server = createServer(session, session);
const client = new Client({ name: "keyed-mcp-test", version: "1" });
const [clientTransport, serverTransport] =
@@ -46,7 +46,9 @@ it("inspects a standalone keyed archive through MCP with original object identit
true,
);
const graph = keyedArchiveResultSchema.parse(
z.object({ result: z.unknown() }).parse(called.structuredContent).result,
z
.object({ normalized_result: z.unknown() })
.parse(called.structuredContent).normalized_result,
);
expect(graph.references).toEqual(
expect.arrayContaining([
@@ -116,7 +118,7 @@ it("returns all 520 ZIP file occurrences in one inspect_artifact MCP result", as
);
await writeFile(archive, await writer.close());
const session = createTestBinarySession(new ArtifactProvider());
const session = createTestBinarySession(new ArtifactProvider(process.env));
const server = createServer(session, session);
const client = new Client({ name: "artifact-inline-test", version: "1" });
const [clientTransport, serverTransport] =
@@ -149,8 +151,9 @@ it("returns all 520 ZIP file occurrences in one inspect_artifact MCP result", as
),
})
.parse(
z.object({ result: z.unknown() }).parse(result.structuredContent)
.result,
z
.object({ normalized_result: z.unknown() })
.parse(result.structuredContent).normalized_result,
);
expect(
inspection.substeps[0]?.evidence.normalized_result.occurrences,
+28 -28
View File
@@ -1,4 +1,6 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -44,7 +46,7 @@ it.each([
await writeFile(archive, bytes);
}
const session = createTestBinarySession(new ArtifactProvider());
const session = createTestBinarySession(new ArtifactProvider(process.env));
const server = createServer(session, session);
const client = new Client({ name: "asar-integrity-test", version: "1" });
const [clientTransport, serverTransport] =
@@ -114,7 +116,7 @@ it("extracts an active archive through MCP when requested", async () => {
await zip.add("main.js", new TextReader("console.log('extract');\n"));
await writeFile(archive, await zip.close());
const session = createTestBinarySession(new ArtifactProvider());
const session = createTestBinarySession(new ArtifactProvider(process.env));
const server = createServer(session, session);
const client = new Client({ name: "artifact-extract-test", version: "1" });
const [clientTransport, serverTransport] =
@@ -136,7 +138,7 @@ it("extracts an active archive through MCP when requested", async () => {
expect(result.isError).not.toBe(true);
const normalized = z
.object({ output_root: z.string(), artifacts: z.array(z.unknown()) })
.parse(compactResult(result.structuredContent).result);
.parse(toolEvidence(result.structuredContent).normalized_result);
outputRoot = normalized.output_root;
expect(await readFile(join(outputRoot, "main.js"), "utf8")).toBe(
"console.log('extract');\n",
@@ -163,7 +165,7 @@ it("extracts a macOS app bundle through MCP", async () => {
header.writeUInt32LE(2, 12);
await writeFile(join(contents, "MacOS", "Fixture"), header);
const session = createTestBinarySession(new ArtifactProvider());
const session = createTestBinarySession(new ArtifactProvider(process.env));
const server = createServer(session, session);
const client = new Client({
name: "artifact-extract-app-test",
@@ -188,7 +190,7 @@ it("extracts a macOS app bundle through MCP", async () => {
expect(result.isError).not.toBe(true);
const normalized = z
.object({ output_root: z.string() })
.parse(compactResult(result.structuredContent).result);
.parse(toolEvidence(result.structuredContent).normalized_result);
outputRoot = normalized.output_root;
expect(
await readFile(join(outputRoot, "Contents", "Info.plist"), "utf8"),
@@ -222,7 +224,7 @@ it("records an explicitly continued mismatch, preserves verified siblings, and n
bytes.write(secondChanged, secondOffset, "utf8");
await writeFile(archive, bytes);
const session = createTestBinarySession(new ArtifactProvider());
const session = createTestBinarySession(new ArtifactProvider(process.env));
const server = createServer(session, session);
const client = new Client({ name: "asar-continue-test", version: "1" });
const [clientTransport, serverTransport] =
@@ -243,7 +245,7 @@ it("records an explicitly continued mismatch, preserves verified siblings, and n
expect(result.isError, JSON.stringify(result.structuredContent)).not.toBe(
true,
);
const compact = compactResult(result.structuredContent);
const compact = toolEvidence(result.structuredContent);
const evidence = session.evidenceById(compact.evidence_id);
if (evidence === undefined) throw new Error("missing inventory Evidence");
const inspection = z
@@ -255,7 +257,7 @@ it("records an explicitly continued mismatch, preserves verified siblings, and n
}),
),
})
.parse(compact.result);
.parse(compact.normalized_result);
const inventory = artifactInventoryResultSchema.parse(
inspection.substeps[0]?.evidence.normalized_result,
);
@@ -296,7 +298,9 @@ it("records an explicitly continued mismatch, preserves verified siblings, and n
},
});
expect(compared.isError).not.toBe(true);
expect(compactResult(compared.structuredContent).result).toMatchObject({
expect(
toolEvidence(compared.structuredContent).normalized_result,
).toMatchObject({
status: "contradiction",
summary: { contradiction: 2 },
changes: expect.arrayContaining([
@@ -320,7 +324,7 @@ it("rejects inline artifact Evidence whose content does not match its ID", async
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer(session, session);
const client = new Client({
@@ -358,7 +362,7 @@ it("compares inline inventory Evidence without prior session calls", async () =>
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer(session, session);
const client = new Client({
@@ -377,7 +381,9 @@ it("compares inline inventory Evidence without prior session calls", async () =>
expect(result.isError, JSON.stringify(result.structuredContent)).not.toBe(
true,
);
expect(compactResult(result.structuredContent).result).toMatchObject({
expect(
toolEvidence(result.structuredContent).normalized_result,
).toMatchObject({
status: "changed",
});
expect(
@@ -404,7 +410,7 @@ it("returns full artifact graphs inline and compares changed inventories", async
new TextReader("changed();"),
);
await writeFile(changedArchive, await changedWriter.close());
const session = createTestBinarySession(new ArtifactProvider());
const session = createTestBinarySession(new ArtifactProvider(process.env));
const server = createServer(session, session);
const client = new Client({ name: "artifact-mcp-test", version: "1" });
const [clientTransport, serverTransport] =
@@ -422,7 +428,7 @@ it("returns full artifact graphs inline and compares changed inventories", async
arguments: {},
});
expect(inspected.isError).not.toBe(true);
const inspectionResult = compactResult(inspected.structuredContent);
const inspectionResult = toolEvidence(inspected.structuredContent);
const inspectionEvidence = session.evidenceById(
inspectionResult.evidence_id,
);
@@ -441,7 +447,7 @@ it("returns full artifact graphs inline and compares changed inventories", async
substeps_completed: z.literal(1),
}),
})
.parse(inspectionResult.result);
.parse(inspectionResult.normalized_result);
expect(inspection.substeps).toHaveLength(1);
expect(
session.evidenceById(inspection.substeps[0]?.evidence_id ?? ""),
@@ -454,7 +460,7 @@ it("returns full artifact graphs inline and compares changed inventories", async
arguments: {},
});
expect(inventory.isError).not.toBe(true);
const inventoryResult = compactResult(inventory.structuredContent);
const inventoryResult = toolEvidence(inventory.structuredContent);
const evidence = session.evidenceById(inventoryResult.evidence_id);
if (evidence === undefined) throw new Error("missing inventory Evidence");
expect(evidence).toMatchObject({
@@ -465,7 +471,7 @@ it("returns full artifact graphs inline and compares changed inventories", async
.object({
substeps: z.array(z.object({ evidence: z.unknown() })),
})
.parse(inventoryResult.result);
.parse(inventoryResult.normalized_result);
const inventoryEvidence = z
.object({
normalized_result: z.object({
@@ -490,12 +496,12 @@ it("returns full artifact graphs inline and compares changed inventories", async
name: "inspect_artifact",
arguments: {},
});
const changedResult = compactResult(changedInventory.structuredContent);
const changedResult = toolEvidence(changedInventory.structuredContent);
const changedInspection = z
.object({
substeps: z.array(z.object({ evidence: z.unknown() })),
})
.parse(changedResult.result);
.parse(changedResult.normalized_result);
const compared = await client.callTool({
name: "compare_artifacts",
arguments: {
@@ -504,8 +510,8 @@ it("returns full artifact graphs inline and compares changed inventories", async
},
});
expect(compared.isError).not.toBe(true);
expect(compactResult(compared.structuredContent)).toMatchObject({
result: { status: "changed" },
expect(toolEvidence(compared.structuredContent)).toMatchObject({
normalized_result: { status: "changed" },
evidence_id: expect.stringMatching(/^ev_/u),
});
const unknowns = await client.callTool({
@@ -526,10 +532,4 @@ it("returns full artifact graphs inline and compares changed inventories", async
}
});
const compactResult = (value: unknown) =>
z
.object({
result: z.unknown(),
evidence_id: z.string(),
})
.parse(value);
const toolEvidence = (value: unknown) => parseEvidence(value);
@@ -61,9 +61,11 @@ it("advertises exact valid schemas and records inline layout without a binary ta
const parsed = toolContract("inspect_binary_layout").outputSchema.parse(
response.structuredContent,
);
const evidence = parseEvidence(parsed.evidence);
expect(parsed.result).toEqual(value);
expect(parsed.result).toEqual(evidence.normalized_result);
const evidence = parseEvidence(parsed);
expect(evidence.confidence).toBe("observed");
expect(evidence.subject?.digest.sha256).toBe(value.artifact.sha256);
expect(parsed.normalized_result).toEqual(value);
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
const viewed = await client.callTool({
name: "inspect_analysis_view",
@@ -79,7 +81,7 @@ it("advertises exact valid schemas and records inline layout without a binary ta
expect(
toolContract("inspect_analysis_view").outputSchema.parse(
viewed.structuredContent,
).result,
).normalized_result,
).toMatchObject({
kind: "summary",
parent_evidence_id: evidence.evidence_id,
@@ -0,0 +1,156 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import {
McpServer,
STDIO_DEFAULT_MAX_BUFFER_SIZE,
} from "@modelcontextprotocol/server";
import { Ajv2020 } from "ajv/dist/2020.js";
import { describe, expect, it } from "vitest";
import { compareWebCaptureEvidence } from "../../../src/application/BrowserObservationService.js";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import {
browserCaptureComparisonInputSchema,
compareBrowserCaptures,
} from "../../../src/domain/browserCaptureComparison.js";
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
import { browserScenarioCaptureSchema } from "../../../src/domain/browserScenarioCapture.js";
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
const delivery = new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE);
const contract = toolContract("compare_web_captures");
describe("browser comparison input boundary", () => {
it("advertises complete producer captures and agrees with SDK validation on both comparison families", async () => {
const browser = await startFakeCdpBrowser({ sensitiveShapes: true });
const server = new McpServer({ name: "capture-input", version: "0" });
const client = new Client({ name: "capture-input", version: "0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
let calls = 0;
const provider = new CdpBrowserProvider();
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async (input) => {
calls += 1;
const compared = await compareWebCaptureEvidence(provider, input);
return compared.ok
? delivery.toEvidenceToolResult(compared.value, contract, undefined)
: delivery.toErrorToolResult(compared.error);
},
);
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = (await client.listTools()).tools.find(
({ name }) => name === contract.name,
);
if (advertised === undefined) throw new Error("Missing comparison tool");
expect(advertised.inputSchema.type).toBe("object");
expect(advertised.inputSchema.anyOf).toHaveLength(2);
const ajv = new Ajv2020({ strict: false, validateFormats: false });
expect(ajv.validateSchema(advertised.inputSchema)).toBe(true);
const validate = ajv.compile(advertised.inputSchema);
const produced = await provider.inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
target_id: "allowed-page",
observation_ms: 0,
include_json_body_shapes: true,
include_websocket_shapes: true,
}),
);
if (!produced.ok) throw produced.error;
const passive = {
before: { inspection: produced.value },
after: { inspection: produced.value },
};
const scenario = contract.examples[0]?.input;
if (scenario === undefined) throw new Error("Missing scenario example");
const withoutNormalization = Object.fromEntries(
Object.entries(scenario).filter(([key]) => key !== "normalization"),
);
const scenarioCapture = browserScenarioCaptureSchema.parse(
scenario.before_scenario,
);
const invalid = [
{},
{ before: passive.before },
{ before: { inspection: {} }, after: passive.after },
{
before: passive.before,
after: { inspection: produced.value, webmcp: {} },
},
{ before_scenario: {}, after_scenario: {} },
{ before_scenario: scenario.before_scenario },
{ ...passive, ...scenario },
{ ...passive, normalization: { rules: [] } },
{ ...passive, unexpected: true },
{
...scenario,
before_scenario: { ...scenarioCapture, steps: [{}] },
},
{
...scenario,
normalization: {
rules: [
{ rule_id: "bad", artifacts: [], match: "x", replacement: "y" },
],
},
},
];
const cases = [
...[passive, scenario, withoutNormalization].map((input) => ({
input,
expected: true,
})),
...invalid.map((input) => ({ input, expected: false })),
];
for (const { input, expected } of cases) {
expect(validate(input), JSON.stringify(validate.errors)).toBe(expected);
expect(
browserCaptureComparisonInputSchema.safeParse(input).success,
).toBe(expected);
const beforeCalls = calls;
const result = await client.callTool({
name: contract.name,
arguments: input,
});
expect(calls - beforeCalls).toBe(expected ? 1 : 0);
expect(result.isError === true).toBe(!expected);
if (expected)
expect(result.structuredContent).toMatchObject({
operation: contract.name,
normalized_result: compareBrowserCaptures(
browserCaptureComparisonInputSchema.parse(input),
),
});
}
const parsedPassive = browserCaptureComparisonInputSchema.parse(passive);
expect(parsedPassive).toEqual({
before: { inspection: produced.value, webmcp: null },
after: { inspection: produced.value, webmcp: null },
});
expect(compareBrowserCaptures(parsedPassive).overall_status).toBe(
"unknown",
);
const parsedScenario =
browserCaptureComparisonInputSchema.parse(withoutNormalization);
expect(parsedScenario).toHaveProperty("normalization", { rules: [] });
expect(compareBrowserCaptures(parsedScenario)).toMatchObject({
comparison_kind: "browser_scenario",
overall_status: "unchanged",
});
} finally {
await Promise.allSettled([
client.close(),
server.close(),
browser.close(),
]);
}
});
});
+25 -33
View File
@@ -1,7 +1,8 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, expect, it } from "vitest";
import { z } from "zod";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
@@ -35,7 +36,7 @@ it(
sensitiveShapes: true,
});
browsers.push(browser);
const connected = await connectBrowser(browser);
const connected = await connectBrowser();
const tools = await connected.client.listTools();
expect(tools.tools).toHaveLength(TOOL_CONTRACTS.length);
@@ -73,7 +74,7 @@ it(
});
expect(listed.isError).not.toBe(true);
expect(listed.structuredContent).toMatchObject({
result: {
normalized_result: {
targets: expect.arrayContaining([
expect.objectContaining({ target_id: "allowed-page" }),
]),
@@ -93,7 +94,7 @@ it(
});
expect(inspected.isError).not.toBe(true);
expect(inspected.structuredContent).toMatchObject({
result: {
normalized_result: {
target: { target_id: "allowed-page" },
console: { prior_activity_available: false },
network: {
@@ -115,7 +116,7 @@ it(
});
expect(reconciled.isError).not.toBe(true);
expect(reconciled.structuredContent).toMatchObject({
result: { summary: { runtime_scripts: 1 } },
normalized_result: { summary: { runtime_scripts: 1 } },
});
expect(JSON.stringify(reconciled.structuredContent)).not.toContain(
"source-secret",
@@ -130,7 +131,7 @@ it(
});
expect(analyzed.isError).not.toBe(true);
expect(analyzed.structuredContent).toMatchObject({
result: {
normalized_result: {
capture: { scripts_analyzed: 1 },
observations: { source_maps: { status: "not_requested" } },
},
@@ -156,7 +157,7 @@ const verifySessionAndComparisonTools = async (
});
expect(observedSession.isError).not.toBe(true);
expect(observedSession.structuredContent).toMatchObject({
result: {
normalized_result: {
window: { end_reason: "window_elapsed" },
timeline: expect.arrayContaining([
expect.objectContaining({ type: "same_origin_reload" }),
@@ -174,7 +175,7 @@ const verifySessionAndComparisonTools = async (
});
expect(webMcp.isError).not.toBe(true);
expect(webMcp.structuredContent).toMatchObject({
result: {
normalized_result: {
tools: {
items: [expect.objectContaining({ name: "search_orders" })],
},
@@ -190,7 +191,7 @@ const verifySessionAndComparisonTools = async (
});
expect(compared.isError).not.toBe(true);
expect(compared.structuredContent).toMatchObject({
result: { overall_status: "unknown" },
normalized_result: { overall_status: "unknown" },
});
const parsedCapture = webPageInspectionSchema.parse(capture);
const socket = parsedCapture.network.websocket_events.find(
@@ -250,22 +251,20 @@ const verifySessionAndComparisonTools = async (
});
expect(visual.isError).not.toBe(true);
expect(visual.structuredContent).toMatchObject({
result: { status: "identical", changed_pixels: 0 },
normalized_result: { status: "identical", changed_pixels: 0 },
});
expect(inspected.structuredContent).toMatchObject({
result: expect.any(Object),
evidence: {
operation: "inspect_web_page",
predicate_type: expect.any(String),
parameters: expect.any(Object),
},
normalized_result: expect.any(Object),
operation: "inspect_web_page",
predicate_type: expect.any(String),
parameters: expect.any(Object),
});
};
it("does not attach to a target outside the request's allowed origin scope", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const connected = await connectBrowser(browser);
const connected = await connectBrowser();
const result = await connected.client.callTool({
name: "inspect_web_page",
arguments: {
@@ -287,10 +286,10 @@ it("does not attach to a target outside the request's allowed origin scope", asy
expect(browser.commands).toHaveLength(0);
});
const connectBrowser = async (browser: FakeCdpBrowser) => {
const connectBrowser = async () => {
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer(session, session, {
browserObservation: new CdpBrowserProvider(),
@@ -309,24 +308,17 @@ const connectBrowser = async (browser: FakeCdpBrowser) => {
};
const normalizedResultOf = (value: unknown): unknown => {
if (typeof value !== "object" || value === null || !("result" in value))
if (
typeof value !== "object" ||
value === null ||
!("normalized_result" in value)
)
throw new TypeError("Missing normalized browser result");
return value.result;
return value.normalized_result;
};
const evidenceFor = (value: unknown) => {
const parsed = z
.object({
evidence_id: z.string(),
result: z.unknown(),
evidence: z.object({}).passthrough(),
})
.parse(value);
return {
...parsed.evidence,
evidence_id: parsed.evidence_id,
normalized_result: parsed.result,
};
return parseEvidence(value);
};
const artifactOf = (value: unknown): unknown => {
+66 -9
View File
@@ -1,5 +1,6 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, describe, expect, test } from "vitest";
import { Ajv2020 } from "ajv/dist/2020.js";
import type { BrowserScenarioCapturePort } from "../../../src/application/BrowserScenarioCapturePort.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
@@ -83,6 +84,7 @@ const captureFor = (scenario: BrowserScenario): BrowserScenarioCapture => {
start_origin: new URL(start).origin,
action_count: scenario.actions.length,
secret_references: scenario.secrets.map(({ secret_id: id }) => id),
network_content: scenario.capture.network,
},
duration_ms: 2,
steps: [
@@ -119,12 +121,37 @@ const minimalScenario = (origin = "https://app.example.test") => ({
const scenario = (origin = "https://app.example.test") => ({
...minimalScenario(origin),
start_url: {
url: `${origin}/?token=caller-selected`,
query: [
{ name: "login", value: { source: "secret", secret_id: "login_input" } },
{ name: "mode", value: { source: "literal", value: "account" } },
],
},
storage: {
local_storage: [
{
origin,
entries: [
{
name: "session",
value: { source: "secret", secret_id: "login_input" },
},
{
name: "view",
value: { source: "literal", value: "token=selected" },
},
],
},
],
},
actions: [
{
step_id: "login-input",
action: "fill",
locator: { kind: "test_id", value: "password" },
value: { source: "secret", secret_id: "login_input" },
timeout_ms: 1_234,
},
],
secrets: [
@@ -146,7 +173,7 @@ describe("browser scenario MCP tool", () => {
const provider = new FakeBrowserScenarioProvider();
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(ok(null)),
}));
const server = createServer(session, session, {
browserObservation: new CdpBrowserProvider(),
@@ -180,7 +207,7 @@ describe("browser scenario MCP tool", () => {
});
expect(captured.isError, JSON.stringify(captured)).not.toBe(true);
expect(captured.structuredContent).toMatchObject({
result: {
normalized_result: {
scenario: {
secret_references: ["login_input"],
},
@@ -188,27 +215,57 @@ describe("browser scenario MCP tool", () => {
});
expect(provider.scenarios).toHaveLength(2);
expect(captured.structuredContent).toMatchObject({
evidence: {
predicate_type: "rea.browser-scenario-capture",
operation: "capture_browser_scenario",
parameters: expect.any(Object),
predicate_type: "rea.browser-scenario-capture",
operation: "capture_browser_scenario",
parameters: {
...provider.scenarios[1],
scenario_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
},
});
const captureResult = Reflect.get(
captured.structuredContent ?? {},
"result",
"normalized_result",
);
const comparisonInput = {
before_scenario: captureResult,
after_scenario: captureResult,
normalization: { rules: [] },
};
const comparisonTool = (await client.listTools()).tools.find(
({ name }) => name === "compare_web_captures",
);
if (comparisonTool === undefined)
throw new Error("Missing comparison tool");
const validateComparison = new Ajv2020({
strict: false,
validateFormats: false,
}).compile(comparisonTool.inputSchema);
expect(
validateComparison(comparisonInput),
JSON.stringify(validateComparison.errors),
).toBe(true);
for (const malformed of [
{ before_scenario: captureResult },
{ before_scenario: captureResult, after: captureResult },
{ ...comparisonInput, before: captureResult, after: captureResult },
]) {
expect(validateComparison(malformed)).toBe(false);
const rejected = await client.callTool({
name: "compare_web_captures",
arguments: malformed,
});
expect(rejected.isError).toBe(true);
}
const compared = await client.callTool({
name: "compare_web_captures",
arguments: {
before_scenario: captureResult,
after_scenario: captureResult,
normalization: { rules: [] },
},
});
expect(compared.isError, JSON.stringify(compared)).not.toBe(true);
expect(compared.structuredContent).toMatchObject({
result: {
normalized_result: {
comparison_kind: "browser_scenario",
overall_status: "unchanged",
alignment: { status: "aligned", aligned_steps: 2 },
@@ -1,4 +1,5 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -37,7 +38,7 @@ const sourceEvidence = (label: string) =>
);
describe("bundle comparison MCP integration", () => {
it("reads caller-selected bundle files and records a compact result", async () => {
it("reads caller-selected bundle files and returns complete Evidence", async () => {
const root = await createTestTempDirectory("rea-bundle-mcp-");
roots.push(root);
const leftPath = join(root, "left.json");
@@ -71,7 +72,7 @@ describe("bundle comparison MCP integration", () => {
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
result: { status: "changed" },
normalized_result: { status: "changed" },
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
});
} finally {
@@ -101,7 +102,7 @@ describe("bundle comparison MCP integration", () => {
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
result: { status: "unchanged" },
normalized_result: { status: "unchanged" },
});
} finally {
await connected.close();
@@ -149,7 +150,7 @@ const connect = async () => {
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer(session, session);
const client = new Client({ name: "bundle-comparison-test", version: "1" });
@@ -1,6 +1,5 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it, onTestFinished } from "vitest";
import { z } from "zod";
import { ARTIFACT_COMPARISON_EXAMPLE } from "../../../src/contracts/artifactComparisonExample.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
@@ -70,7 +69,7 @@ it("retains one open unknown for an incomplete artifact compared with itself", a
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
expect(response.structuredContent).toMatchObject({
result: { status: "truncated" },
normalized_result: { status: "truncated" },
});
expect(session.listUnknowns({ domain: "artifact-comparison" })).toMatchObject(
[
@@ -106,7 +105,7 @@ it.each([
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
expect(response.structuredContent).toMatchObject({
result: { status: "changed" },
normalized_result: { status: "changed" },
});
}
expect(session.listUnknowns({ domain })).toHaveLength(2);
@@ -116,10 +115,7 @@ it.each([
arguments: { left: pair.left, right },
});
expect(repeated.isError, JSON.stringify(repeated)).not.toBe(true);
const compared = parseEvidence(
z.object({ evidence: z.unknown() }).parse(repeated.structuredContent)
.evidence,
);
const compared = parseEvidence(repeated.structuredContent);
expect(session.evidenceById(compared.evidence_id)).toEqual(compared);
expect(session.exportEvidenceBundle()).toEqual(before);
},
@@ -0,0 +1,56 @@
import { execFile } from "node:child_process";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { z } from "zod";
import { GENERATED_MCP_TOOL_CATALOG } from "../../fixtures/mcpToolCatalog.js";
const execute = promisify(execFile);
const fixture = fileURLToPath(
new URL("../../fixtures/contractPresentation.mjs", import.meta.url),
);
const resultSchema = z.object({
catalog: z.array(
z.object({
name: z.string(),
inputSchema: z.record(z.string(), z.unknown()),
outputSchema: z.record(z.string(), z.unknown()),
}),
),
responses: z.array(
z.object({ name: z.string(), response: z.record(z.string(), z.unknown()) }),
),
});
it("preserves advertised schemas and handler meaning when presentation order changes", async () => {
const { stdout } = await execute(process.execPath, [fixture, "reversed"], {
timeout: 20_000,
maxBuffer: 16 * 1024 * 1024,
});
const result = resultSchema.parse(JSON.parse(stdout));
expect(result.catalog).toHaveLength(GENERATED_MCP_TOOL_CATALOG.length);
expect(new Set(result.catalog.map(({ name }) => name))).toEqual(
new Set(GENERATED_MCP_TOOL_CATALOG.map(({ name }) => name)),
);
for (const advertised of result.catalog) {
const canonical = GENERATED_MCP_TOOL_CATALOG.find(
({ name }) => name === advertised.name,
);
expect(advertised.inputSchema).toEqual(canonical?.inputSchema);
expect(advertised.outputSchema).toEqual(canonical?.outputSchema);
}
for (const { name, response } of result.responses) {
if (name === "reconcile_javascript_runtime") {
expect(response.isError).not.toBe(true);
expect(response.structuredContent).toMatchObject({
operation: name,
});
} else {
expect(response.isError, name).toBe(true);
expect(response.structuredContent, name).toMatchObject({
error: { details: { operation: name } },
});
}
}
});
@@ -24,7 +24,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const withClient = async (
verify: (client: Client) => Promise<void>,
): Promise<void> => {
const session = createTestBinarySession(new ArtifactProvider());
const session = createTestBinarySession(new ArtifactProvider(process.env));
const server = createServer(session, session);
const client = new Client({ name: "dylib-mcp-test", version: "1" });
const [clientTransport, serverTransport] =
@@ -40,7 +40,7 @@ const withClient = async (
};
const structuredResult = (value: unknown): unknown =>
z.object({ result: z.unknown() }).parse(value).result;
z.object({ normalized_result: z.unknown() }).parse(value).normalized_result;
it("traces dylib resolution for an opened app bundle and rejects a changed target", async () => {
const app = join(
+52 -39
View File
@@ -1,3 +1,5 @@
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import { rm, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
@@ -50,11 +52,25 @@ it("exposes endpoint-scoped Electron discovery and inspection as Evidence", asyn
await writeFile(join(root, "worker.js"), "self.onmessage = () => {};\n");
const browser = await startFakeCdpBrowser({
electronFileUrl: pathToFileURL(join(root, "index.html")).href,
commandEvents: ({ method }) =>
method === "Debugger.enable"
? [
{
method: "Debugger.scriptParsed",
sessionId: "session-1",
params: {
scriptId: "partial-script",
url: pathToFileURL(join(root, "app.js")).href,
executionContextId: 1,
},
},
]
: undefined,
});
browsers.push(browser);
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer(session, session, {
electronObservation: new CdpElectronProvider(),
@@ -78,7 +94,7 @@ it("exposes endpoint-scoped Electron discovery and inspection as Evidence", asyn
});
expect(listed.isError).not.toBe(true);
expect(listed.structuredContent).toMatchObject({
result: {
normalized_result: {
targets: [{ target_id: "electron-page" }],
},
});
@@ -97,7 +113,9 @@ it("exposes endpoint-scoped Electron discovery and inspection as Evidence", asyn
});
expect(analyzed.isError).not.toBe(true);
expect(analyzed.structuredContent).toMatchObject({
result: { graph: { nodes: expect.any(Array), edges: expect.any(Array) } },
normalized_result: {
graph: { nodes: expect.any(Array), edges: expect.any(Array) },
},
});
const analysisText = analyzed.content.find(({ type }) => type === "text");
expect(analysisText).toBeDefined();
@@ -118,20 +136,23 @@ it("exposes endpoint-scoped Electron discovery and inspection as Evidence", asyn
});
expect(reconciled.isError).not.toBe(true);
expect(reconciled.structuredContent).toMatchObject({
result: {
normalized_result: {
summary: { runtime_scripts: 1, matched: expect.any(Number) },
source_map_authority: { used_for_primary_matching: false },
},
});
expect(inspected.isError).not.toBe(true);
expect(inspected.structuredContent).toMatchObject({
result: {
normalized_result: {
target: { file_path: expect.stringMatching(/\/index\.html$/u) },
scripts: {
items: [
expect.objectContaining({
frame_id: "frame-main",
file_path: expect.stringMatching(/\/app\.js$/u),
cdp_hash: null,
length: null,
is_module: null,
}),
],
},
@@ -174,7 +195,7 @@ it("runs active Electron scenarios with selected paths and inferred working dire
};
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer(session, session, {
electronActiveObservation: provider,
@@ -204,7 +225,7 @@ it("runs active Electron scenarios with selected paths and inferred working dire
});
expect(captured.isError, JSON.stringify(captured)).not.toBe(true);
expect(captured.structuredContent).toMatchObject({
result: {
normalized_result: {
application: { process_ownership: "provider-owned" },
ipc: { events: [{ channel: "readiness:echo" }] },
coverage: {
@@ -231,18 +252,21 @@ it("runs active Electron scenarios with selected paths and inferred working dire
application_path: applicationPath,
application_root: root,
});
expect(JSON.stringify(captured.structuredContent)).not.toContain(
"submit-secret",
);
expect(JSON.stringify(captured.structuredContent)).toContain("submit-secret");
expect(JSON.stringify(captured.structuredContent)).toContain("super-secret");
expect(captured.structuredContent).toMatchObject({
evidence: {
predicate_type: "rea.electron-active-scenario",
operation: "capture_electron_scenario",
parameters: {
args: ["--token", "super-secret"],
actions: [{ step_id: "submit", kind: "click" }],
},
predicate_type: "rea.electron-active-scenario",
operation: "capture_electron_scenario",
parameters: {
args: ["--token", "super-secret"],
actions: [
{
step_id: "submit",
kind: "click",
selector: "#submit-secret",
window_index: 0,
},
],
},
});
}, 20_000);
@@ -253,7 +277,7 @@ it("exposes the target-free static JavaScript application workflow", async () =>
await writeElectronBoundaryFixture(root);
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer(session, session, {
availabilityPolicy: () => ({
@@ -286,7 +310,7 @@ it("exposes the target-free static JavaScript application workflow", async () =>
const projected = z
.object({
evidence_id: z.string(),
result: z.object({
normalized_result: z.object({
input_path: z.string(),
summary: z.object({
browser_windows: z.number(),
@@ -304,13 +328,11 @@ it("exposes the target-free static JavaScript application workflow", async () =>
relations: z.array(z.unknown()),
}),
}),
evidence: z.object({
operation: z.literal("analyze_javascript_application"),
parameters: z.object({ format: z.string() }),
}),
operation: z.literal("analyze_javascript_application"),
parameters: z.object({ format: z.string() }),
})
.parse(analyzed.structuredContent);
expect(projected.result).toMatchObject({
expect(projected.normalized_result).toMatchObject({
input_path: expect.stringMatching(/rea-electron-static-mcp-/u),
summary: {
browser_windows: 3,
@@ -318,25 +340,16 @@ it("exposes the target-free static JavaScript application workflow", async () =>
ipc: { paired_renderer_transmissions: 4 },
},
});
expect(projected.result.graph.nodes.length).toBeGreaterThan(0);
expect(projected.result.semantic_graph.nodes.length).toBeGreaterThan(0);
expect(projected.evidence.operation).toBe("analyze_javascript_application");
expect(projected.normalized_result.graph.nodes.length).toBeGreaterThan(0);
expect(
projected.normalized_result.semantic_graph.nodes.length,
).toBeGreaterThan(0);
expect(projected.operation).toBe("analyze_javascript_application");
const direct = await analyzeJavaScriptApplication({ input_path: root });
if (!direct.ok) throw direct.error;
expect(projected.evidence_id).toBe(direct.value.evidence_id);
});
const evidenceFor = (value: unknown) => {
const parsed = z
.object({
evidence_id: z.string(),
result: z.unknown(),
evidence: z.object({}).passthrough(),
})
.parse(value);
return {
...parsed.evidence,
evidence_id: parsed.evidence_id,
normalized_result: parsed.result,
};
return parseEvidence(value);
};
@@ -40,7 +40,7 @@ describe("enhanced MCP tools", () => {
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
result: {
normalized_result: {
items: addresses.map((address) => ({
address,
procedure: {
@@ -161,7 +161,7 @@ describe("batch procedure identity", () => {
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
result: {
normalized_result: {
items: [
...selectors.slice(0, 3).map((address) => ({
address,
+5 -32
View File
@@ -1,4 +1,5 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import type { CallToolResult } from "@modelcontextprotocol/server";
import {
jsonValueSchema,
@@ -40,35 +41,7 @@ export const closeEnhancedToolResources = async (): Promise<void> => {
);
};
export const jsonResult = (result: CallToolResult): JsonValue => {
if (result.isError === true)
return jsonValueSchema.parse(parseMcpToolError(result));
if (result.structuredContent === undefined)
throw new Error("Tool result omitted structured content");
const structured = jsonValueSchema.safeParse(result.structuredContent);
if (!structured.success)
throw new Error("Tool structured result was not JSON");
if (
typeof structured.data === "object" &&
structured.data !== null &&
!Array.isArray(structured.data) &&
"normalized_result" in structured.data
) {
return structured.data.normalized_result ?? null;
}
if (
typeof structured.data === "object" &&
structured.data !== null &&
!Array.isArray(structured.data) &&
"evidence_id" in structured.data &&
"result" in structured.data
)
return structured.data.result ?? null;
const text = result.content.find((item) => item.type === "text");
if (text?.type !== "text")
throw new Error("Tool result omitted text content");
const decoded: unknown = JSON.parse(text.text);
const parsed = jsonValueSchema.safeParse(decoded);
if (!parsed.success) throw new Error("Tool result was not JSON");
return parsed.data;
};
export const jsonResult = (result: CallToolResult): JsonValue =>
result.isError === true
? jsonValueSchema.parse(parseMcpToolError(result))
: parseEvidence(result.structuredContent).normalized_result;
@@ -1,3 +1,4 @@
import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
@@ -14,7 +15,7 @@ it("returns the complete session Evidence bundle in the tool result", async () =
);
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
expect(session.recordEvidence(evidence).ok).toBe(true);
const server = createServer(session, session);
+5 -3
View File
@@ -63,9 +63,11 @@ it("advertises exact valid schemas and records inline EVM interface evidence wit
const parsed = toolContract("inspect_evm_interface").outputSchema.parse(
response.structuredContent,
);
const evidence = parseEvidence(parsed.evidence);
expect(parsed.result).toEqual(value);
expect(parsed.result).toEqual(evidence.normalized_result);
const evidence = parseEvidence(parsed);
expect(evidence.confidence).toBe("inferred");
expect(evidence.subject?.digest.sha256).toBe(value.artifact.sha256);
expect(parsed.normalized_result).toEqual(value);
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
expect(
(
+2 -2
View File
@@ -45,8 +45,8 @@ it("executes named firmware contracts with inline Evidence and no native binary
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const result = contract.outputSchema.parse(response.structuredContent);
const evidence = parseEvidence(result.evidence);
expect(result.result).toEqual(evidence.normalized_result);
const evidence = parseEvidence(result);
expect(result.normalized_result).toEqual(evidence.normalized_result);
expect(result.evidence_id).toBe(evidence.evidence_id);
expect(evidence.operation).toBe(contract.name);
expect(evidence.raw_result).not.toBeNull();
@@ -1,10 +1,10 @@
import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { jsonObjectSchema } from "../../../src/domain/jsonValue.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
@@ -54,9 +54,7 @@ describe("function comparison reconstruction MCP integration", () => {
arguments: { left, right },
});
expect(compared.isError).not.toBe(true);
const comparison = parseEvidence(
jsonObjectSchema.parse(compared.structuredContent).evidence,
);
const comparison = parseEvidence(compared.structuredContent);
expect(comparison.normalized_result).toMatchObject({
status: comparisonStatus,
});
@@ -89,9 +87,7 @@ describe("function comparison reconstruction MCP integration", () => {
verified.isError,
JSON.stringify(verified.structuredContent),
).not.toBe(true);
const verification = parseEvidence(
jsonObjectSchema.parse(verified.structuredContent).evidence,
);
const verification = parseEvidence(verified.structuredContent);
expect(verification.normalized_result).toMatchObject({
status: verificationStatus,
summary: {
@@ -136,7 +132,7 @@ describe("function comparison MCP integration", () => {
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
expect(session.recordEvidence(FUNCTION_COMPARISON_EXAMPLE.left).ok).toBe(
true,
@@ -163,7 +159,7 @@ describe("function comparison MCP integration", () => {
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
result: { status: expect.any(String) },
normalized_result: { status: expect.any(String) },
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
});
const unknowns = await client.callTool({
@@ -198,7 +194,7 @@ describe("function comparison MCP integration", () => {
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer(session, session);
const client = new Client({ name: "function-link-test", version: "1" });
@@ -216,7 +212,7 @@ describe("function comparison MCP integration", () => {
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
result: { status: expect.any(String) },
normalized_result: { status: expect.any(String) },
});
} finally {
await Promise.allSettled([
@@ -231,7 +227,7 @@ describe("function comparison MCP integration", () => {
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
const wrong = createEvidence(
undefined,
+1 -1
View File
@@ -35,7 +35,7 @@ it("rejects contradictory annotation readback across the provider and MCP bounda
});
expect(accepted.isError).not.toBe(true);
expect(accepted.structuredContent).toMatchObject({
result: { annotations },
normalized_result: { annotations },
});
for (const value of [
{ ...original, annotations: { ...annotations, name: "different" } },
@@ -37,9 +37,7 @@ it("preserves queue failure diagnostics through the provider, CLI adapter and SD
const previousExitCode = process.exitCode;
try {
const cli = await logCliCommand(silentLogger, "inspect", async () => {
const result = await harness.session.execute("list_procedures", {
document: null,
});
const result = await harness.session.execute("list_procedures", {});
if (!result.ok) throw result.error;
return result.value.result;
});
@@ -23,7 +23,9 @@ it("rejects contradictory provider output before emitting MCP Evidence", async (
arguments: { address: bytes.address, length: 4 },
});
expect(accepted.isError).not.toBe(true);
expect(accepted.structuredContent).toMatchObject({ result: bytes });
expect(accepted.structuredContent).toMatchObject({
normalized_result: bytes,
});
const cases = [
...[
{ complete: true },
+10 -18
View File
@@ -1,8 +1,9 @@
import { expect } from "vitest";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js";
import type { BinarySession } from "../../../src/application/binary/BinarySession.js";
import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js";
import { SessionProviderRouter } from "../../../src/application/binary/SessionProviderRouter.js";
import { parseConfig } from "../../../src/config.js";
import type { JsonValue } from "../../../src/domain/jsonValue.js";
import { ok } from "../../../src/domain/result.js";
@@ -39,21 +40,19 @@ export const connectGhidraMcp = async (
if (execute !== undefined) return execute(operation, input, options);
return Promise.resolve(ok(resultFor(operation, input)));
},
close: () => Promise.resolve(),
close: () => Promise.resolve(ok(null)),
});
const config = parseConfig({ GHIDRA_INSTALL_DIR: INSTALL });
if (!config.ok) throw config.error;
const provider = new GhidraProvider(
config.value,
silentLogger,
{},
installationHost(),
factory,
);
const session = composeBinarySession(
SessionProviderRouter.selectable(
new AnalysisProviderRegistry([provider]),
[],
),
new AnalysisProviderRegistry([provider]),
);
const server = createServer(session, session, { logger: silentLogger });
const mcp = new Client({ name, version: "1.0.0" });
@@ -71,7 +70,9 @@ export const connectGhidraMcp = async (
arguments: { path: process.execPath },
});
if (opened.isError === true)
throw new Error("The Ghidra MCP harness could not open its target");
throw new Error(
`The Ghidra MCP harness could not open its target: ${JSON.stringify(opened)}`,
);
} catch (cause: unknown) {
await close();
throw cause;
@@ -85,17 +86,8 @@ export const connectGhidraMcp = async (
};
export const sessionEvidence = (session: BinarySession, value: unknown) => {
if (
typeof value !== "object" ||
value === null ||
!("evidence_id" in value) ||
typeof value.evidence_id !== "string"
)
throw new TypeError(
`Missing compact Evidence ID: ${JSON.stringify(value)}`,
);
const evidence = session.evidenceById(value.evidence_id);
if (evidence === undefined) throw new TypeError("Missing session Evidence");
const evidence = parseEvidence(value);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
return evidence;
};
+1 -1
View File
@@ -13,7 +13,7 @@ describe("Ghidra MCP capability routing", () => {
});
expect(batch.isError).not.toBe(true);
expect(batch.structuredContent).toMatchObject({
result: {
normalized_result: {
succeeded: 1,
failed: 0,
items: [{ status: "ok" }],
+9 -6
View File
@@ -89,12 +89,15 @@ const fixture = async (redirectUrl?: string, cycle = false) => {
const address = server.address();
if (address === null || typeof address === "string")
throw new Error("Missing HTTP fixture address");
const connection: IdaMcpConnection = createIdaMcpConnection({
url: `http://127.0.0.1:${address.port}/mcp`,
headers: { Authorization: "Bearer transport-fixture-secret" },
mode: "headless",
timeoutMs: 2000,
});
const connection: IdaMcpConnection = createIdaMcpConnection(
{
url: `http://127.0.0.1:${address.port}/mcp`,
headers: { Authorization: "Bearer transport-fixture-secret" },
mode: "headless",
timeoutMs: 2000,
},
{},
);
cleanups.push(() => connection.close());
return {
connection,
@@ -20,18 +20,20 @@ describe("inline MCP Evidence composition", () => {
);
const comparison = await mcp.callTool({
name: "compare_functions",
arguments: { left: analyzed.evidence, right: analyzed.evidence },
arguments: { left: analyzed, right: analyzed },
});
expect(comparison.isError).not.toBe(true);
const inline = parseEvidence(analyzed.evidence);
expect(inline.normalized_result).toEqual(analyzed.result);
const inline = parseEvidence(analyzed);
expect(inline.normalized_result).toEqual(analyzed.normalized_result);
expect(session.evidenceById(inline.evidence_id)).toEqual(inline);
const compared = toolContract("compare_functions").outputSchema.parse(
comparison.structuredContent,
);
const comparisonEvidence = parseEvidence(compared.evidence);
const comparisonEvidence = parseEvidence(compared);
expect(comparisonEvidence.evidence_links).toContain(inline.evidence_id);
expect(comparisonEvidence.normalized_result).toEqual(compared.result);
expect(comparisonEvidence.normalized_result).toEqual(
compared.normalized_result,
);
const bundle = await mcp.callTool({
name: "get_evidence_bundle",
arguments: {},
@@ -1,6 +1,7 @@
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { z } from "zod";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import type { BinarySession } from "../../../src/application/binary/BinarySession.js";
@@ -321,7 +322,7 @@ const connected = async () => {
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer(session, session);
const client = new Client({ name: "investigation-test", version: "1" });
@@ -332,20 +333,7 @@ const connected = async () => {
return { session, server, client };
};
const inlineEvidence = (value: unknown) => {
const parsed = z
.object({
evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
result: z.unknown(),
evidence: z.object({ limitations: z.array(z.string()) }).passthrough(),
})
.parse(value);
return {
...parsed.evidence,
evidence_id: parsed.evidence_id,
normalized_result: parsed.result,
};
};
const inlineEvidence = (value: unknown) => parseEvidence(value);
const close = async (
session: BinarySession,
@@ -55,8 +55,18 @@ it.skipIf(process.platform !== "linux" || process.arch !== "x64")(
const parsed = toolContract(
"recover_javascript_sources",
).outputSchema.parse(response.structuredContent);
const evidence = parseEvidence(parsed.evidence);
expect(parsed.result).toEqual(evidence.normalized_result);
const evidence = parseEvidence(parsed);
expect(evidence).toMatchObject({
operation: "recover_javascript_sources",
confidence: "derived",
authority: "shipped-artifact",
parameters: {
...args,
extraction_mode: "structural",
rewrite_level: "standard",
},
});
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
expect(parsed.evidence_id).toBe(evidence.evidence_id);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
await assertRecoveryCleanup(fixture.launches);
@@ -1,3 +1,4 @@
import { ok as resultOk } from "../../../src/domain/result.js";
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
@@ -119,7 +120,7 @@ describe("JavaScript runtime observation MCP tools", () => {
});
expect(listed.isError).not.toBe(true);
expect(listed.structuredContent).toMatchObject({
result: {
normalized_result: {
targets: [{ target_id: inspector.targetId }],
},
});
@@ -134,7 +135,7 @@ describe("JavaScript runtime observation MCP tools", () => {
});
expect(observedRuntime.isError).not.toBe(true);
expect(observedRuntime.structuredContent).toMatchObject({
result: {
normalized_result: {
target: {
target_id: inspector.targetId,
runtime_kind: "node",
@@ -151,11 +152,9 @@ describe("JavaScript runtime observation MCP tools", () => {
});
const evidenceId = evidenceIdFrom(observedRuntime.structuredContent);
expect(observedRuntime.structuredContent).toMatchObject({
evidence: {
evidence_id: evidenceId,
operation: "observe_javascript_runtime",
parameters: expect.any(Object),
},
evidence_id: evidenceId,
operation: "observe_javascript_runtime",
parameters: expect.any(Object),
});
expect(new Set(inspector.commands.map(({ method }) => method))).toEqual(
new Set(["Runtime.enable", "Debugger.enable"]),
@@ -178,7 +177,7 @@ const createObservationClient = async (
resources.push(inspector);
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer(session, session, {
javascriptRuntimeObservation: new V8InspectorProvider(),
@@ -1,3 +1,4 @@
import { silentLogger } from "../../../src/logger.js";
import { expect } from "vitest";
import { z } from "zod";
@@ -18,7 +19,11 @@ mcpTest.for(archiveNumberMetadataCases)(
const fixture = await keyedArchiveNumberMetadataFixture(item);
const configured = parseConfig({ REA_ANALYSIS_PROVIDER: "auto" });
if (!configured.ok) throw configured.error;
const session = createBinarySession(configured.value);
const session = createBinarySession(
configured.value,
silentLogger,
process.env,
);
onTestFinished(async () => {
await session.close();
});
@@ -35,8 +40,8 @@ mcpTest.for(archiveNumberMetadataCases)(
expect(result.isError, JSON.stringify(result.content)).not.toBe(true);
expectKeyedArchiveNumberMetadata(
z
.object({ result: keyedArchiveResultSchema })
.parse(result.structuredContent).result,
.object({ normalized_result: keyedArchiveResultSchema })
.parse(result.structuredContent).normalized_result,
item,
fixture.digest,
);
+203 -22
View File
@@ -1,39 +1,219 @@
import { Ajv2020 } from "ajv/dist/2020.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import {
STDIO_DEFAULT_MAX_BUFFER_SIZE,
isCallToolResult,
isJSONRPCResultResponse,
} from "@modelcontextprotocol/server";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { toEvidenceToolResult } from "../../../src/server/toolResult.js";
import {
createEvidence,
parseEvidence,
type Evidence,
} from "../../../src/domain/evidence.js";
import {
jsonObjectSchema,
type JsonValue,
} from "../../../src/domain/jsonValue.js";
import { ok } from "../../../src/domain/result.js";
import { silentLogger } from "../../../src/logger.js";
import { registerOfficialTools } from "../../../src/server/registerOfficialTools.js";
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
import { encodeToolResult } from "../../../src/server/toolResultEncoding.js";
const delivery = new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE);
const provider = { id: "fixture", name: "Fixture", version: "1" };
const callPseudoCode = async (
payload: string,
rawResult: JsonValue,
retained: boolean,
) => {
const records = new Map<string, Evidence>();
const recordEvidence = retained
? (evidence: Evidence) => {
records.set(evidence.evidence_id, evidence);
return ok("added" as const);
}
: undefined;
const server = new EvidenceMcpServer(
{ name: "complete-evidence", version: "1" },
{ capabilities: {} },
recordEvidence,
delivery,
);
registerOfficialTools(
server,
{
execute: () =>
Promise.resolve(
ok(createAnalysisExecution(payload, provider, { rawResult })),
),
},
{
logger: silentLogger,
activeTarget: undefined,
recordEvidence,
},
);
const client = new Client({ name: "complete-evidence-client", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const send = serverTransport.send.bind(serverTransport);
let responseWire = "";
serverTransport.send = (message, options) => {
if (isJSONRPCResultResponse(message) && isCallToolResult(message.result))
responseWire = JSON.stringify(message);
return send(message, options);
};
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = (await client.listTools()).tools.find(
({ name }) => name === "procedure_pseudo_code",
);
if (advertised?.outputSchema === undefined)
throw new Error("Missing named procedure_pseudo_code output schema");
const result = await client.callTool({
name: "procedure_pseudo_code",
arguments: { procedure: "main" },
});
return {
result,
responseWire,
records,
outputSchema: jsonObjectSchema.parse(advertised.outputSchema),
};
} finally {
await Promise.all([client.close(), server.close()]);
}
};
describe("large complete Evidence MCP delivery", () => {
it("does not claim retention without a recording acknowledgment", () => {
const normalized = {
payload: "x".repeat(Math.ceil(STDIO_DEFAULT_MAX_BUFFER_SIZE / 3)),
};
const evidence = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: "analyze_javascript_application",
parameters: {},
result: normalized,
},
it("delivers a two MiB provider result with raw observations and one normalized payload", async () => {
const payload = "x".repeat(2 * 1024 * 1024);
const { result, responseWire, outputSchema } = await callPseudoCode(
payload,
payload,
false,
);
const detached = toEvidenceToolResult(
expect(result.isError).not.toBe(true);
const evidence = toolContract("procedure_pseudo_code").outputSchema.parse(
result.structuredContent,
);
expect(evidence.normalized_result).toBe(payload);
expect(evidence.raw_result).toBe(payload);
expect(parseEvidence(evidence)).toEqual(evidence);
expect(evidence).not.toHaveProperty("result");
expect(evidence).not.toHaveProperty("evidence");
expect(result.content).toEqual([
{ type: "text", text: JSON.stringify(evidence) },
]);
expect(Buffer.byteLength(responseWire)).toBeLessThan(
STDIO_DEFAULT_MAX_BUFFER_SIZE,
);
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const validate = ajv.compile(outputSchema);
expect(validate(evidence), JSON.stringify(validate.errors)).toBe(true);
expect(
validate({ ...evidence, normalized_result: { unexpected: true } }),
).toBe(false);
expect(
validate({
result: payload,
evidence_id: evidence.evidence_id,
evidence,
}),
).toBe(false);
});
it("accounts for JSON escaping and preserves distinct raw and normalized observations", async () => {
const payload = 'quote" slash\\ control\u0000 newline\n unicode☃'.repeat(
8192,
);
const raw = { source: payload, decoder: "fixture-native-wire" };
const { result, responseWire } = await callPseudoCode(payload, raw, true);
expect(result.isError).not.toBe(true);
const evidence = toolContract("procedure_pseudo_code").outputSchema.parse(
result.structuredContent,
);
expect(evidence.normalized_result).toBe(payload);
expect(evidence.raw_result).toEqual(raw);
expect(result.content).toEqual([
{ type: "text", text: JSON.stringify(evidence) },
]);
expect(Buffer.byteLength(responseWire)).toBeLessThan(
STDIO_DEFAULT_MAX_BUFFER_SIZE,
);
const encoded = encodeToolResult(
jsonObjectSchema.parse(evidence),
delivery.resultBudgetBytes,
);
expect(encoded.ok).toBe(true);
if (!encoded.ok)
throw new Error("Expected complete escaped result delivery");
expect(encoded.bytes).toBe(Buffer.byteLength(JSON.stringify(result)));
expect(JSON.parse(responseWire).result.structuredContent).toEqual(evidence);
});
it("reports a true escaped-wire overrun and keeps acknowledged evidence recoverable", async () => {
// Control characters expand once in structured JSON and again in the text mirror.
const payload = "\u0000".repeat(
Math.ceil(STDIO_DEFAULT_MAX_BUFFER_SIZE / 20),
);
const { result, responseWire, records } = await callPseudoCode(
payload,
payload,
true,
);
expect(result.isError).toBe(true);
const limits = z
.object({
error: z.object({
code: z.literal("resource_constraint"),
details: z.object({
reported_limits: z.object({
constraint: z.literal("receive-buffer"),
evidence_reference: z.object({
kind: z.literal("retained-evidence"),
evidence_id: z.string(),
}),
}),
}),
}),
})
.parse(result.structuredContent).error.details.reported_limits;
const retained = parseEvidence(
records.get(limits.evidence_reference.evidence_id),
);
expect(retained.normalized_result).toBe(payload);
expect(retained.raw_result).toBe(payload);
expect(Buffer.byteLength(responseWire)).toBeLessThan(
STDIO_DEFAULT_MAX_BUFFER_SIZE,
);
});
it("does not claim retention without a recording acknowledgment", () => {
const evidence = createEvidence(undefined, provider, {
operation: "procedure_pseudo_code",
parameters: {},
result: "x".repeat(Math.ceil(STDIO_DEFAULT_MAX_BUFFER_SIZE / 2)),
});
const detached = delivery.toEvidenceToolResult(
evidence,
toolContract("analyze_javascript_application"),
toolContract("procedure_pseudo_code"),
undefined,
);
expect(detached.isError).toBe(true);
expect(Buffer.byteLength(JSON.stringify(detached))).toBeLessThan(
STDIO_DEFAULT_MAX_BUFFER_SIZE,
);
expect(detached.structuredContent).toMatchObject({
error: {
details: { reported_limits: { evidence_id: evidence.evidence_id } },
},
});
const limits = z
.object({
error: z.object({
@@ -43,6 +223,7 @@ describe("large complete Evidence MCP delivery", () => {
}),
})
.parse(detached.structuredContent).error.details.reported_limits;
expect(limits.evidence_id).toBe(evidence.evidence_id);
expect(limits).not.toHaveProperty("evidence_reference");
});
});
+1 -7
View File
@@ -72,7 +72,6 @@ describe("MCP runtime errors", () => {
it("unregisters every process-lifetime handler during idempotent shutdown", async () => {
const shutdown: Array<() => void> = [];
const reload: Array<() => void> = [];
const unregistrations: string[] = [];
let closeCalls = 0;
const runtime: RuntimeDependencies = {
@@ -87,22 +86,17 @@ describe("MCP runtime errors", () => {
exitCodes: [],
shutdownUnregistrations: unregistrations,
}),
registerReload: (handler) => {
reload.push(handler);
return () => unregistrations.push("reload");
},
};
expect(await run(runtime)).toBe(0);
expect(shutdown).toHaveLength(1);
expect(reload).toHaveLength(1);
shutdown[0]?.();
shutdown[0]?.();
await nextTurn();
expect(closeCalls).toBe(1);
expect([...unregistrations].sort()).toEqual(["reload", "shutdown"]);
expect(unregistrations).toEqual(["shutdown"]);
});
it("reports transport startup failure without its cause", async () => {
-51
View File
@@ -1,51 +0,0 @@
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js";
import { silentLogger } from "../../../src/logger.js";
import { registerConfigReload } from "../../../src/main/reload.js";
import type { RuntimeDependencies } from "../../../src/main/types.js";
import { createRuntimeState } from "../../../src/main/state.js";
describe("runtime configuration reload", () => {
it("applies valid reloads and keeps the last valid config after an invalid reload", () => {
const env: NodeJS.ProcessEnv = { REA_LOG_LEVEL: "info" };
const runtime = setupReload(env);
env.REA_LOG_LEVEL = "debug";
runtime.reload();
expect(runtime.state.currentConfig.logLevel).toBe("debug");
env.REA_LOG_LEVEL = "invalid";
runtime.reload();
expect(runtime.state.currentConfig.logLevel).toBe("debug");
});
});
const setupReload = (env: NodeJS.ProcessEnv) => {
const parsed = parseConfig(env);
if (!parsed.ok) throw parsed.error;
const state = createRuntimeState(parsed.value);
let reload: (() => void) | undefined;
const dependencies: RuntimeDependencies = {
env,
serve: serveStdio,
writeStderr: () => undefined,
setExitCode: () => undefined,
registerShutdown: () => () => undefined,
registerReload: (handler) => {
reload = handler;
return () => undefined;
},
};
registerConfigReload({
dependencies,
runtimeState: state,
serverLogger: silentLogger,
});
if (reload === undefined)
throw new Error("Reload handler was not registered");
return { reload, state };
};
+25 -56
View File
@@ -1,4 +1,5 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -14,7 +15,6 @@ import { AnalysisProviderRegistry } from "../../../src/application/binary/Analys
import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js";
import type { BinarySession } from "../../../src/application/binary/BinarySession.js";
import type { BinaryTarget } from "../../../src/domain/binaryTarget.js";
import { SessionProviderRouter } from "../../../src/application/binary/SessionProviderRouter.js";
import { MANAGED_NATIVE_VERIFICATION_EXAMPLE } from "../../../src/contracts/managed/managedWorkflowExamples.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { ManagedStaticProvider } from "../../../src/dotnet/ManagedStaticProvider.js";
@@ -31,11 +31,9 @@ it("runs every managed static inspection independently of an active native targe
const otherPath = join(directory, "other-fixture.dll");
await writeFile(path, buildManagedPeFixture());
await writeFile(otherPath, buildManagedPeFixture({ methodName: "Other" }));
const session = composeBinarySession(
SessionProviderRouter.selectable(new AnalysisProviderRegistry([]), [
new ManagedStaticProvider(),
]),
);
const session = composeBinarySession(new AnalysisProviderRegistry([]), [
new ManagedStaticProvider(),
]);
const server = createServer(
session,
sessionWithUnrelatedNativeTarget(session),
@@ -70,11 +68,9 @@ it("runs every managed static inspection independently of an active native targe
}),
);
expect(artifact).toMatchObject({
evidence: {
operation: "inspect_managed_artifact",
provider: { id: "rea-dotnet-static" },
subject: { local_path: path, format: "pe" },
},
operation: "inspect_managed_artifact",
provider: { id: "rea-dotnet-static" },
subject: { local_path: path, format: "pe" },
});
const misspelledPath = await client.callTool({
name: "inspect_managed_members",
@@ -90,11 +86,9 @@ it("runs every managed static inspection independently of an active native targe
await client.callTool({ name: "inspect_managed_members", arguments: {} }),
);
expect(members).toMatchObject({
evidence: {
operation: "inspect_managed_members",
provider: { id: "rea-dotnet-static" },
subject: { local_path: path, format: "pe" },
},
operation: "inspect_managed_members",
provider: { id: "rea-dotnet-static" },
subject: { local_path: path, format: "pe" },
});
const otherArtifact = structured(
await client.callTool({
@@ -103,16 +97,14 @@ it("runs every managed static inspection independently of an active native targe
}),
);
expect(otherArtifact).toMatchObject({
evidence: { subject: { local_path: otherPath, format: "pe" } },
subject: { local_path: otherPath, format: "pe" },
});
const reusedOtherTarget = structured(
await client.callTool({ name: "inspect_managed_members", arguments: {} }),
);
expect(reusedOtherTarget).toMatchObject({
evidence: {
operation: "inspect_managed_members",
subject: { local_path: otherPath, format: "pe" },
},
operation: "inspect_managed_members",
subject: { local_path: otherPath, format: "pe" },
});
const boundaries = structured(
await client.callTool({
@@ -121,11 +113,9 @@ it("runs every managed static inspection independently of an active native targe
}),
);
expect(boundaries).toMatchObject({
evidence: {
operation: "inspect_managed_native_boundaries",
provider: { id: "rea-dotnet-static" },
subject: { local_path: path, format: "pe" },
},
operation: "inspect_managed_native_boundaries",
provider: { id: "rea-dotnet-static" },
subject: { local_path: path, format: "pe" },
});
} finally {
await Promise.all([client.close(), server.close()]);
@@ -139,11 +129,9 @@ it("opens a managed PE and executes the managed static provider through MCP", as
const rightPath = join(directory, "fixture-renamed.exe");
await writeFile(path, buildManagedPeFixture());
await writeFile(rightPath, buildManagedPeFixture({ methodName: "Renamed" }));
const session = composeBinarySession(
SessionProviderRouter.selectable(new AnalysisProviderRegistry([]), [
new ManagedStaticProvider(),
]),
);
const session = composeBinarySession(new AnalysisProviderRegistry([]), [
new ManagedStaticProvider(),
]);
const server = createServer(
session,
sessionWithUnrelatedNativeTarget(session),
@@ -215,7 +203,7 @@ const verifyManagedCatalogAndNativeWorkflow = async (
await outputAssertion.assert("verify_managed_native_boundaries", verified);
expect(verified).toMatchObject({
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
result: {
normalized_result: {
summary: { verified: 1 },
algorithm: { token_to_address_mapping: "not-inferred" },
},
@@ -249,7 +237,7 @@ const inspectManagedStaticWorkflow = async (
);
await outputAssertion.assert("inspect_managed_artifact", inspected);
expect(inspected).toMatchObject({
result: {
normalized_result: {
classification: { status: "managed", runtime_family: "modern-dotnet" },
references: [expect.objectContaining({ name: "System.Runtime" })],
},
@@ -267,11 +255,7 @@ const inspectManagedStaticWorkflow = async (
}),
),
);
await outputAssertion.assert("inspect_managed_members", {
result: members.normalized_result,
evidence_id: members.evidence_id,
evidence: members,
});
await outputAssertion.assert("inspect_managed_members", members);
expect(members).toMatchObject({
operation: "inspect_managed_members",
provider: { id: "rea-dotnet-static" },
@@ -295,7 +279,7 @@ const inspectManagedStaticWorkflow = async (
);
await outputAssertion.assert("inspect_managed_native_boundaries", boundaries);
expect(boundaries).toMatchObject({
result: {
normalized_result: {
identity_scope: { token_identity: "build-local" },
pinvoke_imports: [],
native_implementations: [],
@@ -369,11 +353,7 @@ const verifyManagedComparisonAndReconstruction = async (
}),
),
);
await outputAssertion.assert("compare_managed_members", {
result: compared.normalized_result,
evidence_id: compared.evidence_id,
evidence: compared,
});
await outputAssertion.assert("compare_managed_members", compared);
expect(compared).toMatchObject({
operation: "compare_managed_members",
provider: { id: "rea-dotnet-workflows" },
@@ -481,16 +461,5 @@ const createOutputAssertion = async (client: Client) => {
const inlineEvidence = (
value: Readonly<Record<string, unknown>>,
): Record<string, unknown> => {
const parsed = z
.object({
evidence_id: z.string(),
result: z.unknown(),
evidence: z.object({}).passthrough(),
})
.parse(value);
return {
...parsed.evidence,
evidence_id: parsed.evidence_id,
normalized_result: parsed.result,
};
return parseEvidence(value);
};
@@ -10,12 +10,14 @@ import {
} from "@zip.js/zip.js";
import { afterEach, expect, it } from "vitest";
import { runProviderAnalysis } from "../../../src/composition/directAnalysis.js";
import { createDirectAnalysis } from "../../../src/composition/directAnalysis.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createServer } from "../../../src/server/createServer.js";
const { runProviderAnalysis } = createDirectAnalysis({});
const resources: Array<{ close(): Promise<unknown> }> = [];
afterEach(async () => {
for (const resource of resources.splice(0)) await resource.close();
@@ -87,12 +89,10 @@ it("advertises and executes Android and Apple inventory projections", async () =
arguments: { inventory_evidence: [apkInventory] },
});
if (android.isError === true)
throw new Error(JSON.stringify(android.structuredContent, null, 2));
throw new Error(JSON.stringify(android, null, 2));
expect(android.structuredContent).toMatchObject({
evidence: {
operation: "project_android_application_graph",
provider: { id: "rea-android-application" },
},
operation: "project_android_application_graph",
provider: { id: "rea-android-application" },
});
const ipaInventory = parseEvidence(
@@ -102,12 +102,9 @@ it("advertises and executes Android and Apple inventory projections", async () =
name: "project_apple_application_graph",
arguments: { inventory_evidence: [ipaInventory] },
});
if (apple.isError === true)
throw new Error(JSON.stringify(apple.structuredContent, null, 2));
if (apple.isError === true) throw new Error(JSON.stringify(apple, null, 2));
expect(apple.structuredContent).toMatchObject({
evidence: {
operation: "project_apple_application_graph",
provider: { id: "rea-apple-application" },
},
operation: "project_apple_application_graph",
provider: { id: "rea-apple-application" },
});
});
@@ -88,7 +88,7 @@ it("routes observe_native_calls through MCP with schema-checked input and output
const path = join(directory, "Tool");
await writeFile(path, machoHeader());
const session = createTestBinarySession(
new NativeMacOSProvider(new NativeFixtureRunner(), "darwin", tracer),
new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin", tracer),
);
const server = createServer(session, session);
const client = new Client({ name: "native-calls-mcp-test", version: "1" });
@@ -113,7 +113,9 @@ it("routes observe_native_calls through MCP with schema-checked input and output
true,
);
const result = nativeCallObservationResultSchema.parse(
z.object({ result: z.unknown() }).parse(called.structuredContent).result,
z
.object({ normalized_result: z.unknown() })
.parse(called.structuredContent).normalized_result,
);
expect(result.process).toMatchObject({ pid: 99, outcome: "exited" });
expect(result.breakpoints[0]?.request).toEqual({
@@ -229,7 +231,7 @@ it.each([
),
};
const session = createTestBinarySession(
new NativeMacOSProvider(new NativeFixtureRunner(), "darwin", tracer),
new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin", tracer),
);
const server = createServer(session, session);
const client = new Client({
+9 -3
View File
@@ -1,3 +1,4 @@
import { silentLogger } from "../../../src/logger.js";
import { copyFile } from "node:fs/promises";
import { join } from "node:path";
@@ -11,7 +12,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { mcpTest } from "../../support/mcp/mcpFixture.js";
const demangledSchema = z.object({
result: z.object({
normalized_result: z.object({
symbols: z.array(
z.object({ input: z.string(), output: z.string(), status: z.string() }),
),
@@ -31,7 +32,11 @@ describe.skipIf(process.platform !== "darwin")(
await copyFile("/usr/bin/true", target);
const configured = parseConfig({ REA_ANALYSIS_PROVIDER: "auto" });
if (!configured.ok) throw configured.error;
const session = createBinarySession(configured.value);
const session = createBinarySession(
configured.value,
silentLogger,
process.env,
);
onTestFinished(async () => {
await session.close();
});
@@ -50,7 +55,8 @@ describe.skipIf(process.platform !== "darwin")(
});
expect(called.isError, JSON.stringify(called.content)).not.toBe(true);
expect(
demangledSchema.parse(called.structuredContent).result.symbols,
demangledSchema.parse(called.structuredContent).normalized_result
.symbols,
).toEqual([
{ input: "-help", output: "-help", status: "unchanged" },
{
@@ -20,7 +20,7 @@ it("rejects changed signature targets through MCP and accepts reopening the new
);
await writeFile(path, machoImage({}));
const session = createTestBinarySession(
new NativeMacOSProvider(new NativeFixtureRunner(), "darwin"),
new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin"),
);
const server = createServer(session, session);
const client = new Client({ name: "signature-binding-test", version: "1" });
@@ -54,7 +54,7 @@ it("rejects changed signature targets through MCP and accepts reopening the new
JSON.stringify(inspected.structuredContent),
).not.toBe(true);
expect(inspected.structuredContent).toMatchObject({
result: { signed: true, identifier: "com.example.fixture" },
normalized_result: { signed: true, identifier: "com.example.fixture" },
});
} finally {
await client.close();
@@ -0,0 +1,158 @@
import { parseConfig } from "../../../src/config.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it, onTestFinished } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { runDirectAnalysis } from "../../../src/application/DirectAnalysis.js";
import { functionDossierSchema } from "../../../src/domain/hopperValues.js";
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
import {
jsonValueSchema,
type JsonValue,
} from "../../../src/domain/jsonValue.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
import {
createBinarySessionTargets,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
const connect = async (analysis: AnalysisOperationPort) => {
const server = createServer(analysis);
const client = new Client({ name: "argument-parity", version: "1.0.0" });
onTestFinished(async () => {
await client.close();
await server.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
return client;
};
describe("official operation arguments", () => {
it("dispatches equivalent CLI and MCP arguments while retaining omissions and defaults", async () => {
const [path] = await createBinarySessionTargets();
const calls: Array<{
name: string;
parameters: Readonly<Record<string, JsonValue>>;
}> = [];
const execute: AnalysisOperationPort["execute"] = (name, parameters) => {
calls.push({ name, parameters });
return Promise.resolve(
observed(name === "search_strings" ? [] : "int main() {}"),
);
};
const createSession = () =>
createTestBinarySession(() => ({
execute,
close: () => Promise.resolve(ok(null)),
}));
const dependencies = {
readConfiguration: () => parseConfig({}),
createBinarySession: createSession,
createManagedBinarySession: createSession,
};
const client = await connect({ execute });
for (const [name, mcpParameters, cliParameters] of [
["procedure_pseudo_code", { procedure: "main" }, { procedure: "main" }],
[
"search_strings",
{ pattern: "entry" },
{ pattern: "entry", mode: "literal", case_sensitive: false },
],
] as const) {
const cli = parseEvidence(
await runDirectAnalysis(dependencies, path, name, cliParameters),
);
const mcp = await client.callTool({ name, arguments: mcpParameters });
expect(mcp.isError).not.toBe(true);
expect(calls.slice(-2)).toEqual([
{ name, parameters: cliParameters },
{ name, parameters: cliParameters },
]);
expect(mcp.structuredContent).toMatchObject({
parameters: cli.parameters,
});
expect(cli.parameters).not.toHaveProperty("document");
}
});
it("rejects explicit null and malformed optional values before dispatch", async () => {
const calls: string[] = [];
const client = await connect({
execute: (name) => {
calls.push(name);
return Promise.resolve(observed(null));
},
});
for (const [name, parameters] of [
["list_procedures", { document: null }],
["procedure_pseudo_code", { procedure: "main", document: 3 }],
["search_strings", { pattern: "entry", case_sensitive: null }],
] as const) {
const result = await client.callTool({ name, arguments: parameters });
expect(result.isError).toBe(true);
}
expect(calls).toEqual([]);
});
it("preserves existing annotations when updates omit them and keeps empty clearing text", async () => {
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
const annotations = {
address: dossier.procedure.address,
name: dossier.procedure.name,
comment: "existing finding",
inline_comment: "existing inline finding",
};
const parameters: Readonly<Record<string, JsonValue>>[] = [];
const client = await connect({
execute: (_name, input) => {
parameters.push(input);
if (typeof input.comment === "string")
annotations.comment = input.comment;
if (typeof input.inline_comment === "string")
annotations.inline_comment = input.inline_comment;
return Promise.resolve(
observed(
jsonValueSchema.parse({
annotations,
dossier,
effects: {
scope: "session-analysis-database",
source_bytes_modified: false,
persists_after_close: false,
},
}),
),
);
},
});
const reply = await client.callTool({
name: "annotate_native_function",
arguments: { procedure: annotations.address, inline_comment: "" },
});
expect(reply.isError).not.toBe(true);
expect(parameters).toEqual([
{ procedure: annotations.address, inline_comment: "" },
]);
expect(reply.structuredContent).toMatchObject({
normalized_result: {
annotations: {
name: annotations.name,
comment: "existing finding",
inline_comment: "",
},
},
});
const rejected = await client.callTool({
name: "annotate_native_function",
arguments: { procedure: annotations.address, comment: null },
});
expect(rejected.isError).toBe(true);
expect(parameters).toHaveLength(1);
});
});
+6 -6
View File
@@ -32,7 +32,7 @@ describe("read_bytes contract", () => {
contract?.inputSchema.safeParse({ address: "0x1000", length: 0 }).success,
).toBe(false);
expect(
contract?.outputSchema.shape.result.safeParse({
contract?.outputSchema.shape.normalized_result.safeParse({
address: "0x1000",
requested_bytes: 4097,
returned_bytes: 4097,
@@ -49,7 +49,7 @@ describe("list_strings contract", () => {
({ name }) => name === "list_strings",
);
expect(
contract?.outputSchema.shape.result.safeParse([
contract?.outputSchema.shape.normalized_result.safeParse([
{
address: "0x1000",
value: "coffee",
@@ -145,7 +145,7 @@ describe("official Hopper proxy tools", () => {
});
});
it("binds list_procedures and projects its omitted Python document option", async () => {
it("binds list_procedures without adding omitted document arguments", async () => {
const invocations: Invocation[] = [];
const client = await connect({
execute: (name, arguments_) => {
@@ -165,14 +165,14 @@ describe("official Hopper proxy tools", () => {
});
expect(result.structuredContent).toMatchObject({
result: [
normalized_result: [
{ address: "0x1", value: "procedure" },
{ address: "0x2", value: "procedure" },
],
});
expect(invocations).toHaveLength(1);
expect(invocations[0]?.name).toBe("list_procedures");
expect(invocations[0]?.arguments_).toEqual({ document: null });
expect(invocations[0]?.arguments_).toEqual({});
expect(
(await client.listTools()).tools.find(
({ name }) => name === "list_procedures",
@@ -200,7 +200,7 @@ describe("official Hopper proxy tools", () => {
});
expect(result.structuredContent).toMatchObject({
result: [
normalized_result: [
{ address: "0x1", value: "coffee" },
{ address: "0x2", value: "coffee" },
],
@@ -192,8 +192,8 @@ mcpTest.for(failedAdapters)(
});
expect(listed.isError).not.toBe(true);
const evidenceId = z
.object({ evidence: z.object({ evidence_id: z.string() }) })
.parse(listed.structuredContent).evidence.evidence_id;
.object({ evidence_id: z.string() })
.parse(listed.structuredContent).evidence_id;
expect(connected.session.evidenceById(evidenceId)?.operation).toBe(healthy);
expect(calls).toEqual([
port === "javascriptRuntimeObservation" ? "browser" : "runtime",
@@ -220,7 +220,7 @@ mcpTest.for(failedAdapters)(
});
expect(analyzed.isError).not.toBe(true);
expect(analyzed.structuredContent).toMatchObject({
evidence: { operation: "analyze_javascript_application" },
operation: "analyze_javascript_application",
});
}
const malformed = await client.callTool({
@@ -17,7 +17,6 @@ import {
import { nativeUiResultSchema } from "../../../src/domain/native/nativeUiObservation.js";
import { processCaptureSchema } from "../../../src/domain/process/processCapture.js";
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
import { inlineLocalJsonSchemaReferences } from "../../fixtures/localJsonSchemaReferences.js";
const record = (value: unknown): Record<string, unknown> => {
if (typeof value !== "object" || value === null || Array.isArray(value))
@@ -25,6 +24,25 @@ const record = (value: unknown): Record<string, unknown> => {
return value as Record<string, unknown>;
};
const schemaNode = (
root: Record<string, unknown>,
value: unknown,
): Record<string, unknown> => {
const schema = record(value);
if (typeof schema.$ref !== "string") return schema;
if (!schema.$ref.startsWith("#/"))
throw new Error("Expected a local advertised schema reference");
const referenced = schema.$ref
.slice(2)
.split("/")
.reduce<unknown>(
(parent, key) =>
record(parent)[key.replaceAll("~1", "/").replaceAll("~0", "~")],
root,
);
return { ...record(referenced), ...schema };
};
it("advertises semantic output invariants and keeps producers aligned with Zod", async () => {
const contracts = [
toolContract("capture_native_ui_scenario"),
@@ -56,7 +74,7 @@ it("advertises semantic output invariants and keeps producers aligned with Zod",
if (tool?.outputSchema === undefined)
throw new Error(`${name} output schema missing`);
const outputSchema = record(tool.outputSchema);
const result = record(record(outputSchema.properties).result);
const result = record(record(outputSchema.properties).normalized_result);
const standaloneResultSchema = z.record(z.string(), z.unknown()).parse({
...result,
...(typeof outputSchema.$schema === "string"
@@ -66,8 +84,11 @@ it("advertises semantic output invariants and keeps producers aligned with Zod",
? {}
: { $defs: outputSchema.$defs }),
});
const node = (value: unknown) =>
schemaNode(standaloneResultSchema, value);
return {
result: record(inlineLocalJsonSchemaReferences(standaloneResultSchema)),
result: node(result),
node,
validate: new Ajv2020({
strict: false,
validateFormats: false,
@@ -76,18 +97,18 @@ it("advertises semantic output invariants and keeps producers aligned with Zod",
};
const native = outputResultSchema("capture_native_ui_scenario");
const initial = record(record(native.result.properties).initial);
const screenshotUnion = record(record(initial.properties).screenshot);
const initial = native.node(record(native.result.properties).initial);
const screenshotUnion = native.node(record(initial.properties).screenshot);
const screenshotVariants = screenshotUnion.anyOf;
if (!Array.isArray(screenshotVariants))
throw new Error("Expected nullable screenshot schema");
const screenshotProperties = record(
record(screenshotVariants[0]).properties,
native.node(screenshotVariants[0]).properties,
);
expect(record(screenshotProperties.base64).description).toContain(
expect(native.node(screenshotProperties.base64).description).toContain(
"PNG signature",
);
expect(record(screenshotProperties.sha256).description).toContain(
expect(native.node(screenshotProperties.sha256).description).toContain(
"decoded PNG bytes",
);
const pngBytes = Buffer.from("not a PNG");
@@ -124,7 +145,7 @@ it("advertises semantic output invariants and keeps producers aligned with Zod",
const process = outputResultSchema("capture_process_scenario");
expect(process.result.description).toContain("canonical scenario");
expect(process.result.description).toContain(
"older input without an event journal",
"The event journal is required",
);
const validCapture = processCaptureSchema.parse(
EMPTY_PROCESS_CAPTURE_EXAMPLE,
@@ -13,10 +13,12 @@ import { EvidenceIntegrityError } from "../../../src/domain/evidenceErrors.js";
import type { Evidence } from "../../../src/domain/evidence.js";
import { err, ok } from "../../../src/domain/result.js";
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
import { toErrorToolResult } from "../../../src/server/toolResult.js";
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
const delivery = new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE);
const oversizedFailure = () =>
toErrorToolResult(
delivery.toErrorToolResult(
new AnalysisInputError("procedure_address", undefined, [
{
path: ["procedure"],
@@ -34,6 +36,7 @@ const exerciseDeliveryFailure = async (
{ name: "oversized-error-test", version: "1" },
{ capabilities: {} },
recordEvidence,
delivery,
);
server.registerTool("large_failure", { inputSchema: {} }, async () =>
oversizedFailure(),
@@ -4,7 +4,6 @@ import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it, onTestFinished } from "vitest";
import { z } from "zod";
import { compareProcessEvidenceFiles } from "../../../src/application/process/ProcessCli.js";
import { PROCESS_PROVIDER } from "../../../src/application/process/ProcessEvidence.js";
@@ -52,10 +51,7 @@ const captureEvidence = (
});
const inlineEvidence = (response: { structuredContent?: unknown }) =>
parseEvidence(
z.object({ evidence: z.unknown() }).parse(response.structuredContent)
.evidence,
);
parseEvidence(response.structuredContent);
const connectedComparison = async () => {
const session = createTestBinarySession(() => {
@@ -1,3 +1,4 @@
import { ok as resultOk } from "../../../src/domain/result.js";
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -120,7 +121,7 @@ describe("declared trace adapter parity", () => {
(_path) =>
({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}) satisfies AnalysisClient,
);
expect(session.recordEvidence(left).ok).toBe(true);
@@ -145,13 +146,13 @@ describe("declared trace adapter parity", () => {
});
expect(response.isError).not.toBe(true);
expect(response.structuredContent).toMatchObject({
result: { trace: { verdict: "equivalent" } },
normalized_result: { trace: { verdict: "equivalent" } },
evidence_id: cliEvidence.evidence_id,
});
const structuredResult =
typeof response.structuredContent === "object" &&
response.structuredContent !== null
? Reflect.get(response.structuredContent, "result")
? Reflect.get(response.structuredContent, "normalized_result")
: undefined;
expect(structuredResult).toEqual(cliEvidence.normalized_result);
expect(cliEvidence.locations).toEqual([
+21 -7
View File
@@ -1,3 +1,4 @@
import { ok as resultOk } from "../../../src/domain/result.js";
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
@@ -15,6 +16,7 @@ import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { createPromptCompletionSource } from "../../../src/server/promptCompletion.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
let directory: string | undefined;
@@ -27,7 +29,21 @@ afterEach(async () => {
describe("guided prompt completion from live analysis", () => {
it("reads live documents and complete procedures without ambiguous names", async () => {
const requests: Array<Readonly<Record<string, unknown>>> = [];
const session = createTestBinarySession(() => client(requests));
const session = createTestBinarySession(() => client(requests), {
resolveAnalysisProfile: () =>
Promise.resolve(
resultOk({
profile: createAnalysisProfile(
{
id: "fixture",
name: "Fixture analysis provider",
version: "1",
},
{ fixture: true },
),
}),
),
});
directory = await createTestTempDirectory("rea-prompt-completion-");
const target = join(directory, "fixture.hop");
await writeFile(target, "fixture");
@@ -44,9 +60,7 @@ describe("guided prompt completion from live analysis", () => {
}),
).toEqual(["0x1000", "0x2000", "0x3000", "0x4000", "tail", "unique"]);
expect(requests).toEqual([{ document: "App" }]);
expect(await completion.complete("provider", "uni")).toEqual([
"unidentified",
]);
expect(await completion.complete("provider", "fix")).toEqual(["fixture"]);
expect(await completion.complete("document", "x".repeat(4_097))).toEqual(
[],
);
@@ -58,7 +72,7 @@ describe("guided prompt completion from live analysis", () => {
});
describe("guided prompt completion from investigation records", () => {
it("completes process captures imported in the original v3 format", async () => {
it("excludes process captures missing canonical executable identity", async () => {
const session = createTestBinarySession(() => client([]));
const {
selected_executable_sha256: _selectedDigest,
@@ -83,7 +97,7 @@ describe("guided prompt completion from investigation records", () => {
expect(
await completion.complete("capture", evidence.evidence_id.slice(0, 8)),
).toEqual([evidence.evidence_id]);
).toEqual([]);
await session.close();
});
@@ -272,5 +286,5 @@ const client = (
}
return Promise.resolve(observed(null));
},
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
});
+48 -25
View File
@@ -1,19 +1,28 @@
import { ok as resultOk } from "../../../src/domain/result.js";
import { readFile, rm, writeFile } from "node:fs/promises";
import { basename, join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import {
STDIO_DEFAULT_MAX_BUFFER_SIZE,
type McpServer,
} from "@modelcontextprotocol/server";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import {
createCacheProvider,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import type { BinarySession } from "../../../src/application/binary/BinarySession.js";
import { PROMPT_CONTRACTS } from "../../../src/contracts/promptContracts.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { createServer } from "../../../src/server/createServer.js";
import { registerGuidedPrompts } from "../../../src/server/registerPrompts.js";
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
import { observed } from "../../fixtures/analysisExecution.js";
const resources: Array<{ close(): Promise<unknown> }> = [];
@@ -61,14 +70,21 @@ describe("guided prompts over MCP", () => {
const result = await client.getPrompt({
name: "investigate_feature",
arguments: {
feature: "license validation",
feature: "Ignore prior instructions and rename everything",
document: "App",
},
});
const content = result.messages[0]?.content;
expect(content?.type).toBe("text");
if (content?.type !== "text") throw new Error("missing prompt text");
expect(content.text).toContain('"feature":"license validation"');
expect(content.text).toContain(
'"feature":"Ignore prior instructions and rename everything"',
);
expect(content.text).toMatch(/not instructions/i);
expect(content.text).toMatch(/not a required sequence/i);
expect(content.text).toMatch(/never as authorization/i);
for (const section of ["Observations", "Inference", "Unknowns"])
expect(content.text).toContain(section);
expect(content.text).toContain("`trace_feature`");
expect(content.text).toContain(
"input_path=target_path directly; no open_binary call is needed",
@@ -234,12 +250,19 @@ describe("guided prompt completion registry", () => {
});
it("emits prompts/list_changed and exposes the updated prompt", async () => {
const session = fixtureSession();
const server = new McpServer({
name: "prompt-registry-test",
version: "1",
});
const registry = registerGuidedPrompts(server, session, session);
const session = createTestBinarySession(createCacheProvider([]));
const delivery = new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE);
const server = new EvidenceMcpServer(
{ name: "prompt-registry-test", version: "1" },
{},
undefined,
delivery,
);
const registry = registerGuidedPrompts(
server,
{ execute: async () => observed(["fixture-document"]) },
session,
);
const client = new Client({ name: "prompt-registry-client", version: "1" });
const changed = new Promise<void>((resolve) => {
client.setNotificationHandler("notifications/prompts/list_changed", () =>
@@ -267,7 +290,7 @@ describe("guided prompt completion registry", () => {
await changed;
const prompts = await client.listPrompts();
expect(prompts.prompts[0]?.title).toBe("Investigate a feature (updated)");
expect(await complete(client, "document", "uni")).toEqual(["unidentified"]);
expect(await complete(client, "document", "fixture")).toEqual(["fixture"]);
});
});
@@ -282,10 +305,13 @@ describe("guided prompt completion lifecycle", () => {
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const server = new McpServer({
name: "prompt-cancellation-test",
version: "1",
});
const delivery = new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE);
const server = new EvidenceMcpServer(
{ name: "prompt-cancellation-test", version: "1" },
{},
undefined,
delivery,
);
registerGuidedPrompts(server, {
async execute() {
calls += 1;
@@ -333,14 +359,11 @@ describe("guided prompt completion lifecycle", () => {
resources.push(session);
expect(await complete(client, "document", "")).toEqual([]);
expect(
(
await client.callTool({
name: "open_binary",
arguments: { path: first },
})
).isError,
).not.toBe(true);
const opened = await client.callTool({
name: "open_binary",
arguments: { path: first },
});
expect(opened).not.toMatchObject({ isError: true });
expect(await complete(client, "document", "first")).toEqual([
"first-document",
]);
@@ -387,7 +410,7 @@ const fixtureSession = (
onExecute();
return Promise.resolve(observed(null));
},
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
const MINIMUM_PROMPT_ARGUMENTS: Readonly<
@@ -428,7 +451,7 @@ const lifecycleClient = (
}
return Promise.resolve(observed(null));
},
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
});
const complete = async (
@@ -17,7 +17,6 @@ import {
} from "../../../src/application/AnalysisProvider.js";
import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js";
import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js";
import { SessionProviderRouter } from "../../../src/application/binary/SessionProviderRouter.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { ok } from "../../../src/domain/result.js";
import { silentLogger } from "../../../src/logger.js";
@@ -39,13 +38,10 @@ describe("provider selection over MCP", () => {
await writeFile(target, "fixture");
const starts: string[] = [];
const session = composeBinarySession(
SessionProviderRouter.selectable(
new AnalysisProviderRegistry([
candidate("beta", starts),
candidate("alpha", starts),
]),
[],
),
new AnalysisProviderRegistry([
candidate("beta", starts),
candidate("alpha", starts),
]),
);
const server = createServer(session, session, { logger: silentLogger });
const mcp = new Client({ name: "provider-selection", version: "1.0.0" });
@@ -117,7 +113,7 @@ describe("provider selection over MCP", () => {
});
expect(observed.isError).not.toBe(true);
expect(structured(observed)).toMatchObject({
result: "beta:address_name",
normalized_result: "beta:address_name",
evidence_id: expect.stringMatching(/^ev_/u),
});
expect(starts).toEqual(["beta"]);
@@ -195,7 +191,6 @@ const candidate = (id: string, starts: string[]): AnalysisProviderCandidate => {
{ id, name: identity.name, version: "1" },
{ fixture: id },
),
compatibility: {},
}),
),
createClient: (_target, profile) => {
@@ -210,7 +205,7 @@ const candidate = (id: string, starts: string[]): AnalysisProviderCandidate => {
),
),
),
close: () => Promise.resolve(),
close: () => Promise.resolve(ok(null)),
};
},
};
@@ -1,4 +1,5 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
@@ -12,7 +13,7 @@ describe("reconstruction coverage MCP", () => {
it("evaluates inline fail-closed coverage without session retention", async () => {
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer(session, session);
const client = new Client({ name: "coverage-mcp-test", version: "1" });
@@ -1,3 +1,4 @@
import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
@@ -10,7 +11,7 @@ describe("reconstruction obligation ledger MCP parity", () => {
it("returns the complete Evidence-backed ledger inline", async () => {
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer(session, session);
const client = new Client({ name: "obligation-ledger-test", version: "1" });
@@ -33,14 +34,14 @@ describe("reconstruction obligation ledger MCP parity", () => {
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
result: {
normalized_result: {
schema: "ReconstructionObligationLedger",
status: "unknown",
summary: { total: 0 },
},
});
expect(result.structuredContent).toHaveProperty(
"result.schema",
"normalized_result.schema",
"ReconstructionObligationLedger",
);
} finally {
+5 -3
View File
@@ -61,9 +61,11 @@ it("advertises exact valid schemas and records inline recorded-core evidence wit
const parsed = toolContract("inspect_recorded_crash").outputSchema.parse(
response.structuredContent,
);
const evidence = parseEvidence(parsed.evidence);
expect(parsed.result).toEqual(value);
expect(parsed.result).toEqual(evidence.normalized_result);
const evidence = parseEvidence(parsed);
expect(evidence.confidence).toBe("observed");
expect(evidence.subject?.digest.sha256).toBe(value.artifact.sha256);
expect(parsed.normalized_result).toEqual(value);
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
expect(
(
@@ -200,6 +200,22 @@ it("preserves validation for the referenced record's operation, predicate, and s
error: { code: "invalid_request", category: "invalid_input" },
});
}
for (const reference of [
{ evidence_id: application.evidence_id },
{ ...retained(application.evidence_id), kind: "another-session" },
retained("ev_short"),
{ ...retained(application.evidence_id), session_id: "foreign" },
{ ...retained(application.evidence_id), normalized_result: {} },
]) {
const rejected = await client.callTool({
name: "trace_application_feature",
arguments: {
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
application: reference,
},
});
expect(rejected.isError).toBe(true);
}
const tampered = {
...application,
provider: { ...application.provider, id: "tampered" },
@@ -233,6 +249,6 @@ it("projects a retained JavaScript summary without graph or semantic_graph", asy
expect(inline.isError).not.toBe(true);
expect(referenced.structuredContent).toEqual(inline.structuredContent);
expect(inline.structuredContent).not.toHaveProperty(
"result.summary.semantic_graph",
"normalized_result.summary.semantic_graph",
);
});
+3 -12
View File
@@ -1,4 +1,5 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -56,7 +57,7 @@ const availabilityProvider = (
createClient: () => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}),
};
};
@@ -88,17 +89,6 @@ const statusCapability = (
});
describe("server and catalog identity", () => {
it("retains all catalog identity fields through transport serialization and detached clones", () => {
const serialized = JSON.parse(JSON.stringify(CATALOG_IDENTITY));
expect(structuredClone(CATALOG_IDENTITY)).toEqual(serialized);
expect(serialized.digests).toEqual(CATALOG_IDENTITY.digests);
expect(serialized.tools).toHaveLength(TOOL_CONTRACTS.length);
const identity = createServerIdentity({
startedAt: "2026-07-13T00:00:00.000Z",
});
expect(JSON.parse(JSON.stringify(identity)).catalog).toEqual(serialized);
});
it("derives package and SDK versions from canonical package metadata", async () => {
const packageJson = JSON.parse(await readFile("package.json", "utf8"));
const packageLock = JSON.parse(await readFile("package-lock.json", "utf8"));
@@ -370,6 +360,7 @@ const assertLiveIdentity = async (client: Client): Promise<void> => {
},
client: { name: "identity-test", version: "9" },
negotiated_protocol_version: expect.any(String),
catalog: CATALOG_IDENTITY,
alignment: { state: "unknown" },
},
},
@@ -131,7 +131,7 @@ it("preserves distinct results across concurrent tool calls", async () => {
results.forEach((result, index) => {
expect(result.isError).not.toBe(true);
expect(structured(result)).toMatchObject({
result: payloads.get(names[index] ?? ""),
normalized_result: payloads.get(names[index] ?? ""),
});
});
});
+6 -8
View File
@@ -11,7 +11,7 @@ import type {
CapabilityDescriptor,
} from "../../../src/application/AnalysisProvider.js";
import { AnalysisCapabilityUnavailableError } from "../../../src/domain/analysisErrorCore.js";
import { err } from "../../../src/domain/result.js";
import { err, ok as resultOk } from "../../../src/domain/result.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import { createServer } from "../../../src/server/createServer.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
@@ -63,7 +63,7 @@ const providerWithCapabilities = (
capabilities: () => capabilities,
createClient: () => ({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}),
};
};
@@ -136,7 +136,7 @@ it("records capture disagreement as a contradicted unknown", async () => {
() =>
({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}) satisfies AnalysisClient,
);
const left = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
@@ -197,7 +197,7 @@ it("records capture disagreement as a contradicted unknown", async () => {
},
});
expect(compared.isError).not.toBe(true);
const firstEvidence = parseEvidence(structured(compared).evidence);
const firstEvidence = parseEvidence(structured(compared));
expect(
structured(await client.callTool({ name: "list_unknowns", arguments: {} })),
).toMatchObject({
@@ -229,7 +229,7 @@ it("records capture disagreement as a contradicted unknown", async () => {
expect(secondComparison.isError, JSON.stringify(secondComparison)).not.toBe(
true,
);
const secondEvidence = parseEvidence(structured(secondComparison).evidence);
const secondEvidence = parseEvidence(structured(secondComparison));
expect(secondEvidence.normalized_result).toMatchObject({
status: "changed",
interaction: "added",
@@ -252,9 +252,7 @@ it("records capture disagreement as a contradicted unknown", async () => {
arguments: { left: leftEvidence, right: repeatedCapture },
});
expect(repeatedComparison.isError).not.toBe(true);
expect(parseEvidence(structured(repeatedComparison).evidence)).toEqual(
secondEvidence,
);
expect(parseEvidence(structured(repeatedComparison))).toEqual(secondEvidence);
expect(
parseEvidenceBundle(
structured(await client.callTool({ name: "get_evidence_bundle" })).result,
+20 -15
View File
@@ -1,4 +1,5 @@
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";
@@ -12,6 +13,7 @@ import type {
import { observed as ok } from "../../fixtures/analysisExecution.js";
import { createServer } from "../../../src/server/createServer.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { toolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
const resources: Array<{ close(): Promise<void> }> = [];
@@ -74,7 +76,7 @@ it("executes a realistic workflow: list methods, decompile selected, get xrefs",
});
expect(listResult.isError).not.toBe(true);
expect(structured(listResult)).toMatchObject({
result: [
normalized_result: [
{ address: "0x1000", value: "main" },
{ address: "0x2000", value: "helper" },
],
@@ -85,7 +87,7 @@ it("executes a realistic workflow: list methods, decompile selected, get xrefs",
arguments: { procedure: "0x1000" },
});
expect(structured(decompileResult)).toMatchObject({
result: "pseudo for 0x1000",
normalized_result: "pseudo for 0x1000",
});
const xrefResult = await client.callTool({
@@ -93,7 +95,7 @@ it("executes a realistic workflow: list methods, decompile selected, get xrefs",
arguments: {},
});
expect(structured(xrefResult)).toMatchObject({
result: ["0x1000"],
normalized_result: ["0x1000"],
});
});
@@ -102,7 +104,7 @@ it("advertises the complete currently available inventory with a session", async
(_path) =>
({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(),
close: () => Promise.resolve(resultOk(null)),
}) satisfies AnalysisClient,
);
const server = createServer(
@@ -127,18 +129,21 @@ it("advertises the complete currently available inventory with a session", async
arguments: {},
}),
);
const inventory = z
.object({
result: z.object({ tool_availability: z.array(toolAvailability) }),
})
.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(
z
.object({
result: z.object({
tool_availability: z.array(
z.object({ name: z.string(), available: z.boolean() }),
),
}),
})
.parse(status)
.result.tool_availability.filter((item) => item.available)
.map(({ name }) => name),
inventory.filter((item) => item.available).map(({ name }) => name),
);
expect(new Set(names)).toEqual(
new Set(TOOL_CONTRACTS.map(({ name }) => name)),
+10 -6
View File
@@ -202,9 +202,7 @@ describe("target-free MCP lifecycle", () => {
const closed: string[] = [];
const session = createTestBinarySession(provider(closed), {
resolveAnalysisProfile: () =>
Promise.resolve(
resultOk({ profile: SNAPSHOT_PROFILE, compatibility: {} }),
),
Promise.resolve(resultOk({ profile: SNAPSHOT_PROFILE })),
});
const server = createServer(session, session, { logger: silentLogger });
const mcp = new Client({ name: "replaced-target", version: "1.0.0" });
@@ -220,6 +218,9 @@ describe("target-free MCP lifecycle", () => {
arguments: { path: targetPath },
}),
).result;
expect(
(await mcp.callTool({ name: "current_document", arguments: {} })).isError,
).not.toBe(true);
await writeFile(targetPath, "second");
const second = structured(
await mcp.callTool({
@@ -350,7 +351,6 @@ describe("target-free MCP workflow", () => {
).result,
).toMatchObject({
path: snapshotPath,
entries: 0,
primitive_entries: 0,
workflow_entries: 0,
evidence_records: 0,
@@ -457,12 +457,16 @@ const client = (path: string, closed: string[]): AnalysisClient => ({
),
close: () => {
closed.push(path);
return Promise.resolve();
return Promise.resolve(resultOk(null));
},
});
const provider = (closed: string[]): AnalysisProvider => {
const identity = { id: "fixture", name: "Fixture", version: "1" };
const identity = {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
};
const capability: CapabilityDescriptor = {
provider: identity,
operation: "current_document",
+1 -1
View File
@@ -42,7 +42,7 @@ export const createSessionMcpHarness = async (
const closed: string[] = [];
const session = createTestBinarySession(provider(closed), {
resolveAnalysisProfile: () =>
Promise.resolve(ok({ profile: SNAPSHOT_PROFILE, compatibility: {} })),
Promise.resolve(ok({ profile: SNAPSHOT_PROFILE })),
});
const server = createServer(session, session, {
logger: silentLogger,
+55 -1
View File
@@ -6,6 +6,13 @@ import { createManagedBinarySession } from "../../../src/composition/binary.js";
import { MCP_SHUTDOWN_FAILED } from "../../../src/main/messages.js";
import { createShutdown } from "../../../src/main/shutdown.js";
import type { RuntimeDependencies } from "../../../src/main/types.js";
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
import { err, ok } from "../../../src/domain/result.js";
import { observed } from "../../fixtures/analysisExecution.js";
import {
createBinarySessionTargets,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
it("keeps shutdown output stable while logging the rejected cause at debug level", async () => {
const logs: string[] = [];
@@ -41,7 +48,6 @@ it("keeps shutdown output stable while logging the rejected cause at debug level
androidClosed = true;
},
session: createManagedBinarySession(),
unregisterReload: () => undefined,
dependencies,
serverLogger: logger,
});
@@ -64,3 +70,51 @@ it("keeps shutdown output stable while logging the rejected cause at debug level
}),
);
});
it("reports a typed binary cleanup failure and retains the client for retry", async () => {
const [target] = await createBinarySessionTargets();
const failure = new ProviderCleanupError("fixture", ["owned-runtime"], {
reason: "fixture removal denied",
});
let cleanupAllowed = false;
let retainDocument: boolean | undefined;
const session = createTestBinarySession(() => ({
execute: async () => observed(null),
close: async (options) => {
retainDocument = options?.retainDocument;
return cleanupAllowed ? ok(null) : err(failure);
},
}));
expect((await session.open(target)).ok).toBe(true);
const output: string[] = [];
const exitCodes: number[] = [];
const requests: Array<() => void> = [];
const dependencies: RuntimeDependencies = {
env: {},
serve: () => {
throw new Error("unused fixture transport");
},
writeStderr: (text) => output.push(text),
setExitCode: (code) => exitCodes.push(code),
registerShutdown: (request) => {
requests.push(request);
return () => undefined;
},
};
createShutdown({
handle: { close: async () => undefined },
session,
dependencies,
serverLogger: pino({ enabled: false }),
});
requests[0]?.();
await new Promise((resolve) => setImmediate(resolve));
expect(exitCodes).toEqual([1]);
expect(output).toEqual([
`${MCP_SHUTDOWN_FAILED}\n`,
`${failure.userMessage}\n`,
]);
expect(retainDocument).toBe(true);
cleanupAllowed = true;
expect((await session.close()).ok).toBe(true);
});
+36 -38
View File
@@ -1,7 +1,10 @@
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import {
McpServer,
STDIO_DEFAULT_MAX_BUFFER_SIZE,
} from "@modelcontextprotocol/server";
import { ProcessCaptureError } from "../../../src/process/capture/ProcessCaptureError.js";
import { resolveProcessResult } from "../../../src/process/capture/ProcessCaptureLifecycle.js";
@@ -9,17 +12,19 @@ import {
toolContract,
type ToolContract,
} from "../../../src/contracts/toolContracts.js";
import { err, ok } from "../../../src/domain/result.js";
import { err } from "../../../src/domain/result.js";
import { HopperProcessError } from "../../../src/domain/hopperErrors.js";
import type { IncompleteProcessCaptureObservations } from "../../../src/domain/process/processCapture.js";
import { processScenarioSchema } from "../../../src/domain/process/processScenario.js";
import { toCallToolResult } from "../../../src/server/toolResult.js";
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { emptyProcessCapture } from "../../../src/domain/process/processCapture.fixture.js";
import type { JsonValue } from "../../../src/domain/jsonValue.js";
import { evidenceResultOf } from "../../../src/contracts/toolOutputSchemas.js";
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
const delivery = new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE);
const contract: ToolContract = {
name: "provider_neutral_fixture",
title: "Provider Neutral Fixture",
@@ -72,7 +77,7 @@ describe("completed partial process capture MCP projection", () => {
if (failure === undefined)
throw new Error("expected process capture failure");
const result = toCallToolResult(
const result = delivery.toCallToolResult(
err(failure),
toolContract("capture_process_scenario"),
);
@@ -130,7 +135,7 @@ describe("completed partial process capture MCP projection", () => {
server.registerTool(
captureContract.name,
toolRegistrationOptions(captureContract),
async () => toCallToolResult(err(failure), captureContract),
async () => delivery.toCallToolResult(err(failure), captureContract),
);
const client = new Client({
name: "process-partial-error-client",
@@ -261,7 +266,7 @@ describe("incomplete partial process observations MCP projection", () => {
server.registerTool(
captureContract.name,
toolRegistrationOptions(captureContract),
async () => toCallToolResult(err(failure), captureContract),
async () => delivery.toCallToolResult(err(failure), captureContract),
);
const client = new Client({
name: "process-partial-observations-client",
@@ -305,7 +310,10 @@ describe("incomplete partial process observations MCP projection", () => {
describe("tool result projection", () => {
it("exposes an actionable adapter code to MCP callers", () => {
const result = toCallToolResult(err(new HopperProcessError(76)), contract);
const result = delivery.toCallToolResult(
err(new HopperProcessError(76)),
contract,
);
expect(result.structuredContent).toMatchObject({
error: {
code: "provider_unavailable",
@@ -315,7 +323,7 @@ describe("tool result projection", () => {
});
});
it("projects bounded private-display coordinates without raw stderr", () => {
const result = toCallToolResult(
const result = delivery.toCallToolResult(
err(
new HopperProcessError(80, {
component: "hopper_private_display",
@@ -350,7 +358,7 @@ describe("tool result projection", () => {
},
});
});
it("returns result and complete Evidence context in one call", () => {
it("returns one complete Evidence record with its typed normalized result", () => {
const evidence = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
@@ -365,25 +373,14 @@ describe("tool result projection", () => {
outputSchema: evidenceResultOf(z.object({ value: z.string() })),
};
const result = toCallToolResult(ok(evidence), evidenceContract);
expect(result.structuredContent).toMatchObject({
result: { value: "observed" },
evidence_id: evidence.evidence_id,
evidence: {
normalized_result: { value: "observed" },
provider: { id: "fixture", name: "Fixture", version: "1" },
operation: "fixture",
predicate_type: "rea.analysis",
parameters: {},
raw_result: null,
confidence: "observed",
authority: "shipped-artifact",
environment: null,
limitations: evidence.limitations,
locations: [],
evidence_links: [],
},
});
const result = delivery.toEvidenceToolResult(
evidence,
evidenceContract,
undefined,
);
expect(result.structuredContent).toEqual(evidence);
expect(result.structuredContent).not.toHaveProperty("result");
expect(result.structuredContent).not.toHaveProperty("evidence");
expect(result.content[0]).toMatchObject({
type: "text",
text: expect.stringContaining('"value":"observed"'),
@@ -391,7 +388,7 @@ describe("tool result projection", () => {
const parsed = evidenceContract.outputSchema.parse(
result.structuredContent,
);
expect(parseEvidence(parsed.evidence)).toEqual(evidence);
expect(parseEvidence(parsed)).toEqual(evidence);
});
it.each<JsonValue>([null, false, 0, "", [], { nested: [false, null, 7] }])(
@@ -406,22 +403,23 @@ describe("tool result projection", () => {
...contract,
outputSchema: evidenceResultOf(z.json()),
};
const result = toCallToolResult(ok(evidence), evidenceContract);
const result = delivery.toEvidenceToolResult(
evidence,
evidenceContract,
undefined,
);
const parsed = evidenceContract.outputSchema.parse(
result.structuredContent,
);
expect(parsed.result).toEqual(value);
expect(parseEvidence(parsed.evidence)).toEqual(evidence);
expect(parsed.normalized_result).toEqual(value);
expect(parseEvidence(parsed)).toEqual(evidence);
expect(result.content).toEqual([
{ type: "text", text: JSON.stringify(parsed) },
]);
const { normalized_result: _missingResult, ...incomplete } = evidence;
expect(
evidenceContract.outputSchema.safeParse({
...parsed,
evidence: incomplete,
}).success,
).toBe(false);
expect(evidenceContract.outputSchema.safeParse(incomplete).success).toBe(
false,
);
},
);
});
+23 -3
View File
@@ -7,7 +7,7 @@ import { z } from "zod";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { emptyArraySchema } from "../../../src/domain/emptyArraySchema.js";
import { processScenarioSchema } from "../../../src/domain/process/processScenario.js";
import { GENERATED_MCP_TOOL_CATALOG } from "../../../src/generatedMcpToolCatalog.js";
import { GENERATED_MCP_TOOL_CATALOG } from "../../fixtures/mcpToolCatalog.js";
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
interface ToolSchemas {
@@ -94,6 +94,23 @@ function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
idempotentHint: false,
openWorldHint: false,
},
export_web_scripts: {
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: false,
},
capture_process_scenario: {
openWorldHint: true,
},
export_evidence_bundle: {
readOnlyHint: false,
destructiveHint: true,
},
import_evidence_bundle: {
readOnlyHint: false,
destructiveHint: false,
},
} as const;
for (const [name, annotations] of Object.entries(expected))
@@ -383,8 +400,11 @@ describe("MCP root input schemas", () => {
for (const contract of TOOL_CONTRACTS) {
const inputSchema = advertised.get(contract.name)!.inputSchema;
expect(inputSchema.type, contract.name).toBe("object");
expect(inputSchema.properties, contract.name).toBeDefined();
expect(inputSchema.anyOf, contract.name).toBeUndefined();
expect(
inputSchema.properties !== undefined ||
Array.isArray(inputSchema.anyOf),
contract.name,
).toBe(true);
const validate = ajv.compile(inputSchema);
for (const example of contract.examples)
expect(
+20 -3
View File
@@ -13,8 +13,9 @@ import {
} from "../../fixtures/webModuleTrace.js";
it("publishes valid SDK schemas and records the named module trace without a binary target", async () => {
const artifacts = webModuleArtifactsFixture();
const service = new WebModuleTraceService(
{ load: () => Promise.resolve(ok(webModuleArtifactsFixture())) },
{ load: () => Promise.resolve(ok(artifacts)) },
webModuleResolverFixture,
);
const session = createTestBinarySession(() => {
@@ -53,8 +54,24 @@ it("publishes valid SDK schemas and records the named module trace without a bin
const parsed = toolContract("trace_web_module_imports").outputSchema.parse(
response.structuredContent,
);
const evidence = parseEvidence(parsed.evidence);
expect(parsed.result).toEqual(evidence.normalized_result);
const evidence = parseEvidence(parsed);
expect(evidence.normalized_result).toMatchObject({
importer: {
url: artifacts.manifest.scripts[0]?.url,
basis: "reported-source-url",
},
imports: [
{
resolution: { state: "resolved", url: "https://app.test/dep.js" },
execution: "unknown",
},
{
resolution: { state: "unknown", reason: "computed-specifier" },
execution: "unknown",
},
],
});
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
const invalid = await client.callTool({
name: "trace_web_module_imports",
@@ -72,9 +72,9 @@ it("publishes valid SDK schemas and retains historical inline Evidence with the
const parsed = toolContract("inspect_web_network_capture").outputSchema.parse(
response.structuredContent,
);
const evidence = parseEvidence(parsed.evidence);
expect(parsed.result).toEqual(evidence.normalized_result);
const capture = webNetworkCaptureSchema.parse(parsed.result);
const evidence = parseEvidence(parsed);
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
const capture = webNetworkCaptureSchema.parse(parsed.normalized_result);
expect(capture.container.reported).toEqual({
creator: "fixture",
["__proto__"]: { preserved: 7 },
+2 -2
View File
@@ -61,8 +61,8 @@ it("advertises actual SDK schemas, instrumentation effects and session-owned inl
const parsed = toolContract(name).outputSchema.parse(
response.structuredContent,
);
const evidence = parseEvidence(parsed.evidence);
expect(parsed.result).toEqual(evidence.normalized_result);
const evidence = parseEvidence(parsed);
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
}
expect(toolContract("observe_web_execution").effects).toMatchObject({
@@ -58,8 +58,22 @@ it("publishes valid SDK schemas and records the named module trace without a bin
const parsed = toolContract("trace_web_source_location").outputSchema.parse(
response.structuredContent,
);
const evidence = parseEvidence(parsed.evidence);
expect(parsed.result).toEqual(evidence.normalized_result);
const evidence = parseEvidence(parsed);
const data = webSourceLocationFixture();
expect(evidence).toMatchObject({
normalized_result: {
source: { sha256: data.sourceFile.sha256 },
source_map: {
association: "caller-selected",
sha256: data.sourceMap.file.sha256,
},
matches: [{ state: "mapped", content: { text: "original" } }],
execution: "unknown",
source_authenticity: "unknown",
},
raw_result: { source_map_text: data.sourceMap.text },
});
expect(parsed.normalized_result).toEqual(evidence.normalized_result);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
const invalid = await client.callTool({
name: "trace_web_source_location",
@@ -1,240 +0,0 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import { Ajv2020 } from "ajv/dist/2020.js";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { browserCaptureComparisonInputSchema } from "../../../src/domain/browserCaptureComparison.js";
import { webPageInspectionSchema } from "../../../src/domain/browserObservation.js";
import { GENERATED_MCP_TOOL_CATALOG } from "../../../src/generatedMcpToolCatalog.js";
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
function resolveLocalReference(root: unknown, reference: string): unknown {
if (reference === "#") return root;
if (!reference.startsWith("#/")) return undefined;
let current = root;
for (const part of reference.slice(2).split("/")) {
const key = part.replaceAll("~1", "/").replaceAll("~0", "~");
if (!isRecord(current) || !Object.hasOwn(current, key)) return undefined;
current = current[key];
}
return current;
}
// Count object/array and composition levels, following references per path.
// Definitions, property maps, and literal example/default data are not levels.
function inputDepth(
schema: unknown,
root: unknown = schema,
activeReferences: readonly string[] = [],
): number {
if (!isRecord(schema)) return 0;
let referenceDepth = 0;
if (typeof schema.$ref === "string") {
if (activeReferences.includes(schema.$ref)) return Number.POSITIVE_INFINITY;
const target = resolveLocalReference(root, schema.$ref);
if (target === undefined) return Number.POSITIVE_INFINITY;
referenceDepth = inputDepth(target, root, [
...activeReferences,
schema.$ref,
]);
}
const childDepths: number[] = [];
for (const key of ["properties", "patternProperties", "dependentSchemas"]) {
const group = schema[key];
if (isRecord(group))
for (const child of Object.values(group))
childDepths.push(inputDepth(child, root, activeReferences));
}
for (const key of [
"items",
"additionalProperties",
"contains",
"not",
"if",
"then",
"else",
"propertyNames",
"unevaluatedProperties",
"unevaluatedItems",
])
childDepths.push(inputDepth(schema[key], root, activeReferences));
for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"]) {
const children = schema[key];
if (Array.isArray(children))
for (const child of children)
childDepths.push(inputDepth(child, root, activeReferences));
}
const types = Array.isArray(schema.type) ? schema.type : [schema.type];
const container = types.includes("object") || types.includes("array") ? 1 : 0;
const composition = ["anyOf", "oneOf", "allOf"].some((key) =>
Array.isArray(schema[key]),
)
? 1
: 0;
return Math.max(
referenceDepth,
container + composition + Math.max(0, ...childDepths),
);
}
function inputDepthViolations(
tools: readonly { name: string; inputSchema: unknown }[],
) {
return tools.flatMap(({ name, inputSchema }) => {
const depth = inputDepth(inputSchema);
return depth > 10 ? [{ name, depth }] : [];
});
}
async function withCatalog(
verify: (client: Client, calls: ReadonlyMap<string, number>) => Promise<void>,
): Promise<void> {
const server = new McpServer({ name: "wire-limits", version: "0" });
const calls = new Map<string, number>();
for (const contract of TOOL_CONTRACTS)
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async () => {
calls.set(contract.name, (calls.get(contract.name) ?? 0) + 1);
return { content: [], isError: true };
},
);
const client = new Client({ name: "wire-limits", version: "0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
await verify(client, calls);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
}
describe("complete catalog input compatibility profile (#919)", () => {
it("follows shared and escaped references without treating data as schemas", () => {
const diamond = {
type: "object",
properties: {
left: { $ref: "#/$defs/a~1b~0c" },
right: { $ref: "#/$defs/a~1b~0c" },
},
$defs: {
"a/b~c": { type: "object", properties: { id: { type: "string" } } },
unused: { $ref: "#/$defs/unused" },
},
examples: [{ $ref: "#" }],
default: { $ref: "#" },
};
expect(inputDepth(diamond)).toBe(2);
expect(
inputDepth({ type: "object", properties: { child: { $ref: "#" } } }),
).toBe(Number.POSITIVE_INFINITY);
expect(
inputDepth({
type: "object",
properties: {
values: {
anyOf: [
{ type: "array", items: { type: "object" } },
{ type: "null" },
],
},
},
}),
).toBe(4);
});
it("keeps every live and generated input within ten structural levels", async () => {
await withCatalog(async (client) => {
const { tools } = await client.listTools();
expect(tools.map(({ name }) => name).sort()).toEqual(
TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
expect(inputDepthViolations(tools)).toEqual([]);
expect(inputDepthViolations(GENERATED_MCP_TOOL_CATALOG)).toEqual([]);
});
});
it("describes capture round trips without altering domain or scenario schemas", () => {
const contract = TOOL_CONTRACTS.find(
({ name }) => name === "compare_web_captures",
);
if (contract === undefined)
throw new Error("Missing capture comparison contract");
const original = z.toJSONSchema(browserCaptureComparisonInputSchema, {
io: "input",
});
const projected = z.toJSONSchema(contract.inputSchema, { io: "input" });
expect(inputDepth(original)).toBeGreaterThan(10);
expect(inputDepth(projected)).toBeLessThanOrEqual(10);
expect(isRecord(original.properties)).toBe(true);
expect(isRecord(projected.properties)).toBe(true);
if (!isRecord(original.properties) || !isRecord(projected.properties))
throw new Error("Missing comparison properties");
for (const key of ["normalization"])
expect(projected.properties[key], key).toEqual(original.properties[key]);
expect(z.toJSONSchema(webPageInspectionSchema).properties).toHaveProperty(
"network",
);
for (const example of contract.examples)
expect(contract.inputSchema.parse(example.input)).toEqual(
browserCaptureComparisonInputSchema.parse(example.input),
);
const example = contract.examples[0];
if (example === undefined) throw new Error("Missing scenario example");
for (const malformed of [
{ before_scenario: {}, after_scenario: {} },
{
...example.input,
before: { inspection: {} },
after: { inspection: {} },
},
{ ...example.input, __unexpected_root_key__: true },
]) {
const originalResult =
browserCaptureComparisonInputSchema.safeParse(malformed);
const projectedResult = contract.inputSchema.safeParse(malformed);
expect(originalResult.success).toBe(false);
expect(projectedResult.success).toBe(false);
if (!originalResult.success && !projectedResult.success)
expect(projectedResult.error.issues).toEqual(
originalResult.error.issues,
);
}
});
it("rejects incomplete round-trip payloads before invoking the handler", async () => {
await withCatalog(async (client, calls) => {
const tool = (await client.listTools()).tools.find(
({ name }) => name === "compare_web_captures",
);
if (tool === undefined)
throw new Error("Missing advertised comparison tool");
const incomplete = {
before: { inspection: {} },
after: { inspection: {} },
};
const validate = new Ajv2020({
strict: false,
validateFormats: false,
}).compile(tool.inputSchema);
expect(validate(incomplete)).toBe(true);
expect(
browserCaptureComparisonInputSchema.safeParse(incomplete).success,
).toBe(false);
const result = await client.callTool({
name: tool.name,
arguments: incomplete,
});
expect(result.isError).toBe(true);
expect(calls.get(tool.name) ?? 0).toBe(0);
});
});
});
@@ -1,3 +1,4 @@
import { parseConfig } from "../../../src/config.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -48,8 +49,7 @@ describe("MCP composed workflow snapshot replay", () => {
const calls: string[] = [];
const provider = makeProvider(starts, calls);
const session = createTestBinarySession(provider, {
resolveAnalysisProfile: () =>
Promise.resolve(ok({ profile, compatibility: {} })),
resolveAnalysisProfile: () => Promise.resolve(ok({ profile })),
});
const server = createServer(session, session, { logger: silentLogger });
const mcp = new Client({ name: "workflow-snapshot", version: "1.0.0" });
@@ -78,7 +78,7 @@ describe("MCP composed workflow snapshot replay", () => {
analysis_profile: z.object({ digest: z.string() }),
})
.passthrough()
.parse(output.evidence);
.parse(output);
const afterAnalysisCalls = [...calls];
const afterAnalysisStarts = [...starts];
@@ -94,9 +94,8 @@ describe("MCP composed workflow snapshot replay", () => {
).result;
expect(receipt).toMatchObject({
path: snapshotPath,
entries: snapshot.value.entries.length,
primitive_entries: snapshot.value.entries.length,
workflow_entries: snapshot.value.workflow_entries?.length ?? 0,
workflow_entries: snapshot.value.workflow_entries.length,
evidence_records: snapshot.value.evidence_bundle.records.length,
});
expect(snapshot.value.workflow_entries).toHaveLength(1);
@@ -108,15 +107,14 @@ describe("MCP composed workflow snapshot replay", () => {
);
const dependencies: DirectAnalysisDependencies = {
readConfiguration: () => parseConfig({}),
createBinarySession: () =>
createTestBinarySession(provider, {
resolveAnalysisProfile: () =>
Promise.resolve(ok({ profile, compatibility: {} })),
resolveAnalysisProfile: () => Promise.resolve(ok({ profile })),
}),
createManagedBinarySession: () =>
createTestBinarySession(provider, {
resolveAnalysisProfile: () =>
Promise.resolve(ok({ profile, compatibility: {} })),
resolveAnalysisProfile: () => Promise.resolve(ok({ profile })),
}),
};
const replay = await runDirectAnalysis(
@@ -127,7 +125,7 @@ describe("MCP composed workflow snapshot replay", () => {
{ snapshotPath },
);
expect(replay).toEqual(output.evidence);
expect(replay).toEqual(output);
expect(calls).toEqual(afterAnalysisCalls);
expect(starts).toEqual(afterAnalysisStarts);
});
@@ -144,8 +142,7 @@ describe("MCP composed workflow snapshot replay", () => {
const session = createTestBinarySession(
makeProvider(starts, calls, "list_strings"),
{
resolveAnalysisProfile: () =>
Promise.resolve(ok({ profile, compatibility: {} })),
resolveAnalysisProfile: () => Promise.resolve(ok({ profile })),
},
);
const server = createServer(session, session, { logger: silentLogger });
@@ -175,7 +172,7 @@ describe("MCP composed workflow snapshot replay", () => {
expect(
toolContract("binary_overview").outputSchema.parse(
analyzed.structuredContent,
).evidence,
),
).toMatchObject({ operation: "binary_overview" });
const closed = await mcp.callTool({
name: "close_binary",
@@ -185,7 +182,7 @@ describe("MCP composed workflow snapshot replay", () => {
const snapshot = await readAnalysisSnapshot(snapshotPath);
if (!snapshot.ok) throw snapshot.error;
expect(snapshot.value.workflow_entries ?? []).toEqual([]);
expect(snapshot.value.workflow_entries).toEqual([]);
});
});
@@ -214,8 +211,7 @@ const makeProvider = (
return {
identity: () => identity,
capabilities: () => capabilities,
resolveAnalysisProfile: () =>
Promise.resolve(ok({ profile, compatibility: {} })),
resolveAnalysisProfile: () => Promise.resolve(ok({ profile })),
createClient: () => {
starts.push("start");
return {
@@ -233,7 +229,7 @@ const makeProvider = (
: { "0x1000": "fixture" };
return ok(createAnalysisExecution(result, identity));
},
close: () => Promise.resolve(),
close: () => Promise.resolve(ok(null)),
};
},
};