refactor: return complete tool results inline

This commit is contained in:
morluto
2026-09-29 07:08:46 +08:00
parent 2160d4fae5
commit 0d96275b68
535 changed files with 4084 additions and 13537 deletions
@@ -0,0 +1,63 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { expect, it } from "vitest";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import { createServer } from "../../../src/server/createServer.js";
it("returns every artifact occurrence in one MCP call", async () => {
const directory = await createTestTempDirectory("rea-artifact-inline-");
const archive = join(directory, "many.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
const fileCount = 520;
for (let index = 0; index < fileCount; index += 1) {
await writer.add(
`files/${String(index)}.txt`,
new TextReader(`file-${String(index)}`),
);
}
await writeFile(archive, await writer.close());
const session = createTestBinarySession(new ArtifactProvider());
const server = createServer(session, session);
const client = new Client({ name: "artifact-inline-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const opened = await client.callTool({
name: "open_binary",
arguments: { path: archive },
});
expect(opened.isError).not.toBe(true);
const result = await client.callTool({
name: "inventory_artifact",
arguments: {},
});
expect(result.isError, JSON.stringify(result.structuredContent)).not.toBe(
true,
);
const inventory = z
.object({
occurrences: z.object({
items: z.array(z.object({ logical_path: z.string() })),
total: z.number(),
}),
})
.parse(
z.object({ result: z.unknown() }).parse(result.structuredContent)
.result,
);
expect(inventory.occurrences.items).toHaveLength(fileCount + 1);
expect(inventory.occurrences.total).toBe(fileCount + 1);
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
});
+36 -51
View File
@@ -12,7 +12,6 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import { ARTIFACT_COMPARISON_EXAMPLE } from "../../../src/contracts/artifactComparisonExample.js";
import { evidenceBundleSchema } from "../../../src/domain/evidenceBundle.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
@@ -99,6 +98,7 @@ const artifactInventoryResultSchema = z.object({
items: z.array(
z.object({ logical_path: z.string(), hash_status: z.string() }),
),
total: z.number(),
}),
integrity_contradictions: z.array(
z.object({
@@ -144,18 +144,6 @@ it("records an approved mismatch, preserves verified siblings, and never reports
name: "open_binary",
arguments: { path: archive },
});
const limited = await client.callTool({
name: "inventory_artifact",
arguments: {
integrity_policy: "record-and-continue",
integrity_continue_approved: true,
max_integrity_mismatches: 1,
},
});
expect(limited).toMatchObject({
isError: true,
structuredContent: { error: { code: "truncated" } },
});
const result = await client.callTool({
name: "inventory_artifact",
arguments: {
@@ -163,7 +151,9 @@ it("records an approved mismatch, preserves verified siblings, and never reports
integrity_continue_approved: true,
},
});
expect(result.isError).not.toBe(true);
expect(result.isError, JSON.stringify(result.structuredContent)).not.toBe(
true,
);
const compact = compactResult(result.structuredContent);
const evidence = session.evidenceById(compact.evidence_id);
if (evidence === undefined) throw new Error("missing inventory Evidence");
@@ -275,7 +265,12 @@ it("rejects altered payloads that reuse session Evidence IDs", async () => {
},
});
expect(result.isError).toBe(true);
expect(session.exportEvidenceBundle().records).toHaveLength(2);
expect(
session.evidenceById(ARTIFACT_COMPARISON_EXAMPLE.left.evidence_id),
).toBeDefined();
expect(
session.evidenceById(ARTIFACT_COMPARISON_EXAMPLE.right.evidence_id),
).toBeDefined();
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
@@ -302,13 +297,18 @@ it("rejects comparison Evidence that is not owned by the session", async () => {
arguments: ARTIFACT_COMPARISON_EXAMPLE,
});
expect(result.isError).toBe(true);
expect(session.exportEvidenceBundle().records).toEqual([]);
expect(
session.evidenceById(ARTIFACT_COMPARISON_EXAMPLE.left.evidence_id),
).toBeUndefined();
expect(
session.evidenceById(ARTIFACT_COMPARISON_EXAMPLE.right.evidence_id),
).toBeUndefined();
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
});
it("opens archives without Hopper, compares them, and exports linked evidence", async () => {
it("returns full artifact graphs inline and compares changed inventories", async () => {
const directory = await createTestTempDirectory("rea-artifact-mcp-");
const archive = join(directory, "fixture.ipa");
const changedArchive = join(directory, "changed.ipa");
@@ -336,7 +336,7 @@ it("opens archives without Hopper, compares them, and exports linked evidence",
expect(opened.isError).not.toBe(true);
const inspected = await client.callTool({
name: "inspect_artifact",
arguments: { max_observations: 1, max_relationships: 1 },
arguments: {},
});
expect(inspected.isError).not.toBe(true);
const inspectionResult = compactResult(inspected.structuredContent);
@@ -354,10 +354,9 @@ it("opens archives without Hopper, compares them, and exports linked evidence",
}),
),
coverage: z.object({
status: z.literal("truncated"),
status: z.literal("complete-within-substeps"),
substeps_completed: z.literal(1),
}),
unexplored_branches: z.array(z.object({ reason: z.string() })),
})
.parse(inspectionResult.result);
expect(inspection.substeps).toHaveLength(1);
@@ -367,11 +366,6 @@ it("opens archives without Hopper, compares them, and exports linked evidence",
expect(inspectionEvidence.evidence_links).toEqual([
inspection.substeps[0]?.evidence_id,
]);
expect(inspection.unexplored_branches).toEqual(
expect.arrayContaining([
expect.objectContaining({ reason: "page-limit" }),
]),
);
const inventory = await client.callTool({
name: "inventory_artifact",
arguments: {},
@@ -384,9 +378,22 @@ it("opens archives without Hopper, compares them, and exports linked evidence",
provider: { id: "rea-artifact-graph" },
subject: { format: "ipa" },
});
expect(inventoryResult.result).toMatchObject({
manifest: { root_format: "ipa" },
});
expect(
z
.object({
manifest: z.object({ root_format: z.literal("ipa") }),
occurrences: z.object({
items: z.array(z.object({ logical_path: z.string() })),
}),
})
.parse(inventoryResult.result).occurrences.items,
).toEqual(
expect.arrayContaining([
expect.objectContaining({
logical_path: "Payload/Fixture.app/main.js",
}),
]),
);
const openedChanged = await client.callTool({
name: "open_binary",
arguments: { path: changedArchive },
@@ -421,32 +428,11 @@ it("opens archives without Hopper, compares them, and exports linked evidence",
result: {
items: [
expect.objectContaining({
unknown: expect.objectContaining({
domain: "artifact-comparison",
}),
domain: "artifact-comparison",
}),
],
},
});
const snapshotted = await client.callTool({
name: "snapshot_evidence_bundle",
arguments: {},
});
const bundleUri = z
.object({ result: z.object({ bundle_uri: z.string() }) })
.parse(snapshotted.structuredContent).result.bundle_uri;
const bundleResource = await client.readResource({ uri: bundleUri });
const bundle = evidenceBundleSchema.parse(
JSON.parse(
z.object({ text: z.string() }).parse(bundleResource.contents[0]).text,
),
);
expect(bundle.records).toHaveLength(6);
expect(bundle.artifacts).toContainEqual({
digest: { sha256: evidence.subject?.digest.sha256 },
format: "ipa",
architecture: null,
});
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
@@ -457,6 +443,5 @@ const compactResult = (value: unknown) =>
.object({
result: z.unknown(),
evidence_id: z.string(),
evidence_uri: z.string(),
})
.parse(value);
+5 -7
View File
@@ -53,7 +53,7 @@ it(
);
const status = await connected.client.callTool({
name: "binary_session",
arguments: { detail: "full" },
arguments: {},
});
expect(status.structuredContent).toMatchObject({
result: {
@@ -77,7 +77,7 @@ it(
expect(listed.isError).not.toBe(true);
expect(listed.structuredContent).toMatchObject({
result: {
targets: { items: [{ target_id: "allowed-page" }] },
targets: [{ target_id: "allowed-page" }],
},
});
const unapprovedSourceCapture = await connected.client.callTool({
@@ -246,12 +246,10 @@ const verifySessionAndComparisonTools = async (
result: { status: "identical", changed_pixels: 0 },
});
const evidenceId = evidenceIdOf(inspected.structuredContent);
const evidence = await connected.client.readResource({
uri: `rea://evidence/${evidenceId}`,
expect(inspected.structuredContent).toMatchObject({
evidence_id: evidenceId,
result: expect.any(Object),
});
expect(evidence.contents[0]).toEqual(
expect.objectContaining({ text: expect.stringContaining(evidenceId) }),
);
};
it("denies origins outside the administrator ceiling before CDP attach", async () => {
@@ -75,7 +75,6 @@ const captureFor = (scenario: BrowserScenario): BrowserScenarioCapture => {
},
});
return browserScenarioCaptureSchema.parse({
schema_version: 1,
browser: {
mode: scenario.browser.mode,
process_ownership: "provider-owned",
@@ -108,7 +107,6 @@ const captureFor = (scenario: BrowserScenario): BrowserScenarioCapture => {
};
const scenario = (origin = "https://app.example.test") => ({
schema_version: 1,
browser: {
mode: "launch",
executable_path: process.execPath,
@@ -72,7 +72,6 @@ describe("bundle comparison MCP integration", () => {
expect(result.structuredContent).toMatchObject({
result: { status: "changed" },
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
evidence_uri: expect.stringMatching(/^rea:\/\/evidence\/ev_/u),
});
} finally {
await connected.close();
+16 -96
View File
@@ -58,7 +58,6 @@ it("exposes root-confined Electron discovery and inspection as Evidence v2", asy
REA_ELECTRON_OBSERVE_ENABLED: "true",
REA_ELECTRON_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
REA_ELECTRON_FILE_ROOTS_JSON: JSON.stringify([root]),
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
});
if (!config.ok) throw config.error;
const authority = await loadConfiguredPermissionAuthority(config.value);
@@ -95,7 +94,7 @@ it("exposes root-confined Electron discovery and inspection as Evidence v2", asy
expect(listed.isError).not.toBe(true);
expect(listed.structuredContent).toMatchObject({
result: {
targets: { items: [{ target_id: "electron-page" }] },
targets: [{ target_id: "electron-page" }],
},
});
const inspected = await client.callTool({
@@ -112,7 +111,7 @@ it("exposes root-confined Electron discovery and inspection as Evidence v2", asy
});
const analyzed = await client.callTool({
name: "analyze_javascript_application",
arguments: { input_path: root, approved: true, detail: "full" },
arguments: { input_path: root },
});
expect(analyzed.isError).not.toBe(true);
expect(analyzed.structuredContent).toMatchObject({
@@ -122,7 +121,7 @@ it("exposes root-confined Electron discovery and inspection as Evidence v2", asy
expect(analysisText).toBeDefined();
if (analysisText?.type !== "text")
throw new TypeError("Missing JavaScript analysis text projection");
expect(analysisText.text).not.toContain('"nodes":[');
expect(analysisText.text).toContain('"nodes":[');
const reconciled = await client.callTool({
name: "reconcile_javascript_runtime",
arguments: {
@@ -242,7 +241,6 @@ it("exposes active Electron scenarios through the separately granted MCP boundar
const captured = await client.callTool({
name: "capture_electron_scenario",
arguments: {
schema_version: 1,
executable_path: process.execPath,
application_path: join(aliasedRoot, "main.js"),
application_root: aliasedRoot,
@@ -292,9 +290,7 @@ it("exposes the target-free static JavaScript application workflow", async () =>
const root = await createTestTempDirectory("rea-electron-static-mcp-");
temporary.push(root);
await writeElectronBoundaryFixture(root);
const config = parseConfig({
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
});
const config = parseConfig({});
if (!config.ok) throw config.error;
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok) throw authority.error;
@@ -322,7 +318,7 @@ it("exposes the target-free static JavaScript application workflow", async () =>
const analyzed = await client.callTool({
name: "analyze_javascript_application",
arguments: { input_path: root, approved: true },
arguments: { input_path: root },
});
expect(analyzed.isError).not.toBe(true);
@@ -330,9 +326,7 @@ it("exposes the target-free static JavaScript application workflow", async () =>
.object({
evidence_id: z.string(),
result: z.object({
schema_version: z.literal(2),
input_path: z.string(),
unknowns: z.array(z.string()),
summary: z.object({
browser_windows: z.number(),
context_bridge_apis: z.number(),
@@ -340,19 +334,19 @@ it("exposes the target-free static JavaScript application workflow", async () =>
}),
graph: z.object({
graph_id: z.string(),
node_count: z.number(),
edge_count: z.number(),
top_findings: z.array(z.unknown()),
pages: z.object({ nodes: z.string(), edges: z.string() }),
nodes: z.array(z.unknown()),
edges: z.array(z.unknown()),
}),
semantic_graph: z.object({
graph_id: z.string(),
nodes: z.number(),
relations: z.number(),
unknown_frontiers: z.number(),
query_tool: z.literal("trace_javascript_semantics"),
nodes: z.array(z.unknown()),
relations: z.array(z.unknown()),
}),
}),
evidence: z.object({
operation: z.literal("analyze_javascript_application"),
parameters: z.object({ format: z.string() }),
}),
})
.parse(analyzed.structuredContent);
expect(projected.result).toMatchObject({
@@ -363,83 +357,9 @@ it("exposes the target-free static JavaScript application workflow", async () =>
ipc: { paired_renderer_transmissions: 4 },
},
});
expect(projected.result.graph.node_count).toBeGreaterThan(0);
expect(projected.result.semantic_graph.nodes).toBeGreaterThan(0);
expect(JSON.stringify(analyzed.structuredContent)).not.toContain('"nodes":[');
const nodePage = await client.readResource({
uri: projected.result.graph.pages.nodes,
});
const nodeContent = nodePage.contents[0];
if (nodeContent === undefined || !("text" in nodeContent))
throw new TypeError("Missing JavaScript application graph node page");
expect(JSON.parse(nodeContent.text)).toMatchObject({
evidence_id: projected.evidence_id,
graph_id: projected.result.graph.graph_id,
collection: "nodes",
items: expect.any(Array),
offset: 0,
limit: 100,
});
});
it("reports an unconfigured investigation ceiling before static analysis", async () => {
const root = await createTestTempDirectory("rea-electron-denied-mcp-");
temporary.push(root);
await writeElectronBoundaryFixture(root);
const config = parseConfig({});
if (!config.ok) throw config.error;
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok) throw authority.error;
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
permissionAuthority: authority.value,
});
const client = new Client({
name: "electron-denied-mcp-test",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server, session);
await server.connect(serverTransport);
await client.connect(clientTransport);
const status = await client.callTool({
name: "binary_session",
arguments: {
detail: "capabilities",
capability_family: "electron-provider",
limit: 100,
},
});
expect(status.structuredContent).toMatchObject({
result: {
capabilities: {
items: expect.arrayContaining([
expect.objectContaining({
name: "analyze_javascript_application",
available: false,
reason: "policy_disabled",
}),
expect.objectContaining({
name: "reconcile_javascript_runtime",
available: true,
reason: "available",
}),
]),
},
},
});
expect(
(await client.listTools()).tools.some(
({ name }) => name === "analyze_javascript_application",
),
).toBe(true);
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");
});
const evidenceFor = (session: BinarySession, value: unknown) => {
@@ -25,24 +25,18 @@ const PROCEDURES = {
"0x6": "prefix_TtOther",
};
const page = (values: Readonly<Record<string, string>>) => ({
items: Object.entries(values).map(([address, value]) => ({ address, value })),
offset: 0,
limit: 100,
total: Object.keys(values).length,
next_offset: null,
has_more: false,
});
const inventory = (values: Readonly<Record<string, string>>) =>
Object.entries(values).map(([address, value]) => ({ address, value }));
const fixturePort = (): AnalysisOperationPort => ({
execute: (name, arguments_) => {
switch (name) {
case "list_procedures":
return Promise.resolve(ok(page(PROCEDURES)));
return Promise.resolve(ok(inventory(PROCEDURES)));
case "list_names":
return Promise.resolve(
ok(
page({
inventory({
"0x10": "_OBJC_CLASS_$_Fixture",
"0x11": "_OBJC_CLASS_$_Fixture",
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
@@ -93,7 +87,11 @@ const fixturePort = (): AnalysisOperationPort => ({
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(ok(page({ "0x30": "hello" })));
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
case "search_strings":
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
case "search_procedures":
return Promise.resolve(ok(inventory({})));
case "analyze_function":
return Promise.resolve(
ok({
@@ -103,29 +101,16 @@ const fixturePort = (): AnalysisOperationPort => ({
signature: null,
locals: [],
},
pseudocode: {
text: "return 0;",
total_chars: 9,
returned_chars: 9,
truncated: false,
next_offset: null,
},
assembly: {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
},
comments: emptyBounded(),
callers: emptyBounded(),
callees: emptyBounded(),
incoming_references: emptyBounded(),
outgoing_references: emptyBounded(),
referenced_strings: emptyBounded(),
referenced_names: emptyBounded(),
basic_blocks: emptyBounded(),
instruction_scan: { scanned: 0, truncated: false },
pseudocode: "return 0;",
assembly: [],
comments: [],
callers: [],
callees: [],
incoming_references: [],
outgoing_references: [],
referenced_strings: [],
referenced_names: [],
basic_blocks: [],
}),
);
default:
@@ -134,14 +119,6 @@ const fixturePort = (): AnalysisOperationPort => ({
},
});
const emptyBounded = () => ({
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
});
const resources: Array<{ close(): Promise<void> }> = [];
afterEach(async () => {
@@ -218,15 +195,15 @@ describe("enhanced MCP tools", () => {
["get_objc_classes", { pattern: "Fixture" }],
["get_objc_protocols", {}],
["batch_decompile", { addresses: ["0x1", "0x2"] }],
["get_call_graph", { address: "0x1", direction: "forward", depth: 2 }],
["get_call_graph", { address: "0x1", direction: "forward" }],
["analyze_swift_types", {}],
["find_xrefs_to_name", { name: "entry" }],
["binary_overview", {}],
["analyze_function", { procedure: "0x1" }],
["inspect_native_api", { procedure: "0x1" }],
["trace_feature", { query: "hello", max_operations: 10 }],
["find_code_for_string", { query: "hello", max_operations: 10 }],
["trace_call_path", { start: "0x1", goal: "0x2", max_operations: 10 }],
["trace_feature", { query: "hello" }],
["find_code_for_string", { query: "hello" }],
["trace_call_path", { start: "0x1", goal: "0x2" }],
] as const;
const results = await Promise.all(
calls.map(async ([name, arguments_]) =>
@@ -267,7 +244,7 @@ describe("enhanced MCP tools", () => {
});
expect(results[8]).toMatchObject({
procedure: { address: "0x1", name: "entry" },
pseudocode: { text: "return 0;" },
pseudocode: "return 0;",
});
expect(results[9]).toMatchObject({
procedure: { address: "0x1", name: "entry" },
@@ -17,24 +17,18 @@ const PROCEDURES = {
"0x6": "prefix_TtOther",
};
const page = (values: Readonly<Record<string, string>>) => ({
items: Object.entries(values).map(([address, value]) => ({ address, value })),
offset: 0,
limit: 100,
total: Object.keys(values).length,
next_offset: null,
has_more: false,
});
const inventory = (values: Readonly<Record<string, string>>) =>
Object.entries(values).map(([address, value]) => ({ address, value }));
const fixturePort = (): AnalysisOperationPort => ({
execute: (name, arguments_) => {
switch (name) {
case "list_procedures":
return Promise.resolve(ok(page(PROCEDURES)));
return Promise.resolve(ok(inventory(PROCEDURES)));
case "list_names":
return Promise.resolve(
ok(
page({
inventory({
"0x10": "_OBJC_CLASS_$_Fixture",
"0x11": "_OBJC_CLASS_$_Fixture",
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
@@ -85,7 +79,7 @@ const fixturePort = (): AnalysisOperationPort => ({
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(ok(page({ "0x30": "hello" })));
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
case "analyze_function":
return Promise.resolve(
ok({
@@ -154,15 +148,13 @@ const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
};
describe("enhanced MCP tools", () => {
it("returns Evidence IDs and explicit call-path frontiers at limits", async () => {
it("returns Evidence IDs and a complete call path", async () => {
const client = await connect();
const result = await client.callTool({
name: "trace_call_path",
arguments: {
start: "0x1",
goal: "0x3",
max_nodes: 1,
max_operations: 10,
},
});
@@ -170,19 +162,12 @@ describe("enhanced MCP tools", () => {
expect(result.structuredContent).toMatchObject({
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
result: {
goal_status: "not_reached",
nodes: [{ address: "0x1", depth: 0 }],
frontier: ["0x2"],
truncated: true,
residual_unknowns: expect.arrayContaining([
expect.stringContaining("reached the node limit"),
expect.stringContaining("reached the edge limit"),
goal_status: "reached",
nodes: expect.arrayContaining([
expect.objectContaining({ address: "0x1" }),
expect.objectContaining({ address: "0x3" }),
]),
limits: {
max_nodes: 1,
nodes_visited: 1,
operations_used: 1,
},
truncated: false,
},
});
});
@@ -22,24 +22,18 @@ const PROCEDURES = {
"0x6": "prefix_TtOther",
};
const page = (values: Readonly<Record<string, string>>) => ({
items: Object.entries(values).map(([address, value]) => ({ address, value })),
offset: 0,
limit: 100,
total: Object.keys(values).length,
next_offset: null,
has_more: false,
});
const inventory = (values: Readonly<Record<string, string>>) =>
Object.entries(values).map(([address, value]) => ({ address, value }));
const fixturePort = (): AnalysisOperationPort => ({
execute: (name, arguments_) => {
switch (name) {
case "list_procedures":
return Promise.resolve(ok(page(PROCEDURES)));
return Promise.resolve(ok(inventory(PROCEDURES)));
case "list_names":
return Promise.resolve(
ok(
page({
inventory({
"0x10": "_OBJC_CLASS_$_Fixture",
"0x11": "_OBJC_CLASS_$_Fixture",
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
@@ -90,7 +84,7 @@ const fixturePort = (): AnalysisOperationPort => ({
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(ok(page({ "0x30": "hello" })));
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
case "analyze_function":
return Promise.resolve(
ok({
@@ -195,13 +189,12 @@ describe("enhanced MCP tools", () => {
execute: (name) =>
name === "procedure_callees"
? Promise.resolve(err(new AnalysisOutputError(name, "failed")))
: Promise.resolve(ok(page({}))),
: Promise.resolve(ok(inventory({}))),
});
const graph = await tools.execute("get_call_graph", {
address: "0x1",
direction: "forward",
depth: 1,
});
const unresolved = await tools.execute("find_xrefs_to_name", {
name: "missing",
@@ -233,53 +226,72 @@ describe("enhanced MCP tools", () => {
});
});
it("follows procedure pagination for whole-binary workflows", async () => {
const offsets: number[] = [];
const client = await connect({
execute: (_name, arguments_) => {
const offset = arguments_.offset;
offsets.push(typeof offset === "number" ? offset : 0);
it("traverses the complete reachable call graph and stops at cycles", async () => {
const calls: string[] = [];
const tools = new EnhancedTools({
execute: (name, arguments_) => {
if (name !== "procedure_callees") return Promise.resolve(ok([]));
const address = String(arguments_.procedure);
calls.push(address);
const next = Number.parseInt(address.slice(2), 16) + 1;
return Promise.resolve(
ok({
items: [
{
address: offset === 500 ? "0x2" : "0x1",
value: offset === 500 ? "_TtC4Last" : "_TtC5First",
},
],
offset: typeof offset === "number" ? offset : 0,
limit: 500,
total: 2,
next_offset: offset === 500 ? null : 500,
has_more: offset !== 500,
}),
ok(next <= 8 ? [`0x${next.toString(16)}`] : ["0x2"]),
);
},
});
const result = await tools.execute("get_call_graph", {
address: "0x1",
direction: "forward",
});
expect(calls).toEqual([
"0x1",
"0x2",
"0x3",
"0x4",
"0x5",
"0x6",
"0x7",
"0x8",
]);
expect(result).toMatchObject({
ok: true,
value: {
"0": [{ address: "0x1", calls: ["0x2"], status: "ok" }],
"7": [{ address: "0x8", calls: ["0x2"], status: "ok" }],
},
});
});
it("uses every procedure in one complete inventory", async () => {
const calls: string[] = [];
const client = await connect({
execute: (name) => {
calls.push(name);
return Promise.resolve(
ok([
{ address: "0x1", value: "_TtC5First" },
{ address: "0x2", value: "_TtC4Last" },
]),
);
},
});
const result = jsonResult(
await client.callTool({ name: "swift_classes", arguments: {} }),
);
expect(offsets).toEqual([0, 500]);
expect(calls).toEqual(["list_procedures"]);
expect(result).toMatchObject({ count: 2 });
});
it("does not start another page after cancellation", async () => {
it("returns cancellation when a complete inventory call is cancelled", async () => {
const controller = new AbortController();
let calls = 0;
const analysis: AnalysisOperationPort = {
execute: () => {
calls += 1;
controller.abort();
return Promise.resolve(
ok({
items: [{ address: "0x1", value: "_TtC5First" }],
offset: 0,
limit: 500,
total: 2,
next_offset: 500,
has_more: true,
}),
);
return Promise.resolve(ok([{ address: "0x1", value: "_TtC5First" }]));
},
};
@@ -19,24 +19,18 @@ const PROCEDURES = {
"0x6": "prefix_TtOther",
};
const page = (values: Readonly<Record<string, string>>) => ({
items: Object.entries(values).map(([address, value]) => ({ address, value })),
offset: 0,
limit: 100,
total: Object.keys(values).length,
next_offset: null,
has_more: false,
});
const inventory = (values: Readonly<Record<string, string>>) =>
Object.entries(values).map(([address, value]) => ({ address, value }));
const fixturePort = (): AnalysisOperationPort => ({
execute: (name, arguments_) => {
switch (name) {
case "list_procedures":
return Promise.resolve(ok(page(PROCEDURES)));
return Promise.resolve(ok(inventory(PROCEDURES)));
case "list_names":
return Promise.resolve(
ok(
page({
inventory({
"0x10": "_OBJC_CLASS_$_Fixture",
"0x11": "_OBJC_CLASS_$_Fixture",
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
@@ -87,7 +81,7 @@ const fixturePort = (): AnalysisOperationPort => ({
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(ok(page({ "0x30": "hello" })));
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
case "analyze_function":
return Promise.resolve(
ok({
@@ -187,43 +181,31 @@ const jsonResult = (result: CallToolResult): JsonValue => {
};
describe("enhanced MCP tools", () => {
it("follows name pagination for exhaustive Objective-C discovery", async () => {
const offsets: number[] = [];
it("discovers every Objective-C class from one complete inventory", async () => {
const calls: string[] = [];
const client = await connect({
execute: (name, arguments_) => {
execute: (name) => {
expect(name).toBe("list_names");
const offset =
typeof arguments_.offset === "number" ? arguments_.offset : 0;
offsets.push(offset);
calls.push(name);
return Promise.resolve(
ok({
items: [
{
address: offset === 500 ? "0x2" : "0x1",
value:
offset === 500 ? "_OBJC_CLASS_$_Last" : "_OBJC_CLASS_$_First",
},
],
offset,
limit: 500,
total: 2,
next_offset: offset === 500 ? null : 500,
has_more: offset !== 500,
}),
ok([
{ address: "0x1", value: "_OBJC_CLASS_$_First" },
{ address: "0x2", value: "_OBJC_CLASS_$_Last" },
]),
);
},
});
const result = jsonResult(
await client.callTool({ name: "get_objc_classes", arguments: {} }),
);
expect(offsets).toEqual([0, 500]);
expect(calls).toEqual(["list_names"]);
expect(result).toMatchObject({ count: 2 });
});
it("honors overview detail and limit while reporting exhaustive totals", async () => {
const procedureOffsets: number[] = [];
it("returns the complete overview inline with exhaustive totals", async () => {
const inventoryCalls: string[] = [];
const client = await connect({
execute: (name, arguments_) => {
execute: (name) => {
switch (name) {
case "list_segments":
return Promise.resolve(
@@ -235,34 +217,22 @@ describe("enhanced MCP tools", () => {
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
inventoryCalls.push(name);
return Promise.resolve(
ok({
items: [{ address: "0x30", value: "first page only" }],
offset: 0,
limit: 100,
total: 700,
next_offset: 100,
has_more: true,
}),
ok(
Array.from({ length: 700 }, (_, index) => ({
address: `0x${(0x30 + index).toString(16)}`,
value: `string-${index}`,
})),
),
);
case "list_procedures": {
const offset =
typeof arguments_.offset === "number" ? arguments_.offset : 0;
procedureOffsets.push(offset);
inventoryCalls.push(name);
return Promise.resolve(
ok({
items: [
{
address: offset === 500 ? "0x2" : "0x1",
value: offset === 500 ? "last" : "first",
},
],
offset,
limit: 500,
total: 2,
next_offset: offset === 500 ? null : 500,
has_more: offset !== 500,
}),
ok([
{ address: "0x1", value: "first" },
{ address: "0x2", value: "last" },
]),
);
}
default:
@@ -273,15 +243,15 @@ describe("enhanced MCP tools", () => {
const result = jsonResult(
await client.callTool({
name: "binary_overview",
arguments: { detail: "detailed", limit: 1 },
arguments: {},
}),
);
expect(procedureOffsets).toEqual([0]);
expect(inventoryCalls).toEqual(["list_procedures", "list_strings"]);
expect(result).toEqual({
document: "fixture",
detail: "detailed",
segments: [
{ name: "__TEXT", start: "0x1000", end: "0x1800", length: 2048 },
{ name: "__DATA", start: "0x1800", end: "0x2000", length: 2048 },
],
segment_count: 2,
procedure_count: 2,
@@ -289,17 +259,12 @@ describe("enhanced MCP tools", () => {
});
});
it("rejects non-advancing pagination metadata", async () => {
it("rejects paginated provider output", async () => {
const client = await connect({
execute: () =>
Promise.resolve(
ok({
items: [{ address: "0x1", value: "_TtC5First" }],
offset: 0,
limit: 500,
total: 2,
next_offset: 0,
has_more: true,
}),
),
});
@@ -14,24 +14,18 @@ const PROCEDURES = {
"0x6": "prefix_TtOther",
};
const page = (values: Readonly<Record<string, string>>) => ({
items: Object.entries(values).map(([address, value]) => ({ address, value })),
offset: 0,
limit: 100,
total: Object.keys(values).length,
next_offset: null,
has_more: false,
});
const inventory = (values: Readonly<Record<string, string>>) =>
Object.entries(values).map(([address, value]) => ({ address, value }));
const fixturePort = (): AnalysisOperationPort => ({
execute: (name, arguments_) => {
switch (name) {
case "list_procedures":
return Promise.resolve(ok(page(PROCEDURES)));
return Promise.resolve(ok(inventory(PROCEDURES)));
case "list_names":
return Promise.resolve(
ok(
page({
inventory({
"0x10": "_OBJC_CLASS_$_Fixture",
"0x11": "_OBJC_CLASS_$_Fixture",
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
@@ -82,7 +76,7 @@ const fixturePort = (): AnalysisOperationPort => ({
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(ok(page({ "0x30": "hello" })));
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
case "analyze_function":
return Promise.resolve(
ok({
@@ -92,29 +86,16 @@ const fixturePort = (): AnalysisOperationPort => ({
signature: null,
locals: [],
},
pseudocode: {
text: "return 0;",
total_chars: 9,
returned_chars: 9,
truncated: false,
next_offset: null,
},
assembly: {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
},
comments: emptyBounded(),
callers: emptyBounded(),
callees: emptyBounded(),
incoming_references: emptyBounded(),
outgoing_references: emptyBounded(),
referenced_strings: emptyBounded(),
referenced_names: emptyBounded(),
basic_blocks: emptyBounded(),
instruction_scan: { scanned: 0, truncated: false },
pseudocode: "return 0;",
assembly: [],
comments: [],
callers: [],
callees: [],
incoming_references: [],
outgoing_references: [],
referenced_strings: [],
referenced_names: [],
basic_blocks: [],
}),
);
default:
@@ -123,14 +104,6 @@ const fixturePort = (): AnalysisOperationPort => ({
},
});
const emptyBounded = () => ({
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
});
const resources: Array<{ close(): Promise<void> }> = [];
afterEach(async () => {
@@ -208,7 +181,7 @@ describe("enhanced MCP tools", () => {
);
});
it("accepts a final dossier page whose total exceeds returned", async () => {
it("rejects legacy paged collection wrappers", async () => {
const malformedPort = fixturePort();
const client = await connect({
execute: async (name, arguments_, options) => {
@@ -223,13 +196,7 @@ describe("enhanced MCP tools", () => {
return result;
return ok({
...dossier,
callers: {
items: [],
total: 1,
returned: 0,
truncated: false,
next_offset: null,
},
callers: { items: [], total: 1, returned: 0 },
});
},
});
@@ -237,6 +204,6 @@ describe("enhanced MCP tools", () => {
name: "analyze_function",
arguments: { procedure: "0x1" },
});
expect(result.isError).not.toBe(true);
expect(result.isError).toBe(true);
});
});
@@ -1,12 +1,7 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import {
jsonValueSchema,
type JsonValue,
} from "../../../src/domain/jsonValue.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
@@ -19,24 +14,18 @@ const PROCEDURES = {
"0x6": "prefix_TtOther",
};
const page = (values: Readonly<Record<string, string>>) => ({
items: Object.entries(values).map(([address, value]) => ({ address, value })),
offset: 0,
limit: 100,
total: Object.keys(values).length,
next_offset: null,
has_more: false,
});
const inventory = (values: Readonly<Record<string, string>>) =>
Object.entries(values).map(([address, value]) => ({ address, value }));
const fixturePort = (): AnalysisOperationPort => ({
execute: (name, arguments_) => {
switch (name) {
case "list_procedures":
return Promise.resolve(ok(page(PROCEDURES)));
return Promise.resolve(ok(inventory(PROCEDURES)));
case "list_names":
return Promise.resolve(
ok(
page({
inventory({
"0x10": "_OBJC_CLASS_$_Fixture",
"0x11": "_OBJC_CLASS_$_Fixture",
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
@@ -87,7 +76,10 @@ const fixturePort = (): AnalysisOperationPort => ({
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(ok(page({ "0x30": "hello" })));
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
case "search_strings":
case "search_procedures":
return Promise.resolve(ok(inventory({ "0x1": "needle" })));
case "analyze_function":
return Promise.resolve(
ok({
@@ -155,80 +147,17 @@ const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
return client;
};
const jsonResult = (result: CallToolResult): JsonValue => {
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;
};
describe("enhanced MCP tools", () => {
it("stops trace_feature at its explicit operation budget", async () => {
let operations = 0;
const client = await connect({
execute: () => {
operations += 1;
return Promise.resolve(
ok({
items: [{ address: "0x1", value: "needle" }],
offset: 0,
limit: 500,
total: 2,
next_offset: 1,
has_more: true,
}),
);
},
});
const result = jsonResult(
await client.callTool({
name: "trace_feature",
arguments: { query: "needle", max_operations: 1 },
}),
);
expect(operations).toBe(1);
expect(result).toMatchObject({
operations_used: 1,
operation_budget: 1,
truncated: true,
});
expect(JSON.stringify(result)).toContain("operation budget");
});
it("lets the SDK reject misspelled and out-of-range inputs", async () => {
describe("enhanced MCP input validation", () => {
it("lets the SDK reject misspelled tool inputs", async () => {
const client = await connect();
const valid = await client.callTool({
name: "trace_feature",
arguments: { query: "needle", max_operations: 1 },
arguments: { query: "needle" },
});
expect(valid.isError).not.toBe(true);
const misspelled = await client.callTool({
name: "trace_feature",
arguments: { query: "needle", max_operatons: 1 },
arguments: { query: "needle", unrecognized_option: true },
});
expect(misspelled.isError).toBe(true);
expect(misspelled.structuredContent).toBeUndefined();
@@ -241,12 +170,6 @@ describe("enhanced MCP tools", () => {
});
expect(nestedMisspelled.isError).toBe(true);
expect(nestedMisspelled.structuredContent).toBeUndefined();
const bounded = await client.callTool({
name: "trace_feature",
arguments: { query: "needle", max_operations: 101 },
});
expect(bounded.isError).toBe(true);
expect(bounded.structuredContent).toBeUndefined();
});
it("returns a typed tool error for malformed Hopper boundary values", async () => {
@@ -0,0 +1,45 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { createServer } from "../../../src/server/createServer.js";
it("returns the complete session Evidence bundle in the tool result", async () => {
const evidence = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{ operation: "observe", parameters: {}, result: { value: "seen" } },
);
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
expect(session.recordEvidence(evidence).ok).toBe(true);
const server = createServer(session, session);
const client = new Client({ name: "inline-evidence-bundle", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "get_evidence_bundle",
arguments: {},
});
expect(result.structuredContent).toMatchObject({
result: {
records: [
{
evidence_id: evidence.evidence_id,
normalized_result: { value: "seen" },
},
],
},
});
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
});
@@ -1,128 +0,0 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { createServer } from "../../../src/server/createServer.js";
const structured = (result: CallToolResult): Record<string, unknown> => {
if (result.structuredContent === undefined)
throw new Error("expected structured MCP content");
return result.structuredContent as Record<string, unknown>;
};
const createSession = () =>
createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
describe("evidence bundle release", () => {
it("notifies snapshot observers and invalidates the retained URI", async () => {
const session = createSession();
const server = createServer(session, session);
const client = new Client({ name: "release-test", version: "1" });
const bundleUpdated = new Promise<string>((resolve) => {
client.setNotificationHandler(
"notifications/resources/updated",
(notice) => {
if (notice.params.uri.startsWith("rea://evidence-bundle/"))
resolve(notice.params.uri);
},
);
});
let updates = 0;
session.onAnalysisSnapshotChanged(() => {
updates += 1;
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const snapshot = z
.object({
result: z.object({
bundle_uri: z.string(),
bundle_digest: z.string(),
}),
})
.parse(
structured(
await client.callTool({
name: "snapshot_evidence_bundle",
arguments: {},
}),
),
).result;
expect(
structured(
await client.callTool({
name: "release_evidence_bundle",
arguments: { bundle_digest: snapshot.bundle_digest },
}),
).result,
).toEqual({
bundle_digest: snapshot.bundle_digest,
released: true,
});
expect(updates).toBe(1);
await expect(bundleUpdated).resolves.toBe(snapshot.bundle_uri);
await expect(
client.readResource({ uri: snapshot.bundle_uri }),
).rejects.toThrow(/not found/iu);
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
});
it("requires evidence-write permission before releasing a bundle", async () => {
const session = createSession();
const server = createServer(session, session, {
permissionAuthority: new PermissionAuthority(createPermissionPolicy([])),
});
const client = new Client({
name: "release-permission-test",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const snapshot = z
.object({ result: z.object({ bundle_digest: z.string() }) })
.parse(
structured(
await client.callTool({
name: "snapshot_evidence_bundle",
arguments: {},
}),
),
).result;
const release = await client.callTool({
name: "release_evidence_bundle",
arguments: { bundle_digest: snapshot.bundle_digest },
});
expect(release.isError).toBe(true);
expect(
session.retainedEvidenceBundle(snapshot.bundle_digest),
).toBeDefined();
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
});
});
@@ -1,322 +0,0 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { createServer } from "../../../src/server/createServer.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { createInvestigationWorkspace } from "../../../src/domain/investigationWorkspace.js";
import { createResidualUnknown } from "../../../src/domain/residualUnknown.js";
const provider = { id: "fixture", name: "Fixture", version: "1" };
interface ResourceFixture {
readonly evidence: ReturnType<typeof createEvidence>;
readonly capture: ReturnType<typeof createEvidence>;
readonly workspace: ReturnType<typeof createInvestigationWorkspace>;
readonly unknown: ReturnType<BinarySession["recordUnknown"]>;
}
function seedResourceFixture(session: BinarySession): ResourceFixture {
const evidence = createEvidence(undefined, provider, {
operation: "resource_probe",
parameters: {},
result: { observed: true },
});
session.recordEvidence(evidence);
const capture = createEvidence(undefined, provider, {
operation: "capture_process_scenario",
parameters: {},
result: {
frames: [{ sequence: 0, at_ms: 0, data: "ready" }],
protocol_events: [],
replay_transitions: [],
},
});
session.recordEvidence(capture);
const workspace = createInvestigationWorkspace(
"resource test",
createEvidenceBundle([]),
[],
);
session.retainInvestigationWorkspace(workspace);
const unknown = session.recordUnknown({
approved: true,
question: "Was every branch observed?",
severity: "medium",
domain: "control-flow",
supporting_evidence_ids: [evidence.evidence_id],
contradicting_evidence_ids: [],
required_authority: "controlled-replay",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
});
expect(unknown.ok).toBe(true);
return { evidence, capture, workspace, unknown };
}
async function verifyResourceProtocol(
client: Client,
fixture: ResourceFixture,
): Promise<void> {
const { evidence, capture, workspace, unknown } = fixture;
const templates = await client.listResourceTemplates();
expect(templates.resourceTemplates).toContainEqual(
expect.objectContaining({ uriTemplate: "rea://evidence/{evidenceId}" }),
);
expect(
templates.resourceTemplates.map(({ uriTemplate }) => uriTemplate),
).toEqual(
expect.arrayContaining([
"rea://artifact/{manifestId}/{collection}",
"rea://function/{targetSha256}/{address}",
"rea://evidence-bundle/{bundleDigest}",
"rea://workspace/{workspaceId}/revision/{revision}",
]),
);
expect(templates.resourceTemplates).toContainEqual(
expect.objectContaining({
uriTemplate: "rea://evidence/{evidenceId}/section/{section}",
}),
);
const listed = await client.listResources();
expect(listed.resources).toContainEqual(
expect.objectContaining({ uri: "rea://snapshot/current" }),
);
expect(listed.resources).not.toContainEqual(
expect.objectContaining({
uri: `rea://evidence/${evidence.evidence_id}`,
}),
);
const read = await client.readResource({
uri: `rea://evidence/${evidence.evidence_id}`,
});
expect(read.contents).toEqual([
expect.objectContaining({
uri: `rea://evidence/${evidence.evidence_id}`,
mimeType: "application/json",
text: expect.stringContaining(evidence.evidence_id),
}),
]);
const firstSnapshot = await client.callTool({
name: "snapshot_evidence_bundle",
arguments: {},
});
const secondSnapshot = await client.callTool({
name: "snapshot_evidence_bundle",
arguments: {},
});
expect(secondSnapshot.structuredContent).toEqual(
firstSnapshot.structuredContent,
);
expect(firstSnapshot.content).toContainEqual(
expect.objectContaining({
type: "text",
text: expect.stringContaining("Copy the opaque URI exactly"),
}),
);
const bundleUri = z
.object({ result: z.object({ bundle_uri: z.string() }) })
.parse(firstSnapshot.structuredContent).result.bundle_uri;
const retainedBundle = await client.readResource({ uri: bundleUri });
expect(retainedBundle.contents[0]).toEqual(
expect.objectContaining({
uri: bundleUri,
text: expect.stringContaining(evidence.evidence_id),
}),
);
const terminal = await client.readResource({
uri: `rea://evidence/${capture.evidence_id}/section/terminal`,
});
const workspaceResource = await client.readResource({
uri: `rea://workspace/${workspace.workspace_id}/revision/${String(workspace.revision)}`,
});
expect(workspaceResource.contents[0]).toEqual(
expect.objectContaining({
text: expect.stringContaining(workspace.revision_digest),
}),
);
expect(terminal.contents[0]).toEqual(
expect.objectContaining({ text: expect.stringContaining("ready") }),
);
if (unknown.ok) {
const unknownResource = await client.readResource({
uri: `rea://unknown/${unknown.value.unknown_id}`,
});
expect(unknownResource.contents[0]).toEqual(
expect.objectContaining({
text: expect.stringContaining(unknown.value.revision_digest),
}),
);
}
await expect(
client.readResource({ uri: `rea://evidence/ev_${"0".repeat(64)}` }),
).rejects.toThrow(/not found/iu);
}
describe("evidence MCP resources", () => {
it("publishes mutable snapshot changes for every Evidence mutation", () => {
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
let updates = 0;
session.onAnalysisSnapshotChanged(() => {
updates += 1;
});
const first = createEvidence(undefined, provider, {
operation: "notification_probe",
parameters: {},
result: 1,
});
expect(session.recordEvidence(first)).toEqual({ ok: true, value: "added" });
expect(session.recordEvidence(first)).toEqual({
ok: true,
value: "duplicate",
});
const importedUnknown = createResidualUnknown(
{
approved: true,
question: "Does an imported unknown publish a snapshot update?",
severity: "low",
domain: "notifications",
supporting_evidence_ids: [first.evidence_id],
contradicting_evidence_ids: [],
required_authority: "controlled-replay",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
},
first.evidence_id,
first.subject?.digest.sha256 ?? null,
);
expect(
session.importEvidenceBundle(
createEvidenceBundle([first], [importedUnknown]),
),
).toEqual({ ok: true, value: 0 });
const imported = createEvidence(undefined, provider, {
operation: "import_notification_probe",
parameters: {},
result: 2,
});
expect(
session.importEvidenceBundle(createEvidenceBundle([imported])),
).toEqual({ ok: true, value: 1 });
expect(
session.recordUnknown({
approved: true,
question: "Does mutation publish a snapshot update?",
severity: "low",
domain: "notifications",
supporting_evidence_ids: [first.evidence_id],
contradicting_evidence_ids: [],
required_authority: "controlled-replay",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
}).ok,
).toBe(true);
expect(updates).toBe(4);
});
it("contains observer failures after committing a mutation", () => {
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
session.onAnalysisSnapshotChanged(() => {
throw new Error("fixture observer failure");
});
expect(() =>
session.recordEvidence(
createEvidence(undefined, provider, {
operation: "observer_failure_probe",
parameters: {},
result: true,
}),
),
).not.toThrow();
});
});
describe("evidence bundle resources", () => {
it("retains bundles without eviction and rejects a seventeenth digest", () => {
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const first = session.snapshotEvidenceBundle();
expect(first.ok).toBe(true);
for (let index = 0; index < 15; index += 1) {
session.recordEvidence(
createEvidence(undefined, provider, {
operation: `retention_probe_${String(index)}`,
parameters: {},
result: index,
}),
);
expect(session.snapshotEvidenceBundle().ok).toBe(true);
}
session.recordEvidence(
createEvidence(undefined, provider, {
operation: "retention_probe_overflow",
parameters: {},
result: true,
}),
);
expect(session.snapshotEvidenceBundle()).toMatchObject({
ok: false,
error: { _tag: "EvidenceLimitError", limit: "records", maximum: 16 },
});
if (first.ok) {
expect(session.retainedEvidenceBundle(first.value.bundleDigest)).toEqual(
expect.any(String),
);
expect(session.releaseEvidenceBundle(first.value.bundleDigest)).toBe(
true,
);
expect(session.releaseEvidenceBundle(first.value.bundleDigest)).toBe(
false,
);
expect(session.snapshotEvidenceBundle().ok).toBe(true);
}
});
it("lists and reads only evidence owned by the current session", async () => {
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const fixture = seedResourceFixture(session);
const server = createServer(session, session);
const client = new Client({
name: "evidence-resource-test",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
await verifyResourceProtocol(client, fixture);
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
}, 10_000);
});
@@ -33,8 +33,8 @@ describe("function comparison MCP integration", () => {
const result = await client.callTool({
name: "compare_functions",
arguments: {
left_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.left.evidence_id],
right_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.right.evidence_id],
left_evidence_id: FUNCTION_COMPARISON_EXAMPLE.left.evidence_id,
right_evidence_id: FUNCTION_COMPARISON_EXAMPLE.right.evidence_id,
unknown_registry_approved: true,
},
});
@@ -42,7 +42,6 @@ describe("function comparison MCP integration", () => {
expect(result.structuredContent).toMatchObject({
result: { status: expect.any(String) },
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
evidence_uri: expect.stringMatching(/^rea:\/\/evidence\/ev_/u),
});
const unknowns = await client.callTool({
name: "list_unknowns",
@@ -52,15 +51,13 @@ describe("function comparison MCP integration", () => {
result: {
items: [
expect.objectContaining({
unknown: expect.objectContaining({
domain: "function-comparison",
recommended_probes: [
expect.objectContaining({
rationale:
"Capture complete dossiers for both functions under the same target context and analysis limits.",
}),
],
}),
domain: "function-comparison",
recommended_probes: [
expect.objectContaining({
rationale:
"Capture complete dossiers for both functions under the same target context.",
}),
],
}),
],
},
@@ -90,8 +87,8 @@ describe("function comparison MCP integration", () => {
const result = await client.callTool({
name: "compare_functions",
arguments: {
left_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.left.evidence_id],
right_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.right.evidence_id],
left_evidence_id: FUNCTION_COMPARISON_EXAMPLE.left.evidence_id,
right_evidence_id: FUNCTION_COMPARISON_EXAMPLE.right.evidence_id,
},
});
expect(result.isError).toBe(true);
@@ -135,8 +132,8 @@ describe("function comparison MCP integration", () => {
const result = await client.callTool({
name: "compare_functions",
arguments: {
left_evidence_ids: [wrong.evidence_id],
right_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.right.evidence_id],
left_evidence_id: wrong.evidence_id,
right_evidence_id: FUNCTION_COMPARISON_EXAMPLE.right.evidence_id,
},
});
expect(result.isError).toBe(true);
+20 -31
View File
@@ -26,23 +26,17 @@ describe("Ghidra MCP evidence parity", () => {
analyzer_preset: "ghidra-default",
},
},
normalized_result: {
items: [
{
address: "0x401000",
value: "fixture_main",
procedure: {
external: false,
thunk: false,
thunk_target: null,
},
normalized_result: [
{
address: "0x401000",
value: "fixture_main",
procedure: {
external: false,
thunk: false,
thunk_target: null,
},
],
total: 1,
},
raw_result: {
items: [{ value_truncated: false }],
},
},
],
});
const mcpOverview = sessionEvidence(
@@ -50,13 +44,13 @@ describe("Ghidra MCP evidence parity", () => {
(
await mcp.callTool({
name: "binary_overview",
arguments: { detail: "detailed", limit: 5 },
arguments: {},
})
).structuredContent,
);
const directOverview = await new EnhancedTools(session).execute(
"binary_overview",
{ detail: "detailed", limit: 5 },
{},
);
expect(directOverview.ok).toBe(true);
if (!directOverview.ok) return;
@@ -97,7 +91,7 @@ describe("Ghidra MCP evidence parity", () => {
(
await mcp.callTool({
name: "analyze_function",
arguments: { procedure: "fixture_main", include_assembly: true },
arguments: { procedure: "fixture_main" },
})
).structuredContent,
);
@@ -114,17 +108,12 @@ describe("Ghidra MCP evidence parity", () => {
provenance: "ghidra-function-manager",
},
},
pseudocode: { truncated: false },
outgoing_references: {
items: [
{
kind: {
available: true,
provenance: "ghidra-reference-manager",
},
},
],
},
pseudocode: "int fixture_main(void) { return 42; }",
outgoing_references: [
{
kind: { available: true, provenance: "ghidra-reference-manager" },
},
],
limitations: expect.arrayContaining([
expect.stringContaining("indirect flows without target addresses"),
expect.stringContaining(
@@ -138,7 +127,7 @@ describe("Ghidra MCP evidence parity", () => {
});
const directAnalyzed = await new EnhancedTools(session).execute(
"analyze_function",
{ procedure: "fixture_main", include_assembly: true },
{ procedure: "fixture_main" },
);
expect(directAnalyzed.ok).toBe(true);
if (!directAnalyzed.ok) return;
+33 -63
View File
@@ -16,7 +16,6 @@ import { GHIDRA_SESSION_CAPABILITIES } from "../../../src/ghidra/GhidraSessionVa
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import {
ghidraBounded,
ghidraFunctionClassification,
ghidraFunctionDossier,
ghidraFunctionIdentity,
@@ -139,33 +138,24 @@ const resultBuilders = new Map<GhidraOperation, GhidraResultBuilder>([
["list_documents", () => ["fixture"]],
[
"list_procedures",
(_input, limit) =>
page(
[
{
address: "0x401000",
value: "fixture_main",
value_truncated: false,
procedure: {
external: false,
thunk: false,
thunk_target: null,
},
},
],
limit,
),
() => [
{
address: "0x401000",
value: "fixture_main",
procedure: {
external: false,
thunk: false,
thunk_target: null,
},
},
],
],
[
"list_strings",
(_input, limit) =>
page(
[
stringItem("0x402000", "inventory fixture"),
stringItem("0x402020", "external fixture"),
],
limit,
),
() => [
stringItem("0x402000", "inventory fixture"),
stringItem("0x402020", "external fixture"),
],
],
[
"list_segments",
@@ -189,27 +179,22 @@ const resultBuilders = new Map<GhidraOperation, GhidraResultBuilder>([
],
[
"list_names",
(_input, limit) =>
page(
[
{
address: "0x401000",
value: "fixture_main",
value_truncated: false,
symbol: {
primary: true,
dynamic: false,
external: false,
type: "function",
source: "user_defined",
},
},
],
limit,
),
() => [
{
address: "0x401000",
value: "fixture_main",
symbol: {
primary: true,
dynamic: false,
external: false,
type: "function",
source: "user_defined",
},
},
],
],
["search_procedures", (_input, limit) => page([], limit)],
["search_strings", (_input, limit) => page([], limit)],
["search_procedures", () => []],
["search_strings", () => []],
["address_name", () => "fixture_main"],
["procedure_address", () => "0x401000"],
[
@@ -240,9 +225,7 @@ const resultBuilders = new Map<GhidraOperation, GhidraResultBuilder>([
"read_function_instructions",
() => ({
procedure: ghidraFunctionIdentity(),
instructions: ghidraBounded(["0x401000: CALL 0x401020", "0x401005: RET"]),
instructions_scanned: 2,
instruction_scan_truncated: false,
instructions: ["0x401000: CALL 0x401020", "0x401005: RET"],
limitations: ["Ghidra-specific instruction text."],
}),
],
@@ -251,9 +234,7 @@ const resultBuilders = new Map<GhidraOperation, GhidraResultBuilder>([
(input, _limit) => ({
procedure: ghidraFunctionIdentity(),
direction: input.direction ?? "outgoing",
references: ghidraBounded([ghidraReferenceEdge()]),
instructions_scanned: 2,
instruction_scan_truncated: false,
references: [ghidraReferenceEdge()],
}),
],
["xrefs", () => ["0x401001"]],
@@ -271,26 +252,15 @@ const resultFor = (
operation: GhidraOperation,
input: Readonly<Record<string, JsonValue>>,
): JsonValue => {
const limit = typeof input.limit === "number" ? input.limit : 100;
const builder = resultBuilders.get(operation);
if (builder === undefined)
throw new TypeError(`Unexpected Ghidra operation: ${operation}`);
return builder(input, limit);
return builder(input, typeof input.limit === "number" ? input.limit : 100);
};
const page = (items: readonly JsonValue[], limit: number): JsonValue => ({
items: items.slice(0, limit),
offset: 0,
limit,
total: items.length,
next_offset: items.length > limit ? limit : null,
has_more: items.length > limit,
});
const stringItem = (address: string, value: string): JsonValue => ({
address,
value,
value_truncated: false,
string: {
encoding: "UTF-8",
termination: "present_or_not_required",
+12 -14
View File
@@ -63,20 +63,18 @@ describe("Ghidra MCP native API evidence", () => {
result: {
items: [
{
unknown: {
status: "open",
domain: "native-api",
question: expect.stringContaining(
"additional data sources or targets",
),
supporting_evidence_ids: [approvedInspection.evidence_id],
recommended_probes: [
{
operation: "inspect_native_api",
rationale: expect.stringContaining("ABI probe"),
},
],
},
status: "open",
domain: "native-api",
question: expect.stringContaining(
"additional data sources or targets",
),
supporting_evidence_ids: [approvedInspection.evidence_id],
recommended_probes: [
{
operation: "inspect_native_api",
rationale: expect.stringContaining("ABI probe"),
},
],
},
],
},
+1 -1
View File
@@ -27,7 +27,7 @@ describe("Ghidra MCP capability routing", () => {
const status = await mcp.callTool({
name: "binary_session",
arguments: { detail: "full" },
arguments: {},
});
expect(status.structuredContent).toMatchObject({
result: {
@@ -75,7 +75,7 @@ it("builds a zero-hop exact-address path with dossier citations", async () => {
normalized_result: {
status: "found",
shortest_hops: 0,
paths: { total: 1 },
paths: [expect.objectContaining({ hops: 0 })],
},
evidence_links: [FUNCTION_COMPARISON_EXAMPLE.left.evidence_id],
});
@@ -104,13 +104,7 @@ it("records a safe unresolved call-path question", async () => {
parameters: base.parameters,
result: jsonValueSchema.parse({
...jsonObjectSchema.parse(base.normalized_result),
callees: {
items: [{ address: "0x2000", name: "next" }],
total: 1,
returned: 1,
truncated: false,
next_offset: null,
},
callees: [{ address: "0x2000", name: "next" }],
}),
rawResult: base.raw_result,
confidence: base.confidence,
@@ -175,7 +169,7 @@ it("records an explicit non-causal static/runtime hypothesis", async () => {
}
});
it("records a safe unresolved static/runtime question", async () => {
it("uses inline assembly observations without recording a false unknown", async () => {
const { session, server, client } = await connected();
for (const evidence of [
FUNCTION_COMPARISON_EXAMPLE.left,
@@ -209,11 +203,7 @@ it("records a safe unresolved static/runtime question", async () => {
expect(response.isError).not.toBe(true);
expect(
session.listUnknowns({ domain: "static-runtime-correlation" }),
).toMatchObject([
{
question: "Does runtime behavior match the available static analysis?",
},
]);
).toEqual([]);
} finally {
await close(session, server, client);
}
@@ -107,26 +107,9 @@ it("runs and reuses a persistent cross-version workspace", async () => {
ok: true,
value: { revision: 3, runs: [{ status: "complete" }] },
});
expect(first.content).toContainEqual(
expect.objectContaining({
type: "resource_link",
uri: expect.stringMatching(
/^rea:\/\/workspace\/ws_[a-f0-9]{64}\/revision\/3$/u,
),
}),
expect(firstEvidence.normalized_result).toHaveProperty(
"investigation_run.workspace_id",
);
const retainedWorkspace = session.investigationWorkspaces()[0];
expect(retainedWorkspace).toBeDefined();
if (retainedWorkspace !== undefined) {
const resource = await client.readResource({
uri: `rea://workspace/${retainedWorkspace.workspace_id}/revision/${String(retainedWorkspace.revision)}`,
});
expect(resource.contents[0]).toEqual(
expect.objectContaining({
text: expect.stringContaining(retainedWorkspace.revision_digest),
}),
);
}
const second = await client.callTool({
name: "find_changed_behavior",
@@ -166,7 +149,7 @@ it("replays a complete workspace without write authority", async () => {
},
};
const writer = await investigationAuthority(directory, true);
const initial = await connected(filePolicy, [directory], writer);
const initial = await connected(filePolicy, writer);
try {
const created = await initial.client.callTool({
name: "find_changed_behavior",
@@ -178,7 +161,7 @@ it("replays a complete workspace without write authority", async () => {
}
const reader = await investigationAuthority(directory, false);
const replay = await connected(filePolicy, [directory], reader);
const replay = await connected(filePolicy, reader);
try {
const cached = await replay.client.callTool({
name: "find_changed_behavior",
@@ -229,7 +212,7 @@ it("defers input permission for an explicit replay with deleted inputs", async (
options: { page_size: 500, change_limit: 100 },
};
const writer = await investigationAuthority(directory, true);
const initial = await connected(filePolicy, [directory], writer);
const initial = await connected(filePolicy, writer);
let runId: string | undefined;
try {
const created = await initial.client.callTool({
@@ -256,14 +239,10 @@ it("defers input permission for an explicit replay with deleted inputs", async (
]);
const workspaceOnly = await permissionAuthorityForRoot(
directory,
[
"investigation_workspace_read",
"investigation_workspace_write",
"investigation_input",
],
["investigation_workspace_read", "investigation_workspace_write"],
["investigation_workspace_read"],
);
const replay = await connected(filePolicy, [], workspaceOnly);
const replay = await connected(filePolicy, workspaceOnly);
try {
const cached = await replay.client.callTool({
name: "find_changed_behavior",
@@ -284,49 +263,8 @@ it("defers input permission for an explicit replay with deleted inputs", async (
}
});
it("refuses automatic artifact reads outside operator-approved roots", async () => {
const directory = await createTestTempDirectory("rea-investigation-mcp-");
const approvedInputs = join(directory, "approved-inputs");
const outsideInputs = join(directory, "outside-inputs");
const evidenceRoot = join(directory, "evidence");
await Promise.all([
mkdir(approvedInputs),
mkdir(outsideInputs),
mkdir(evidenceRoot),
]);
const left = join(outsideInputs, "left");
const right = join(outsideInputs, "right");
await Promise.all([mkdir(left), mkdir(right)]);
const { session, server, client } = await connected(
evidencePolicy(evidenceRoot),
[approvedInputs],
);
try {
const response = await client.callTool({
name: "find_changed_behavior",
arguments: {
investigation_run: {
approved: true,
workspace_path: join(evidenceRoot, "workspace.json"),
left_path: left,
right_path: right,
},
},
});
expect(response.isError).toBe(true);
expect(response.content[0]).toEqual({
type: "text",
text: JSON.stringify(response.structuredContent),
});
} finally {
await close(session, server, client);
await rm(directory, { recursive: true, force: true });
}
});
const connected = async (
evidenceFilePolicy?: EvidenceFilePolicy,
investigationInputRoots: readonly string[] = evidenceFilePolicy?.roots ?? [],
permissionAuthority?: PermissionAuthority,
) => {
const session = createTestBinarySession(() => ({
@@ -335,12 +273,7 @@ const connected = async (
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
...(evidenceFilePolicy === undefined
? {}
: {
evidenceFilePolicy,
investigationInputRoots,
}),
...(evidenceFilePolicy === undefined ? {} : { evidenceFilePolicy }),
...(permissionAuthority === undefined ? {} : { permissionAuthority }),
});
const client = new Client({ name: "investigation-test", version: "1" });
@@ -374,14 +307,9 @@ const investigationAuthority = async (
): Promise<PermissionAuthority> =>
permissionAuthorityForRoot(
root,
["investigation_workspace_read", "investigation_workspace_write"],
[
"investigation_workspace_read",
"investigation_workspace_write",
"investigation_input",
],
[
"investigation_workspace_read",
"investigation_input",
...(includeWrite ? (["investigation_workspace_write"] as const) : []),
],
);
@@ -78,7 +78,7 @@ describe("JavaScript runtime observation MCP tools", () => {
expect(listed.isError).not.toBe(true);
expect(listed.structuredContent).toMatchObject({
result: {
targets: { items: [{ target_id: inspector.targetId }] },
targets: [{ target_id: inspector.targetId }],
},
});
+22 -27
View File
@@ -121,13 +121,11 @@ const verifyManagedCatalogAndNativeWorkflow = async (
MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations.map(
({ evidence_id: evidenceId }) => evidenceId,
),
limits: MANAGED_NATIVE_VERIFICATION_EXAMPLE.limits,
},
}),
);
expect(verified).toMatchObject({
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
evidence_uri: expect.stringMatching(/^rea:\/\/evidence\/ev_/u),
result: {
summary: { verified: 1 },
algorithm: { token_to_address_mapping: "not-inferred" },
@@ -163,13 +161,13 @@ const inspectManagedStaticWorkflow = async (
const inspected = structured(
await client.callTool({
name: "inspect_managed_artifact",
arguments: { path, reference_limit: 1 },
arguments: { path },
}),
);
expect(inspected).toMatchObject({
result: {
classification: { status: "managed", runtime_family: "modern-dotnet" },
references: { limit: 1 },
references: [expect.objectContaining({ name: "System.Runtime" })],
},
});
const members = sessionEvidence(
@@ -177,7 +175,7 @@ const inspectManagedStaticWorkflow = async (
structured(
await client.callTool({
name: "inspect_managed_members",
arguments: { method_limit: 1 },
arguments: {},
}),
),
);
@@ -187,22 +185,26 @@ const inspectManagedStaticWorkflow = async (
subject: { local_path: path, format: "pe" },
normalized_result: {
identity_scope: { token_identity: "build-local" },
methods: { total: 1, returned: 1 },
call_edges: { total: 1 },
field_accesses: { total: 1 },
methods: [expect.objectContaining({ token: expect.any(String) })],
call_edges: [
expect.objectContaining({ target_token: expect.any(String) }),
],
field_accesses: [
expect.objectContaining({ field_token: expect.any(String) }),
],
},
});
const boundaries = structured(
await client.callTool({
name: "inspect_managed_native_boundaries",
arguments: { import_limit: 1 },
arguments: {},
}),
);
expect(boundaries).toMatchObject({
result: {
identity_scope: { token_identity: "build-local" },
pinvoke_imports: { total: 0, limit: 1 },
native_implementations: { total: 0 },
pinvoke_imports: [],
native_implementations: [],
},
});
return members;
@@ -210,19 +212,17 @@ const inspectManagedStaticWorkflow = async (
const methodFrom = (members: Record<string, unknown>) =>
z
.object({
items: z.array(
z.object({
token: z.string(),
signature: z.object({ raw_sha256: z.string() }),
body: z.object({ normalized_il_sha256: z.string().nullable() }),
}),
),
})
.array(
z.object({
token: z.string(),
signature: z.object({ raw_sha256: z.string() }),
body: z.object({ normalized_il_sha256: z.string().nullable() }),
}),
)
.parse(
z.record(z.string(), z.unknown()).parse(members.normalized_result)
.methods,
).items[0];
)[0];
const verifyManagedComparisonAndReconstruction = async (
client: Client,
@@ -239,7 +239,7 @@ const verifyManagedComparisonAndReconstruction = async (
structured(
await client.callTool({
name: "inspect_managed_members",
arguments: { method_limit: 1 },
arguments: {},
}),
),
);
@@ -251,11 +251,6 @@ const verifyManagedComparisonAndReconstruction = async (
arguments: {
left_evidence_id: members.evidence_id,
right_evidence_id: right.evidence_id,
limits: {
max_method_matches: 100,
max_field_matches: 100,
max_candidates: 10,
},
},
}),
),
+73 -35
View File
@@ -74,18 +74,11 @@ const connect = async (analysis: AnalysisOperationPort) => {
return client;
};
const page: JsonValue = {
items: [],
offset: 0,
limit: 100,
total: 0,
next_offset: null,
has_more: false,
};
const inventory: JsonValue = [];
const outputFor = (name: string): JsonValue => {
if (["list_procedures", "list_names", "list_strings"].includes(name))
return page;
return inventory;
if (["address_name", "comment", "inline_comment"].includes(name)) return null;
if (["procedure_callees", "procedure_callers", "xrefs"].includes(name))
return [];
@@ -102,7 +95,7 @@ const outputFor = (name: string): JsonValue => {
)
return true;
if (name === "set_addresses_names") return { "0x1000": true };
if (["search_procedures", "search_strings"].includes(name)) return page;
if (["search_procedures", "search_strings"].includes(name)) return inventory;
if (name === "procedure_info")
return {
name: "main",
@@ -121,15 +114,7 @@ const outputFor = (name: string): JsonValue => {
if (name === "read_function_instructions")
return {
procedure: { address: "0x1000", name: "main" },
instructions: {
items: ["0x1000: ret"],
total: 1,
returned: 1,
truncated: false,
next_offset: null,
},
instructions_scanned: 1,
instruction_scan_truncated: false,
instructions: ["0x1000: ret"],
limitations: ["Provider-specific instruction text."],
};
if (name === "read_bytes")
@@ -146,15 +131,7 @@ const outputFor = (name: string): JsonValue => {
return {
procedure: { address: "0x1000", name: "main" },
direction: "outgoing",
references: {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
},
instructions_scanned: 1,
instruction_scan_truncated: false,
references: [],
};
return name.includes("address") ? "0x1000" : "fixture";
};
@@ -191,11 +168,6 @@ describe("official Hopper proxy tools", () => {
arguments: VALID_INPUTS[contract.name],
});
expect(result.isError).not.toBe(true);
expect(result.content).not.toEqual(
expect.arrayContaining([
expect.objectContaining({ type: "resource_link" }),
]),
);
}
expect(invocations.map(({ name }) => name)).toEqual(
@@ -213,8 +185,6 @@ describe("official Hopper proxy tools", () => {
pattern: "main",
mode: "literal",
case_sensitive: false,
offset: 0,
limit: 100,
document: null,
});
});
@@ -233,4 +203,72 @@ describe("official Hopper proxy tools", () => {
text: JSON.stringify(result.structuredContent),
});
});
it("returns every procedure inline without caller-authored page calls", async () => {
const invocations: Invocation[] = [];
const client = await connect({
execute: (name, arguments_) => {
invocations.push({ name, arguments_ });
return Promise.resolve(
ok([
{ address: "0x1", value: "procedure" },
{ address: "0x2", value: "procedure" },
]),
);
},
});
const result = await client.callTool({
name: "list_procedures",
arguments: {},
});
expect(result.structuredContent).toMatchObject({
result: [
{ address: "0x1", value: "procedure" },
{ address: "0x2", value: "procedure" },
],
});
expect(invocations).toHaveLength(1);
expect(invocations[0]?.arguments_).toEqual({ document: null });
expect(
(await client.listTools()).tools.find(
({ name }) => name === "list_procedures",
)?.inputSchema,
).not.toHaveProperty("properties.offset");
});
it("returns every search match inline in one provider call", async () => {
const invocations: Invocation[] = [];
const client = await connect({
execute: (name, arguments_) => {
invocations.push({ name, arguments_ });
return Promise.resolve(
ok([
{ address: "0x1", value: "coffee" },
{ address: "0x2", value: "coffee" },
]),
);
},
});
const result = await client.callTool({
name: "search_strings",
arguments: { pattern: "coffee" },
});
expect(result.structuredContent).toMatchObject({
result: [
{ address: "0x1", value: "coffee" },
{ address: "0x2", value: "coffee" },
],
});
expect(invocations).toHaveLength(1);
expect(invocations[0]?.arguments_).toMatchObject({ pattern: "coffee" });
expect(
(await client.listTools()).tools.find(
({ name }) => name === "search_strings",
)?.inputSchema,
).not.toHaveProperty("properties.offset");
});
});
@@ -70,21 +70,15 @@ describe("process-capture MCP elicitation handshake", () => {
});
try {
await client.connect(clientTransport);
const identity = await client.readResource({
uri: "rea://server/identity",
});
const identityContent = identity.contents[0];
if (identityContent === undefined || !("text" in identityContent))
throw new Error("missing modern server identity resource");
expect(JSON.parse(identityContent.text)).toMatchObject({
client: { name: "process-elicit", version: "1" },
});
const status = await client.callTool({
name: "binary_session",
arguments: { detail: "full" },
arguments: {},
});
expect(status.structuredContent).toMatchObject({
result: {
server_identity: {
client: { name: "process-elicit", version: "1" },
},
client_features: {
elicitation_form: true,
elicitation_url: false,
@@ -82,7 +82,7 @@ const traceSpecification: ProcessTraceSpecification = {
const captureEvidence = (side: "left" | "right") =>
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture/v4",
predicateType: "rea.process-capture",
operation: "capture_process_scenario",
parameters: { side },
result: jsonValueSchema.parse(capture),
+20 -91
View File
@@ -21,7 +21,7 @@ afterEach(async () => {
});
describe("guided prompt completion from live analysis", () => {
it("reads live documents and paged procedures without ambiguous names", async () => {
it("reads live documents and complete procedures without ambiguous names", async () => {
const requests: Array<Readonly<Record<string, unknown>>> = [];
const session = createTestBinarySession(() => client(requests));
directory = await createTestTempDirectory("rea-prompt-completion-");
@@ -39,10 +39,7 @@ describe("guided prompt completion from live analysis", () => {
arguments: { document: "App" },
}),
).toEqual(["0x1000", "0x2000", "0x3000", "0x4000", "tail", "unique"]);
expect(requests).toEqual([
{ offset: 0, limit: 500, document: "App" },
{ offset: 2, limit: 500, document: "App" },
]);
expect(requests).toEqual([{ document: "App" }]);
expect(await completion.complete("provider", "uni")).toEqual([
"unidentified",
]);
@@ -62,7 +59,7 @@ describe("guided prompt completion from investigation records", () => {
const invalidCapture = createEvidence(undefined, fixtureProvider, {
operation: "capture_process_scenario",
parameters: {},
result: { schema_version: 4 },
result: {},
confidence: "observed",
authority: "controlled-replay",
environment: fixtureEnvironment,
@@ -156,65 +153,24 @@ describe("guided prompt completion from investigation records", () => {
});
});
describe("guided prompt completion validation and limits", () => {
it("does not offer procedure names from an incomplete discovery", async () => {
let calls = 0;
const completion = createPromptCompletionSource({
execute() {
calls += 1;
return Promise.resolve(
observed(
calls === 1
? page(0, [{ address: "0x1000", value: "possibly_ambiguous" }], 1)
: null,
),
);
},
});
expect(await completion.complete("procedure", "")).toEqual(["0x1000"]);
});
it("bounds procedure scans and rejects non-advancing continuation metadata", async () => {
describe("guided prompt completion from complete inventories", () => {
it("reads every procedure in one provider call", async () => {
let calls = 0;
const procedures = Array.from({ length: 6_000 }, (_, address) => ({
address: `0x${address.toString(16).padStart(8, "0")}`,
value: `procedure_${String(address)}`,
}));
const bounded = createPromptCompletionSource({
execute(_operation, parameters) {
calls += 1;
const offset = Number(parameters.offset);
const items = Array.from({ length: 500 }, (_, index) => {
const address = offset + index;
return {
address: `0x${address.toString(16).padStart(8, "0")}`,
value: `procedure_${String(address)}`,
};
});
return Promise.resolve(
observed({
items,
offset,
limit: 500,
total: 6_000,
next_offset: offset + 500,
has_more: true,
}),
);
expect(parameters).toEqual({});
return Promise.resolve(observed(procedures));
},
});
const values = await bounded.complete("procedure", "");
expect(calls).toBe(10);
expect(values).toHaveLength(5_000);
expect(values.every((value) => value.startsWith("0x"))).toBe(true);
let nonAdvancingCalls = 0;
const nonAdvancing = createPromptCompletionSource({
execute() {
nonAdvancingCalls += 1;
return Promise.resolve(
observed(page(0, [{ address: "0x5000", value: "unsafe_name" }], 0)),
);
},
});
expect(await nonAdvancing.complete("procedure", "")).toEqual(["0x5000"]);
expect(nonAdvancingCalls).toBe(1);
expect(calls).toBe(1);
expect(values).toHaveLength(12_000);
expect(values).toContain("0x00000000");
});
it("normalizes Unicode prefixes while preserving distinct exact identifiers", async () => {
@@ -258,43 +214,16 @@ const client = (
return Promise.resolve(observed(["AppTests", "App", "App"]));
if (operation === "list_procedures") {
requests.push(parameters);
const offset = parameters.offset;
return Promise.resolve(
observed(
offset === 0
? page(
0,
[
{ address: "0x1000", value: "duplicate" },
{ address: "0x2000", value: "unique" },
],
2,
)
: page(
2,
[
{ address: "0x3000", value: "duplicate" },
{ address: "0x4000", value: "tail" },
],
null,
),
),
observed([
{ address: "0x1000", value: "duplicate" },
{ address: "0x2000", value: "unique" },
{ address: "0x3000", value: "duplicate" },
{ address: "0x4000", value: "tail" },
]),
);
}
return Promise.resolve(observed(null));
},
close: () => Promise.resolve(),
});
const page = (
offset: number,
items: readonly { readonly address: string; readonly value: string }[],
nextOffset: number | null,
) => ({
items,
offset,
limit: 500,
total: 4,
next_offset: nextOffset,
has_more: nextOffset !== null,
});
+6 -13
View File
@@ -376,19 +376,12 @@ const lifecycleClient = (
if (operation === "list_procedures") {
requests.push(parameters);
return Promise.resolve(
observed({
items: [
{
address: target === "first" ? "0x1000" : "0x2000",
value: `${target}-procedure`,
},
],
offset: 0,
limit: 500,
total: 1,
next_offset: null,
has_more: false,
}),
observed([
{
address: target === "first" ? "0x1000" : "0x2000",
value: `${target}-procedure`,
},
]),
);
}
return Promise.resolve(observed(null));
@@ -57,7 +57,7 @@ describe("provider selection over MCP", () => {
const before = structured(
await mcp.callTool({
name: "binary_session",
arguments: { detail: "full" },
arguments: {},
}),
);
expect(before.result).toMatchObject({
@@ -124,7 +124,7 @@ describe("provider selection over MCP", () => {
const status = structured(
await mcp.callTool({
name: "binary_session",
arguments: { detail: "full" },
arguments: {},
}),
);
expect(status.result).toMatchObject({
@@ -157,7 +157,7 @@ describe("provider selection over MCP", () => {
structured(
await mcp.callTool({
name: "binary_session",
arguments: { detail: "full" },
arguments: {},
}),
).result,
).toMatchObject({
@@ -192,7 +192,6 @@ const candidate = (id: string, starts: string[]): AnalysisProviderCandidate => {
ok({
profile: createAnalysisProfile(
{ id, name: identity.name, version: "1" },
1,
{ fixture: id },
),
compatibility: {},
@@ -219,8 +218,6 @@ const candidate = (id: string, starts: string[]): AnalysisProviderCandidate => {
const capability = (provider: ProviderIdentity): CapabilityDescriptor => ({
provider,
operation: "address_name",
inputContractVersion: 1,
outputContractVersion: 1,
available: true,
reason: null,
pagination: "none",
@@ -65,16 +65,10 @@ describe("reconstruction coverage MCP parity", () => {
revision: 1,
revision_sha256: workspace.revision_sha256,
});
const resourceUri = `rea://reconstruction-coverage/${workspace.workspace_id}/revision/1`;
expect(committed.content).toContainEqual(
expect.objectContaining({ type: "resource_link", uri: resourceUri }),
);
const resource = await client.readResource({ uri: resourceUri });
expect(resource.contents[0]).toEqual(
expect.objectContaining({
text: expect.stringContaining(workspace.revision_sha256),
}),
);
expect(committed.structuredContent).toMatchObject({
workspace_id: workspace.workspace_id,
revision_sha256: workspace.revision_sha256,
});
const queried = await client.callTool({
name: "query_reconstruction_coverage",
arguments: {
@@ -7,7 +7,7 @@ import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
describe("reconstruction obligation ledger MCP parity", () => {
it("builds an Evidence-backed page and exposes the retained resource", async () => {
it("returns an Evidence-backed page inline", async () => {
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
@@ -25,44 +25,24 @@ describe("reconstruction obligation ledger MCP parity", () => {
evidence_bundle: createEvidenceBundle([]),
reviewed_obligations: [],
manifest: {
schema_version: 1,
bindings: [],
contradictions: [],
},
limits: { max_obligations: 100 },
page: { offset: 0, limit: 50 },
},
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
evidence_uri: expect.stringMatching(
/^rea:\/\/evidence\/ev_[a-f0-9]{64}$/u,
),
result: {
schema: "ReconstructionObligationLedger",
status: "unknown",
summary: { total: 0 },
},
});
const evidence = result.structuredContent;
if (
evidence === undefined ||
evidence === null ||
typeof evidence !== "object" ||
!("evidence_id" in evidence) ||
typeof evidence.evidence_id !== "string"
)
throw new TypeError("Missing obligation ledger Evidence ID");
const resource = await client.readResource({
uri: `rea://evidence/${evidence.evidence_id}/reconstruction-obligation-ledger`,
});
expect(resource.contents[0]).toEqual(
expect.objectContaining({
text: expect.stringContaining(
'"schema": "ReconstructionObligationLedger"',
),
}),
expect(result.structuredContent).toHaveProperty(
"result.schema",
"ReconstructionObligationLedger",
);
} finally {
await client.close();
@@ -7,7 +7,7 @@ import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
describe("reconstruction readiness MCP parity", () => {
it("returns a passing compact result and retains the full report resource", async () => {
it("returns the complete passing report inline", async () => {
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
@@ -30,31 +30,13 @@ describe("reconstruction readiness MCP parity", () => {
schema: "ReconstructionReadinessReport",
status: "pass",
summary: { passed_required_stages: 9 },
report_resource_uri: expect.stringMatching(
/^rea:\/\/evidence\/ev_[a-f0-9]{64}\/reconstruction-readiness-report$/u,
),
stages: expect.arrayContaining([expect.any(Object)]),
},
});
expect(result.structuredContent).not.toHaveProperty("result.snapshot");
expect(result.structuredContent).not.toHaveProperty("result.stages");
const content = result.structuredContent;
if (
content === undefined ||
content === null ||
typeof content !== "object" ||
!("evidence_id" in content) ||
typeof content.evidence_id !== "string"
)
throw new TypeError("Missing readiness Evidence ID");
const resource = await client.readResource({
uri: `rea://evidence/${content.evidence_id}/reconstruction-readiness-report`,
});
expect(resource.contents[0]).toEqual(
expect.objectContaining({
text: expect.stringContaining(
'"schema": "ReconstructionReadinessReport"',
),
}),
expect(result.structuredContent).toHaveProperty("result.snapshot");
expect(result.structuredContent).toHaveProperty("result.stages");
expect(result.structuredContent).not.toHaveProperty(
"result.report_resource_uri",
);
} finally {
await client.close();
@@ -27,7 +27,6 @@ describe("direct replay machine MCP parity", () => {
expect(result).toMatchObject({
structuredContent: {
result: {
schema_version: 1,
final_state: "complete",
terminal: true,
decisions: [{ outcome: "matched", transition_sequence: 0 }],
+20 -99
View File
@@ -11,7 +11,6 @@ import {
import { PACKAGE_METADATA } from "../../../src/generatedPackageMetadata.js";
import { PRODUCT_IDENTITY, SDK_IDENTITY } from "../../../src/identity.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { TOOL_KINDS } from "../../../src/contracts/toolContractTypes.js";
import { createServer } from "../../../src/server/createServer.js";
import { createServerIdentity } from "../../../src/serverIdentity.js";
import { observed } from "../../fixtures/analysisExecution.js";
@@ -26,8 +25,6 @@ const availabilityProvider = (): AnalysisProvider => {
const capability: CapabilityDescriptor = {
provider: identity,
operation: "current_address",
inputContractVersion: 1,
outputContractVersion: 1,
available: true,
reason: null,
pagination: "none",
@@ -118,8 +115,6 @@ describe("server and catalog identity", () => {
cli_commands: 68,
mcp_tools: TOOL_CONTRACTS.length,
mcp_prompts: 6,
mcp_resources: 2,
mcp_resource_templates: 11,
});
expect(CATALOG_IDENTITY.digests.combined_sha256).toMatch(/^[a-f0-9]{64}$/u);
});
@@ -238,7 +233,6 @@ describe("live server identity over MCP", () => {
await client.connect(clientTransport);
await assertLiveIdentity(client);
await assertSessionIdentity(client);
await assertCapabilityViews(client);
expect(
(await client.listTools()).tools.map(({ name }) => name),
).toContain("current_address");
@@ -269,29 +263,30 @@ const assertLiveIdentity = async (client: Client): Promise<void> => {
expect(instructions).toContain(
"native binary/database -> open_binary, then binary_overview",
);
expect(instructions).toContain("Never repeat identical analysis");
expect(instructions).toContain("cite Evidence IDs");
const resource = await client.readResource({ uri: "rea://server/identity" });
const content = resource.contents[0];
expect(content).toBeDefined();
if (content === undefined || !("text" in content))
throw new Error("missing identity resource text");
expect(JSON.parse(content.text)).toMatchObject({
package: { version: PRODUCT_IDENTITY.packageVersion },
server: { version: PRODUCT_IDENTITY.packageVersion },
sdk: {
server: SDK_IDENTITY.server,
client_test: PACKAGE_METADATA.clientSdkVersion,
const identity = await client.callTool({
name: "binary_session",
arguments: {},
});
expect(identity.structuredContent).toMatchObject({
result: {
server_identity: {
package: { version: PRODUCT_IDENTITY.packageVersion },
server: { version: PRODUCT_IDENTITY.packageVersion },
sdk: {
server: SDK_IDENTITY.server,
client_test: PACKAGE_METADATA.clientSdkVersion,
},
client: null,
alignment: { state: "unknown" },
},
},
client: null,
alignment: { state: "unknown" },
});
};
const assertSessionIdentity = async (client: Client): Promise<void> => {
const status = await client.callTool({
name: "binary_session",
arguments: { detail: "full", expected_package_version: "1.2.0" },
arguments: { expected_package_version: "1.2.0" },
});
expect(status.structuredContent).toMatchObject({
result: {
@@ -328,11 +323,9 @@ const assertSessionIdentity = async (client: Client): Promise<void> => {
}),
expect.objectContaining({
name: "analyze_javascript_application",
available: false,
reason: "policy_disabled",
remediation: expect.stringContaining(
"REA_INVESTIGATION_INPUT_ROOTS_JSON",
),
available: true,
reason: "available",
remediation: null,
}),
]),
client_features: {
@@ -343,76 +336,4 @@ const assertSessionIdentity = async (client: Client): Promise<void> => {
},
},
});
const summary = await client.callTool({
name: "binary_session",
arguments: { expected_package_version: "1.2.0" },
});
expect(summary.structuredContent).toMatchObject({
result: {
view: "summary",
open: false,
target: null,
alignment: { state: "mcp_server_restart_required" },
recommended_actions: expect.arrayContaining([
"For a supplied target, route by format: ASAR/JavaScript to analyze_javascript_application; archive/package to open_binary(path), then inspect_artifact or inventory_artifact on the active target; managed PE/CLI to inspect_managed_artifact; browser/Electron runtimes to their list-target tools; native binaries to open_binary.",
]),
},
});
expect(JSON.stringify(summary.structuredContent)).not.toContain(
"tool_availability",
);
};
const assertCapabilityViews = async (client: Client): Promise<void> => {
const capabilities = await client.callTool({
name: "binary_session",
arguments: {
detail: "capabilities",
capability_family: "browser-provider",
cursor: 0,
limit: 1,
},
});
expect(capabilities.structuredContent).toMatchObject({
result: {
view: "capabilities",
capability_family: "browser-provider",
capabilities: {
items: [expect.objectContaining({ surface: "browser-provider" })],
cursor: 0,
limit: 1,
total: expect.any(Number),
next_cursor: expect.any(Number),
has_more: true,
},
client_features: {
elicitation_form: false,
elicitation_url: false,
roots: false,
sampling: false,
},
},
});
for (const capabilityFamily of TOOL_KINDS) {
const familyCapabilities = await client.callTool({
name: "binary_session",
arguments: {
detail: "capabilities",
capability_family: capabilityFamily,
limit: 100,
},
});
expect(familyCapabilities.structuredContent).toMatchObject({
result: {
view: "capabilities",
capability_family: capabilityFamily,
capabilities: {
items: expect.arrayContaining([
expect.objectContaining({ surface: capabilityFamily }),
]),
total: expect.any(Number),
},
},
});
}
};
+1 -12
View File
@@ -116,18 +116,7 @@ it("handles concurrent tool calls without corruption", async () => {
execute: (name) => {
invocations.push(name);
return Promise.resolve(
ok(
["list_procedures", "list_strings"].includes(name)
? {
items: [],
offset: 0,
limit: 100,
total: 0,
next_offset: null,
has_more: false,
}
: [],
),
ok(["list_procedures", "list_strings"].includes(name) ? [] : []),
);
},
});
+14 -83
View File
@@ -35,8 +35,6 @@ const providerWithCapabilities = (
(operation) => ({
provider: identity,
operation,
inputContractVersion: 1,
outputContractVersion: 1,
available: true,
reason: null,
pagination: "none",
@@ -77,69 +75,6 @@ const structured = (result: CallToolResult): Record<string, unknown> => {
return Object.fromEntries(Object.entries(result.structuredContent));
};
it("records approved trace truncation as a deduplicated residual unknown", async () => {
const analysis: AnalysisOperationPort = {
execute: () =>
Promise.resolve(
ok({
items: [],
offset: 0,
limit: 500,
total: 0,
next_offset: null,
has_more: false,
}),
),
};
const session = createTestBinarySession(
providerWithCapabilities([
"list_strings",
"list_procedures",
"xrefs",
"resolve_containing_procedure",
]),
);
const server = createServer(analysis, session);
const client = new Client({ name: "unknown-workflow", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
await client.callTool({
name: "open_binary",
arguments: { path: process.execPath },
});
for (let attempt = 0; attempt < 2; attempt += 1) {
const traced = await client.callTool({
name: "trace_feature",
arguments: {
query: "license",
max_operations: 1,
unknown_registry_approved: true,
},
});
expect(traced.isError).not.toBe(true);
}
const listed = structured(
await client.callTool({ name: "list_unknowns", arguments: {} }),
);
expect(listed).toMatchObject({
result: {
items: [
{
unknown: {
status: "open",
domain: "control-flow",
question: "Investigation reached the operation budget.",
},
},
],
},
});
}, 10_000);
it("records approved typed capability unavailability without forwarding the flag", async () => {
const received: Array<Readonly<Record<string, unknown>>> = [];
const analysis: AnalysisOperationPort = {
@@ -191,17 +126,15 @@ it("records approved typed capability unavailability without forwarding the flag
result: {
items: [
{
unknown: {
domain: "analysis-capability",
question:
"The requested analysis is unavailable for the current target.",
recommended_probes: [
{
rationale:
"Choose another analysis or target that can answer this question.",
},
],
},
domain: "analysis-capability",
question:
"The requested analysis is unavailable for the current target.",
recommended_probes: [
{
rationale:
"Choose another analysis or target that can answer this question.",
},
],
},
],
},
@@ -243,7 +176,7 @@ it("records approved capture disagreement as a contradicted unknown", async () =
});
const captureEvidence = (capture: typeof left) =>
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture/v4",
predicateType: "rea.process-capture",
operation: "capture_process_scenario",
parameters: {},
result: jsonValueSchema.parse(capture),
@@ -291,12 +224,10 @@ it("records approved capture disagreement as a contradicted unknown", async () =
result: {
items: [
{
unknown: {
status: "contradicted",
domain: "process-comparison",
question: "Process captures disagree across: interaction, shim",
contradicting_evidence_ids: [rightEvidence.evidence_id],
},
status: "contradicted",
domain: "process-comparison",
question: "Process captures disagree across: interaction, shim",
contradicting_evidence_ids: [rightEvidence.evidence_id],
},
],
},
+9 -20
View File
@@ -49,17 +49,10 @@ it("executes a realistic workflow: list methods, decompile selected, get xrefs",
switch (name) {
case "list_procedures":
return Promise.resolve(
ok({
items: [
{ address: "0x1000", value: "main" },
{ address: "0x2000", value: "helper" },
],
offset: 0,
limit: 100,
total: 2,
next_offset: null,
has_more: false,
}),
ok([
{ address: "0x1000", value: "main" },
{ address: "0x2000", value: "helper" },
]),
);
case "procedure_pseudo_code":
return Promise.resolve(
@@ -79,14 +72,10 @@ it("executes a realistic workflow: list methods, decompile selected, get xrefs",
});
expect(listResult.isError).not.toBe(true);
expect(structured(listResult)).toMatchObject({
result: {
items: [
{ address: "0x1000", value: "main" },
{ address: "0x2000", value: "helper" },
],
total: 2,
has_more: false,
},
result: [
{ address: "0x1000", value: "main" },
{ address: "0x2000", value: "helper" },
],
});
const decompileResult = await client.callTool({
@@ -138,7 +127,7 @@ it("advertises the complete currently available inventory with a session", async
const status = structured(
await client.callTool({
name: "binary_session",
arguments: { detail: "full" },
arguments: {},
}),
);
const available = new Set(
+15 -18
View File
@@ -27,7 +27,6 @@ import {
const SNAPSHOT_PROFILE = createAnalysisProfile(
{ id: "fixture", name: "Fixture analysis provider", version: "1" },
1,
{ fixture: true },
);
@@ -93,7 +92,7 @@ describe("target-free MCP lifecycle", () => {
structured(
await mcp.callTool({
name: "binary_session",
arguments: { detail: "full" },
arguments: {},
}),
),
).result,
@@ -117,7 +116,7 @@ describe("target-free MCP workflow", () => {
const beforeTools = (await mcp.listTools()).tools;
const beforeNames = beforeTools.map(({ name }) => name);
expect(mcp.getInstructions()).toContain(
"archive/package -> open_binary(path), then inspect_artifact/inventory_artifact (active target)",
"archive/package -> open_binary(path), then inspect_artifact/inventory_artifact",
);
expect(
beforeTools.find(({ name }) => name === "inventory_artifact")
@@ -137,15 +136,17 @@ describe("target-free MCP workflow", () => {
structured(
await mcp.callTool({
name: "binary_session",
arguments: { detail: "full" },
arguments: {},
}),
),
).toMatchObject({ result: { path: await realpath(first) } });
expect(
text(await mcp.callTool({ name: "current_document", arguments: {} })),
).toContain("first.hop");
const { recordedUnknown, changesBeforeMutation } =
await snapshotAndRecordUnknown(lifecycle, directory);
const { recordedUnknown } = await snapshotAndRecordUnknown(
lifecycle,
directory,
);
const resolved = await mcp.callTool({
name: "update_unknown",
arguments: {
@@ -170,8 +171,6 @@ describe("target-free MCP workflow", () => {
});
expect(resolved.isError).not.toBe(true);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(lifecycle.unknownResourceUpdates()).toBe(1);
expect(lifecycle.resourceListChanges()).toBe(changesBeforeMutation);
expect(
structured(
await mcp.callTool({
@@ -267,21 +266,19 @@ describe("process residuals over MCP", () => {
result: z.object({
items: z.array(
z.object({
unknown: z.object({
question: z.string(),
domain: z.string(),
}),
question: z.string(),
domain: z.string(),
}),
),
}),
})
.parse(structured(listedUnknowns)).result.items;
expect(listed).toContainEqual({
unknown: expect.objectContaining({
expect(listed).toContainEqual(
expect.objectContaining({
question: "Was network behavior fully observed during capture?",
domain: "process-network",
}),
});
);
});
});
@@ -301,8 +298,6 @@ const provider = (closed: string[]): AnalysisProvider => {
const capability: CapabilityDescriptor = {
provider: identity,
operation: "current_document",
inputContractVersion: 1,
outputContractVersion: 1,
available: true,
reason: null,
pagination: "none",
@@ -341,6 +336,8 @@ const structured = (result: CallToolResult): Record<string, unknown> => {
typeof result.structuredContent !== "object" ||
result.structuredContent === null
)
throw new Error("missing structured result");
throw new Error(
`missing structured result: ${JSON.stringify(result.content)}`,
);
return z.record(z.string(), z.unknown()).parse(result.structuredContent);
};
+14 -39
View File
@@ -1,4 +1,4 @@
import { writeFile } from "node:fs/promises";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
@@ -20,7 +20,6 @@ import type { AnalysisProvider } from "../../../src/application/AnalysisProvider
const SNAPSHOT_PROFILE = createAnalysisProfile(
{ id: "fixture", name: "Fixture analysis provider", version: "1" },
1,
{ fixture: true },
);
@@ -29,8 +28,6 @@ export interface SessionMcpHarness {
readonly first: string;
readonly second: string;
readonly closed: string[];
readonly resourceListChanges: () => number;
readonly unknownResourceUpdates: () => number;
}
export const createSessionMcpHarness = async (
@@ -59,14 +56,6 @@ export const createSessionMcpHarness = async (
analysisSnapshotFilePolicy: filePolicy,
});
const mcp = new Client({ name: "session-test", version: "1.0.0" });
let resourceChanges = 0;
let unknownUpdates = 0;
mcp.setNotificationHandler("notifications/resources/list_changed", () => {
resourceChanges += 1;
});
mcp.setNotificationHandler("notifications/resources/updated", (notice) => {
if (notice.params.uri.startsWith("rea://unknown/")) unknownUpdates += 1;
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(mcp, server);
@@ -77,8 +66,6 @@ export const createSessionMcpHarness = async (
first,
second,
closed,
resourceListChanges: () => resourceChanges,
unknownResourceUpdates: () => unknownUpdates,
};
};
@@ -87,34 +74,27 @@ export const snapshotAndRecordUnknown = async (
root: string,
): Promise<{
recordedUnknown: { unknown_id: string; revision: number };
changesBeforeMutation: number;
}> => {
const { mcp } = harness;
const snapshotted = await mcp.callTool({
name: "snapshot_evidence_bundle",
name: "get_evidence_bundle",
arguments: {},
});
const snapshotResult = z
.object({ result: z.object({ bundle_uri: z.string() }) })
.parse(structured(snapshotted)).result;
const bundleResource = await mcp.readResource({
uri: snapshotResult.bundle_uri,
expect(structured(snapshotted).result).toMatchObject({
records: expect.any(Array),
unknowns: expect.any(Array),
});
const evidencePath = join(root, "evidence.json");
structured(
await mcp.callTool({
name: "export_evidence_bundle",
arguments: { path: evidencePath },
}),
);
const bundle = evidenceBundleSchema.parse(
JSON.parse(
z.object({ text: z.string() }).parse(bundleResource.contents[0]).text,
),
JSON.parse(await readFile(evidencePath, "utf8")),
);
expect(bundle.records).toHaveLength(1);
const evidencePath = join(root, "evidence.json");
expect(
structured(
await mcp.callTool({
name: "export_evidence_bundle",
arguments: { path: evidencePath },
}),
).result,
).toMatchObject({ path: evidencePath, records: 1 });
expect(
structured(
await mcp.callTool({
@@ -144,9 +124,6 @@ export const snapshotAndRecordUnknown = async (
}),
).result,
).toEqual({ imported: 1, unknowns_added: 0, total: 2 });
await new Promise<void>((resolve) => setImmediate(resolve));
expect(harness.resourceListChanges()).toBe(0);
const changesBeforeMutation = harness.resourceListChanges();
const recordedUnknown = z
.object({
result: z.object({ unknown_id: z.string(), revision: z.number() }),
@@ -170,8 +147,6 @@ export const snapshotAndRecordUnknown = async (
),
).result;
expect(recordedUnknown.revision).toBe(1);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(harness.resourceListChanges()).toBe(changesBeforeMutation);
const listedUnknowns = await mcp.callTool({
name: "list_unknowns",
arguments: {},
@@ -182,7 +157,7 @@ export const snapshotAndRecordUnknown = async (
.object({ result: z.object({ items: z.array(z.unknown()) }) })
.parse(structured(listedUnknowns)).result.items,
).toHaveLength(1);
return { recordedUnknown, changesBeforeMutation };
return { recordedUnknown };
};
const structured = (result: CallToolResult): Record<string, unknown> => {
@@ -58,16 +58,8 @@ describe("tool registration options", () => {
const analyzeFunction = advertised.find(
({ name }) => name === "analyze_function",
);
expect(analyzeFunction?.inputSchema.properties).toMatchObject({
include_assembly: {
description: "Whether to include assembly in the result.",
},
max_instructions: {
description: "Maximum permitted instructions for this operation.",
},
pseudocode_offset: {
description: "Zero-based index of the first pseudocode to return.",
},
expect(analyzeFunction?.inputSchema.properties).toEqual({
procedure: expect.objectContaining({ type: "string" }),
});
expect(advertised).toEqual(
GENERATED_MCP_TOOL_CATALOG.map((tool) => ({
+24 -20
View File
@@ -42,7 +42,7 @@ describe("tool result projection", () => {
error: {
code: "provider_unavailable",
details: { failure_code: "unsupported_demo_dialog" },
category: "execution_failure",
category: "unavailable",
},
});
expect(JSON.stringify(result)).not.toContain("expected Hopper");
@@ -87,7 +87,7 @@ describe("tool result projection", () => {
});
expect(JSON.stringify(result)).not.toContain("cookie");
});
it("links successful evidence only when its session resource exists", () => {
it("returns result and complete Evidence context in one call", () => {
const evidence = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
@@ -95,7 +95,6 @@ describe("tool result projection", () => {
operation: "fixture",
parameters: {},
result: { value: "observed" },
limitations: [],
},
);
const evidenceContract: ToolContract = {
@@ -103,22 +102,27 @@ describe("tool result projection", () => {
outputSchema: evidenceResultOf(z.object({ value: z.string() })),
};
expect(
toCallToolResult(ok(evidence), evidenceContract).content,
).not.toEqual(
expect.arrayContaining([
expect.objectContaining({ type: "resource_link" }),
]),
);
expect(
toCallToolResult(ok(evidence), evidenceContract, {
evidenceResourcesAvailable: true,
}).content,
).toContainEqual(
expect.objectContaining({
type: "resource_link",
uri: `rea://evidence/${evidence.evidence_id}`,
}),
);
const result = toCallToolResult(ok(evidence), evidenceContract);
expect(result.structuredContent).toMatchObject({
result: { value: "observed" },
evidence_id: evidence.evidence_id,
evidence: {
provider: { id: "fixture", name: "Fixture", version: "1" },
operation: "fixture",
predicate_type: "rea.analysis/v2",
parameters: {},
raw_result: null,
confidence: "observed",
authority: "shipped-artifact",
environment: null,
limitations: evidence.limitations,
locations: [],
evidence_links: [],
},
});
expect(result.content[0]).toMatchObject({
type: "text",
text: expect.stringContaining('"value":"observed"'),
});
});
});