fix(ida): reconcile native bridge with main and verify function switching

Merge the PR 1544 native IDA bridge onto current main and validate two-function pseudocode identity with a unique second-body marker. Preserve current input-error and GUI-effect semantics, identify the adapter without implying an IDA edition, and document the upstream listener and navigation limits.

Verified on Windows IDA Pro 9.3 through the attached legacy MCP workflow: production CLI/MCP analysis, distinct-function pseudocode, return to the original function, target identity, and cleanup. Native Windows plugin and IDA Free runtime workflows were not verified in this follow-up. No private target paths or license details are included.
This commit is contained in:
N0zoM1z0
2026-10-12 23:53:01 +08:00
1783 changed files with 452281 additions and 19836 deletions
+381
View File
@@ -0,0 +1,381 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it, onTestFinished } from "vitest";
import type { AdbDeviceAnalysisPort } from "../../../src/application/adb/AdbDeviceAnalysisPort.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { assertAdvertisedMcpContracts } from "./mcpContractHarness.js";
const identity = { id: "adb", name: "Android Debug Bridge", version: null };
const clientIdentity = {
binary_path: "/usr/bin/adb",
path_source: "path",
version: "34.0.5-debian",
installed_path: "/usr/bin/adb",
};
const results: Readonly<Record<string, unknown>> = {
inspect_adb_client: {
client: clientIdentity,
contacted_adb_server: false,
},
list_adb_devices: {
client: clientIdentity,
devices: [
{
serial: "emulator-5554",
state: "device",
transport: "tcp",
product: "sdk_gphone64_x86_64",
model: "sdk_gphone64_x86_64",
device: "emu64xa",
transport_id: 1,
kind: "emulator",
kind_basis: "emulator_serial_prefix",
},
],
may_have_started_adb_server: false,
},
inspect_adb_device: {
client: clientIdentity,
serial: "emulator-5554",
properties: [{ name: "ro.build.version.sdk", value: "34" }],
property_count: 1,
emulator_observed: true,
},
list_adb_packages: {
client: clientIdentity,
serial: "emulator-5554",
scope: "third_party",
packages: [
{
package_name: "com.example",
base_apk_device_path: "/data/app/x/base.apk",
},
],
unparsed_lines: [],
coverage: "complete",
},
pull_adb_package: {
client: clientIdentity,
serial: "emulator-5554",
package_name: "com.example",
output_directory: "/tmp/rea-pulls",
artifacts: [
{
device_path: "/data/app/x/base.apk",
file_name: "base.apk",
local_path: "/tmp/rea-pulls/com.example/base.apk",
bytes: 2048,
sha256: "a".repeat(64),
role: "base",
role_basis: "file_name",
},
],
failures: [],
coverage: "complete",
},
read_adb_logcat: {
client: clientIdentity,
serial: "emulator-5554",
count: 500,
buffer: "main",
pid: null,
lines: ["08-10 13:00:00.000 I/Tag( 123): message"],
total_bytes: 34,
coverage: "complete",
},
inspect_adb_package: {
client: clientIdentity,
serial: "emulator-5554",
package_name: "com.example",
version_name: "1.2.3",
version_code: 45,
first_install_time: "2026-01-02 03:04:05",
last_update_time: "2026-02-03 04:05:06",
installer_package_name: null,
user_id: 10234,
pkg_flags: "[ HAS_CODE ]",
requested_permissions_count: 2,
coverage: "complete",
},
pull_adb_file: {
client: clientIdentity,
serial: "emulator-5554",
device_path: "/data/local/tmp/notes.txt",
local_path: "/tmp/rea-pulls/notes.txt",
bytes: 10,
sha256: "a".repeat(64),
},
push_adb_file: {
client: clientIdentity,
serial: "emulator-5554",
local_path: "/tmp/payload.bin",
device_path: "/data/local/tmp/payload.bin",
bytes: 12,
sha256: "a".repeat(64),
device_sha256: "a".repeat(64),
overwritten: false,
device_digest_source: "device_sha256sum",
},
capture_adb_screen: {
client: clientIdentity,
serial: "emulator-5554",
local_path: "/tmp/rea-captures/screen.png",
bytes: 8192,
sha256: "a".repeat(64),
width: 1080,
height: 2340,
},
list_adb_processes: {
client: clientIdentity,
serial: "emulator-5554",
columns: "USER PID PPID VSZ RSS WCHAN ADDR S NAME",
processes: [
{
user: "u0_a1",
pid: 1234,
ppid: 567,
rss: 7890,
state: "S",
name: "com.example.app",
},
],
unparsed_lines: [],
coverage: "complete",
},
list_adb_directory: {
client: clientIdentity,
serial: "emulator-5554",
device_path: "/data/local/tmp",
entries: [
{
name: "notes.txt",
kind: "file",
permissions: "-rw-rw-rw-",
owner: "shell",
group: "shell",
bytes: 10,
date: "2026-01-01 10:00",
link_target: null,
},
],
unparsed_lines: [],
coverage: "complete",
},
list_adb_features: {
client: clientIdentity,
serial: "emulator-5554",
features: [{ name: "android.hardware.camera", version: null }],
unparsed_lines: [],
coverage: "complete",
},
list_adb_services: {
client: clientIdentity,
serial: "emulator-5554",
services: [
{ name: "package", interface: "android.content.pm.IPackageManager" },
],
unparsed_lines: [],
coverage: "complete",
},
inspect_adb_display: {
client: clientIdentity,
serial: "emulator-5554",
physical_size: { width: 1080, height: 2340 },
override_size: null,
physical_density: 420,
override_density: null,
},
inspect_adb_window: {
client: clientIdentity,
serial: "emulator-5554",
focused_window: "Window{abcdef u0 com.example.app/Main}",
focused_app: null,
observed_lines: ["Window{abcdef u0 com.example.app/Main}"],
},
read_adb_setting: {
client: clientIdentity,
serial: "emulator-5554",
namespace: "secure",
key: "adb_enabled",
value: "1",
device_reported_null: false,
},
collect_adb_bugreport: {
client: clientIdentity,
serial: "emulator-5554",
local_path: "/tmp/rea-bugreports/bugreport.zip",
bytes: 1024,
sha256: "a".repeat(64),
adb_reported_path: "/tmp/rea-bugreports/bugreport.zip",
},
resolve_adb_packages: {
client: clientIdentity,
serial: "emulator-5554",
query: "whatsapp",
matches: [
{
package_name: "com.whatsapp",
base_apk_device_path: "/data/app/x/base.apk",
},
],
exact_match: true,
coverage: "complete",
},
install_adb_package: {
client: clientIdentity,
serial: "emulator-5554",
apk_path: "/tmp/app.apk",
bytes: 2048,
sha256: "a".repeat(64),
replaced: false,
},
uninstall_adb_package: {
client: clientIdentity,
serial: "emulator-5554",
package_name: "com.whatsapp",
},
start_adb_app: {
client: clientIdentity,
serial: "emulator-5554",
package_name: "com.example.app",
component: "com.example.app/.Main",
started_activity:
"act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.app/.Main",
},
start_adb_activity: {
client: clientIdentity,
serial: "emulator-5554",
action: "android.intent.action.VIEW",
data_uri: "https://example.com/",
component: null,
extras: [],
started_activity: "act=android.intent.action.VIEW dat=https://example.com/",
},
stop_adb_app: {
client: clientIdentity,
serial: "emulator-5554",
package_name: "com.example.app",
},
};
it("advertises exact valid ADB schemas and records inline evidence through MCP", async () => {
const provider: AdbDeviceAnalysisPort = {
async inspectAvailability() {
return { status: "available", code: null, reason: null, diagnostics: {} };
},
async close() {},
async execute(request) {
return ok(createAnalysisExecution(results[request.operation], identity));
},
};
const session = createTestBinarySession(() => {
throw new Error("deep provider must not start");
});
const server = createServer(
{ kind: "session", session },
{ adbDeviceAnalysis: provider },
);
onTestFinished(() => server.close());
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
const client = new Client({ name: "adb-boundary", version: "0.0.0" });
onTestFinished(() => client.close());
await client.connect(clientTransport);
const { tools } = await client.listTools();
const names = tools.map((tool) => tool.name);
const operationNames = [
"inspect_adb_client",
"list_adb_devices",
"inspect_adb_device",
"list_adb_packages",
"pull_adb_package",
"read_adb_logcat",
"inspect_adb_package",
"pull_adb_file",
"push_adb_file",
"capture_adb_screen",
"list_adb_processes",
"list_adb_directory",
"list_adb_features",
"list_adb_services",
"inspect_adb_display",
"inspect_adb_window",
"read_adb_setting",
"collect_adb_bugreport",
"resolve_adb_packages",
"install_adb_package",
"uninstall_adb_package",
"start_adb_app",
"start_adb_activity",
"stop_adb_app",
] as const;
for (const name of operationNames) expect(names, name).toContain(name);
assertAdvertisedMcpContracts(operationNames, tools);
const pulled = await client.callTool({
name: "pull_adb_package",
arguments: {
serial: "emulator-5554",
package: "com.example",
output_directory: "/tmp/rea-pulls",
},
});
expect(pulled.isError).not.toBe(true);
const text = (pulled.content as { readonly text?: string }[])
.map((part) => part.text ?? "")
.join("");
const evidence = parseEvidence(JSON.parse(text));
expect(evidence.provider.id).toBe("adb");
expect(evidence.operation).toBe("pull_adb_package");
expect(evidence.normalized_result).toMatchObject({
artifacts: [{ file_name: "base.apk", role: "base", bytes: 2048 }],
coverage: "complete",
});
});
it("rejects invalid tool input before reaching the provider", async () => {
const provider: AdbDeviceAnalysisPort = {
async inspectAvailability() {
return { status: "available", code: null, reason: null, diagnostics: {} };
},
async close() {},
async execute() {
throw new Error("must not execute");
},
};
const server = createServer(
{
kind: "session",
session: createTestBinarySession(() => {
throw new Error("must not start");
}),
},
{ adbDeviceAnalysis: provider },
);
onTestFinished(() => server.close());
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
const client = new Client({ name: "adb-boundary-invalid", version: "0.0.0" });
onTestFinished(() => client.close());
await client.connect(clientTransport);
const rejected = await client.callTool({
name: "inspect_adb_device",
arguments: { serial: "bad serial" },
});
expect(rejected.isError).toBe(true);
const text = (rejected.content as { readonly text?: string }[])
.map((part) => part.text ?? "")
.join("");
expect(text).toContain("Invalid arguments for tool inspect_adb_device");
});
@@ -0,0 +1,170 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished } from "vitest";
import { BinaryLayoutService } from "../../../src/application/binaryDiagnostics/BinaryLayoutService.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { ok } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { analysisViewLayoutFixture } from "../../fixtures/analysisView.js";
import { BINARY_LAYOUT_TEST_PROVIDER } from "../../fixtures/binaryDiagnostics/layout.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const contract = toolContract("analyze_javascript_application");
const connect = async (
retainsEvidence: boolean,
binaryLayout?: BinaryLayoutService,
) => {
const session = createTestBinarySession(() => {
throw new Error("JavaScript analysis must not start a deep provider");
});
const server = createServer(
retainsEvidence
? { kind: "session", session }
: {
kind: "fixed",
analysis: {
execute: () => {
throw new Error("JavaScript analysis must not use a target");
},
},
},
binaryLayout === undefined ? {} : { binaryLayout },
);
const client = new Client({ name: "analysis-summary-detail", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
return client;
};
const application = async () => {
const root = await createTestTempDirectory("rea-summary-detail-");
await writeFile(
join(root, "main.js"),
'import { helper } from "./util.js";\nexport const greet = (name) => helper(name);\n',
);
await writeFile(
join(root, "util.js"),
"export const helper = (value) => value.toUpperCase();\n",
);
return { input_path: root, format: "directory" };
};
const textBytes = (content: unknown): number => {
const [first] = Array.isArray(content) ? content : [];
if (first?.type !== "text") throw new Error("Missing MCP text result");
return Buffer.byteLength(String(first.text));
};
it("returns the summary of complete Evidence retained for later views", async () => {
const client = await connect(true);
const input = await application();
const complete = await client.callTool({
name: contract.name,
arguments: input,
});
expect(complete.isError).not.toBe(true);
const completeEvidence = contract.outputSchema.parse(
complete.structuredContent,
);
expect(completeEvidence.operation).toBe("analyze_javascript_application");
const summary = await client.callTool({
name: contract.name,
arguments: { ...input, detail: "summary" },
});
expect(summary.isError).not.toBe(true);
const summaryEvidence = contract.outputSchema.parse(
summary.structuredContent,
);
expect(summaryEvidence).toMatchObject({
operation: "inspect_analysis_view",
evidence_links: [completeEvidence.evidence_id],
normalized_result: {
kind: "summary",
parent_evidence_id: completeEvidence.evidence_id,
parent_operation: "analyze_javascript_application",
},
});
expect(textBytes(summary.content)).toBeLessThan(textBytes(complete.content));
const modules = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "retained-evidence",
evidence_id: completeEvidence.evidence_id,
},
view: { kind: "page", collection: "modules", offset: 0, limit: 8 },
},
});
expect(modules.isError).not.toBe(true);
expect(modules.structuredContent).toMatchObject({
normalized_result: {
kind: "page",
parent_evidence_id: completeEvidence.evidence_id,
},
});
});
it("refuses summary detail when the server cannot retain the complete Evidence", async () => {
const client = await connect(false);
const failure = parseMcpToolError(
await client.callTool({
name: contract.name,
arguments: { ...(await application()), detail: "summary" },
}),
);
expect(failure.error).toMatchObject({
code: "capability_unavailable",
message: expect.stringContaining("detail complete"),
});
});
it("returns the summary of retained binary layout Evidence", async () => {
const layout = analysisViewLayoutFixture();
const client = await connect(
true,
new BinaryLayoutService({
identity: BINARY_LAYOUT_TEST_PROVIDER,
inspect: () => Promise.resolve(ok(layout)),
}),
);
const layoutContract = toolContract("inspect_binary_layout");
const summary = await client.callTool({
name: layoutContract.name,
arguments: { path: layout.artifact.path, detail: "summary" },
});
expect(summary.isError).not.toBe(true);
const evidence = layoutContract.outputSchema.parse(summary.structuredContent);
expect(evidence).toMatchObject({
operation: "inspect_analysis_view",
normalized_result: {
kind: "summary",
parent_operation: "inspect_binary_layout",
},
});
const [parentId] = evidence.evidence_links;
const sections = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "retained-evidence", evidence_id: parentId },
view: { kind: "page", collection: "sections", offset: 0, limit: 8 },
},
});
expect(sections.isError).not.toBe(true);
expect(sections.structuredContent).toMatchObject({
normalized_result: { kind: "page", parent_evidence_id: parentId },
});
});
+441 -2
View File
@@ -1,5 +1,14 @@
import { API_SURFACE_EXAMPLE } from "../../../src/contracts/analysisViewApiSurfaceExample.js";
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { WebNetworkCaptureService } from "../../../src/application/WebNetworkCaptureService.js";
import { decodeHarCapture } from "../../../src/browser/history/HarCapture.js";
import { join } from "node:path";
import { apiSurfaceHar } from "../../fixtures/historicalHar.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished } from "vitest";
import { z } from "zod";
@@ -7,6 +16,8 @@ import { z } from "zod";
import { BinaryLayoutService } from "../../../src/application/binaryDiagnostics/BinaryLayoutService.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { jsonObjectSchema } from "../../../src/domain/jsonValue.js";
import { functionDossierSchema } from "../../../src/domain/hopperValues.js";
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
import { ok } from "../../../src/domain/result.js";
@@ -15,22 +26,33 @@ import {
createJavaScriptApplicationNode,
} from "../../../src/domain/javascript/javascriptApplicationGraph.js";
import { createServer } from "../../../src/server/createServer.js";
import { connectGhidraMcp } from "./ghidraMcpHarness.js";
import {
analysisViewJavaScriptEvidence,
analysisViewJavaScriptAnalysisWithSource,
analysisViewBindJavaScriptGraphs,
analysisViewLayoutEvidence,
analysisViewLayoutFixture,
analysisViewCaptureFixture,
analysisViewCaptureEvidence,
analysisViewObjectDenseCapture,
} from "../../fixtures/analysisView.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { BINARY_LAYOUT_TEST_PROVIDER } from "../../fixtures/binaryDiagnostics/layout.js";
const connect = async (binaryLayout?: BinaryLayoutService) => {
const connect = async (
binaryLayout?: BinaryLayoutService,
webNetworkCapture?: WebNetworkCaptureService,
) => {
const session = createTestBinarySession(() => {
throw new Error("selected views must not start a deep provider");
});
const server = createServer(
{ kind: "session", session },
binaryLayout === undefined ? {} : { binaryLayout },
{
...(binaryLayout === undefined ? {} : { binaryLayout }),
...(webNetworkCapture === undefined ? {} : { webNetworkCapture }),
},
);
const client = new Client({ name: "analysis-view-mcp", version: "1" });
onTestFinished(async () => {
@@ -45,6 +67,115 @@ const connect = async (binaryLayout?: BinaryLayoutService) => {
return { client, session };
};
it("discovers an oversized native dossier by exact metadata and reads its retained view", async () => {
const { client, session } = await connect();
const provider = { id: "ghidra", name: "Ghidra", version: "12.1.4" };
const profile = createAnalysisProfile(provider, { language: "fixture" });
const parent = createEvidence(
{ path: "/fixtures/large.exe", format: "pe", sha256: "a".repeat(64) },
provider,
{
operation: "analyze_function",
parameters: { procedure: "0x401000" },
analysisProfile: profile,
result: {
...jsonObjectSchema.parse(ghidraFunctionDossier()),
pseudocode: "x".repeat(6 * 1024 * 1024),
},
rawResult: null,
},
);
const other = createEvidence(
{ path: "/fixtures/other.exe", format: "pe", sha256: "b".repeat(64) },
provider,
{
operation: "analyze_function",
parameters: {},
result: ghidraFunctionDossier(),
},
);
for (const record of [parent, other]) {
const retained = session.recordEvidence(record);
if (!retained.ok) throw retained.error;
}
const broad = await client.callTool({
name: "get_evidence_bundle",
arguments: {},
});
const broadError = parseMcpToolError(broad).error;
expect(broadError.code).toBe("resource_constraint");
expect(broadError.remediation?.action).toContain(
"get_evidence_bundle and detail: summary",
);
const response = await client.callTool({
name: "get_evidence_bundle",
arguments: {
detail: "summary",
filters: {
operation: "analyze_function",
target_sha256: "a".repeat(64),
analysis_profile_digest: profile.digest,
procedure_address: "0x401000",
},
},
});
expect(response.isError).not.toBe(true);
const result = toolContract("get_evidence_bundle").outputSchema.parse(
response.structuredContent,
).result;
expect(result).toMatchObject({
kind: "evidence-bundle-summary",
total_retained_records: 2,
matching_records: 1,
records: [
{
evidence_id: parent.evidence_id,
analysis_profile_digest: profile.digest,
retention: "complete-record",
native_dossier: { available: true, procedure_address: "0x401000" },
},
],
});
expect(JSON.stringify(response)).not.toContain("pseudocode");
expect(
JSON.parse(response.content.find((c) => c.type === "text")?.text ?? "null"),
).toEqual(response.structuredContent);
const page = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
view: { kind: "native", facet: "pseudocode", offset: 0, limit: 32 },
},
});
expect(page.isError).not.toBe(true);
expect(
toolContract("inspect_analysis_view").outputSchema.parse(
page.structuredContent,
).normalized_result,
).toMatchObject({
item: { text: "x".repeat(32) },
coverage: { total: 6 * 1024 * 1024, exhausted: false },
});
const empty = await client.callTool({
name: "get_evidence_bundle",
arguments: {
detail: "summary",
filters: { evidence_id: `ev_${"e".repeat(64)}` },
},
});
expect(
toolContract("get_evidence_bundle").outputSchema.parse(
empty.structuredContent,
).result,
).toMatchObject({ matching_records: 0, records: [] });
await client.ping();
const invalid = await client.callTool({
name: "get_evidence_bundle",
arguments: { filters: { operation: "analyze_function" } },
});
expect(parseMcpToolError(invalid).error.code).toBe("invalid_request");
});
it("advertises exact schemas and projects one layout section from retained Evidence", async () => {
const layout = analysisViewLayoutFixture();
const service = new BinaryLayoutService({
@@ -62,6 +193,18 @@ it("advertises exact schemas and projects one layout section from retained Evide
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
expect(
ajv.validate(inputSchema, {
source: { kind: "inline", evidence: analysisViewLayoutEvidence() },
view: { kind: "summary" },
}),
).toBe(true);
expect(
ajv.validate(inputSchema, {
source: { kind: "inline", evidence: {} },
view: { kind: "summary" },
}),
).toBe(false);
expect(
ajv.validate(inputSchema, {
source: {
@@ -111,6 +254,129 @@ it("advertises exact schemas and projects one layout section from retained Evide
);
});
it("reports a tampered inline Evidence ID at its full MCP source path", async () => {
const { client } = await connect();
const parent = analysisViewLayoutEvidence();
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "inline",
evidence: { ...parent, evidence_id: `ev_${"0".repeat(64)}` },
},
view: { kind: "summary" },
},
});
expect(parseMcpToolError(response).error).toMatchObject({
code: "invalid_request",
category: "invalid_input",
details: {
issues: [
{
path: ["source", "evidence", "evidence_id"],
reason: "invalid_value",
message: "Evidence semantic identifier does not match its record",
},
],
},
});
});
it("admits portable captures before SDK Evidence parsing and preserves capture caveats", async () => {
const { client } = await connect();
const dense = analysisViewCaptureEvidence(analysisViewObjectDenseCapture());
const refused = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "inline", evidence: dense },
view: { kind: "api-surface" },
},
});
expect(parseMcpToolError(refused).error).toMatchObject({
code: "resource_constraint",
details: { resource: "memory" },
});
await client.ping();
const capture = analysisViewCaptureFixture();
capture.records = capture.records.slice(0, 1);
capture.total_records = 1;
const caveat = "Producer omitted exchanges before capture startup.";
capture.limitations = [caveat, caveat];
capture.records[0]!.reported = {
request: { method: "GET", url: "https://api.test/a" },
response: { status: 200, content: { mimeType: "\u00a0text/plain\u00a0" } },
};
const parent = analysisViewCaptureEvidence(capture);
expect(parent.limitations).not.toContain(caveat);
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "inline", evidence: parent },
view: { kind: "api-surface" },
},
});
const result = parseEvidence(response.structuredContent);
expect(result.limitations.filter((value) => value === caveat)).toEqual([
caveat,
]);
expect(result.normalized_result).toMatchObject({
groups: [{ content_types: [], flags: ["single-sample"] }],
limitations: expect.arrayContaining([caveat]),
unknowns: [
"Some retained records have unavailable status or content type values.",
],
});
});
it("rejects inconsistent portable coverage and accepts caller-ordered ordinal subsets", async () => {
const { client } = await connect();
for (const [total, ordinals] of [
[0, [0]],
[2, [0, 0]],
[2, [2]],
] as const) {
const capture = analysisViewCaptureFixture();
capture.total_records = total;
capture.records = ordinals.map((ordinal) => ({
...capture.records[0]!,
ordinal,
}));
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "inline",
evidence: analysisViewCaptureEvidence(capture),
},
view: { kind: "api-surface" },
},
});
expect(parseMcpToolError(response).error.code).toBe("invalid_request");
}
const capture = analysisViewCaptureFixture();
capture.records = [capture.records[8]!, capture.records[1]!];
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "inline",
evidence: analysisViewCaptureEvidence(capture),
},
view: { kind: "api-surface" },
},
});
expect(
parseEvidence(response.structuredContent).normalized_result,
).toMatchObject({
records: { examined: 2, total: 15 },
limitations: expect.arrayContaining([
"Parent contains an ordinal subset; the surface covers only retained records.",
]),
});
});
it("delivers a bounded native dossier view over MCP without a Ghidra provider or lost connection", async () => {
const { client, session } = await connect();
const original = functionDossierSchema.parse(ghidraFunctionDossier());
@@ -314,6 +580,95 @@ it("retains an oversized native assembly row and permits a subsequent smaller vi
await client.ping();
});
it("reads successive native source pages directly from a completed-result transport error", async () => {
const pseudocode = "int fixture_add(int a, int b) { return a + b; }\n".repeat(
150_000,
);
const harness = await connectGhidraMcp(
"native-continuation",
async (operation) => {
if (operation !== "analyze_function")
throw new Error(`Unexpected provider operation: ${operation}`);
return ok({
value: {
...functionDossierSchema.parse(ghidraFunctionDossier()),
pseudocode,
},
limitations: [],
});
},
);
onTestFinished(() => harness.close());
const { mcp: client, session, calls } = harness;
const failed = await client.callTool({
name: "analyze_function",
arguments: { procedure: "0x401000" },
});
expect(failed.isError).toBe(true);
const limits = z
.object({
error: z.object({
details: z.object({ reported_limits: jsonObjectSchema }),
}),
})
.parse(parseMcpToolError(failed)).error.details.reported_limits;
const reference = z
.object({
kind: z.literal("retained-evidence"),
evidence_id: z.string(),
})
.parse(limits.evidence_reference);
const parent = parseEvidence(session.evidenceById(reference.evidence_id));
expect(parent.operation).toBe("analyze_function");
expect(parent.parameters).toMatchObject({ procedure: "0x401000" });
const call = z
.object({
name: z.literal("inspect_analysis_view"),
arguments: toolContract("inspect_analysis_view").inputSchema,
})
.parse(limits.continuation);
expect(call.arguments.source).toEqual({
kind: "retained-evidence",
evidence_id: parent.evidence_id,
});
const first = await client.callTool(call);
expect(first.isError).not.toBe(true);
const page = toolContract("inspect_analysis_view").outputSchema.parse(
first.structuredContent,
).normalized_result;
expect(page).toMatchObject({
parent_evidence_id: parent.evidence_id,
item: { text: pseudocode.slice(0, 64) },
coverage: { examined: 64, next_offset: 64, exhausted: false },
});
expect(Buffer.byteLength(JSON.stringify(first))).toBeLessThan(
STDIO_DEFAULT_MAX_BUFFER_SIZE,
);
const second = await client.callTool({
name: call.name,
arguments: {
...call.arguments,
view: {
kind: "native",
facet: "pseudocode",
offset: page.coverage.next_offset,
limit: 64,
},
},
});
expect(second.isError).not.toBe(true);
expect(
toolContract("inspect_analysis_view").outputSchema.parse(
second.structuredContent,
).normalized_result,
).toMatchObject({ item: { text: pseudocode.slice(64, 128) } });
expect(
session.evidenceById(parent.evidence_id)?.normalized_result,
).toMatchObject({ pseudocode });
await client.ping();
expect(calls).toEqual(["analyze_function"]);
});
it("returns a JavaScript summary without graph payloads from a retained reference", async () => {
const { client, session } = await connect();
const parent = analysisViewJavaScriptEvidence();
@@ -392,3 +747,87 @@ it("accepts a transport-constraint retained reference as the view source", async
},
]);
});
it("projects an actual HAR capture retained by the public MCP workflow", async () => {
const root = await createTestTempDirectory("rea-surface-mcp-");
const path = join(root, "surface.har");
await writeFile(path, JSON.stringify(apiSurfaceHar()));
const service = new WebNetworkCaptureService({
inspect: async (input) => {
const bytes = await readFile(input.capture_path);
return ok({
...decodeHarCapture(bytes.toString("utf8"), input.sensitive_values),
artifact: {
path: input.capture_path,
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.length,
},
format: "har",
runtime_attribution: "unknown",
limitations: [],
});
},
});
const { client } = await connect(undefined, service);
const captureResponse = await client.callTool({
name: "inspect_web_network_capture",
arguments: { capture_path: path, format: "har" },
});
expect(captureResponse.isError).not.toBe(true);
const parent = parseEvidence(captureResponse.structuredContent);
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
view: { kind: "api-surface" },
},
});
expect(response.isError).not.toBe(true);
const evidence = parseEvidence(response.structuredContent);
expect(evidence.confidence).toBe("inferred");
expect(evidence.normalized_result).toMatchObject({
records: { examined: 13, total: 13, excluded: 0 },
coverage: { total: 12, exhausted: true },
groups: expect.arrayContaining([
expect.objectContaining({
path_template: "/users/{numeric}",
record_ordinals: [0, 1],
}),
]),
});
});
it("reproduces the published API surface example from decoded fixture bytes", async () => {
const fixture = apiSurfaceHar();
fixture.log.entries = fixture.log.entries.slice(0, 2);
const bytes = Buffer.from(JSON.stringify(fixture));
const service = new WebNetworkCaptureService({
inspect: async () =>
ok({
...decodeHarCapture(bytes.toString("utf8"), []),
artifact: {
path: "/fixtures/api-surface.har",
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.length,
},
format: "har",
runtime_attribution: "unknown",
limitations: [],
}),
});
const { client } = await connect(undefined, service);
const capture = await client.callTool({
name: "inspect_web_network_capture",
arguments: { capture_path: "/fixtures/api-surface.har", format: "har" },
});
expect(parseEvidence(capture.structuredContent).evidence_id).toBe(
API_SURFACE_EXAMPLE.input.source.evidence_id,
);
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: API_SURFACE_EXAMPLE.input,
});
expect(parseEvidence(response.structuredContent).normalized_result).toEqual(
API_SURFACE_EXAMPLE.output,
);
});
+95
View File
@@ -0,0 +1,95 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it, onTestFinished } from "vitest";
import type { ApktoolResourceAnalysisPort } from "../../../src/application/apktool/ApktoolResourceAnalysisPort.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { assertAdvertisedMcpContracts } from "./mcpContractHarness.js";
const identity = { id: "apktool", name: "Apktool", version: "2.7.0-dirty" };
const clientIdentity = {
command: "/usr/bin/apktool",
command_source: "path",
apktool_version: "2.7.0-dirty",
};
const results: Readonly<Record<string, unknown>> = {
inspect_apktool_client: { client: clientIdentity },
decode_android_resources: {
client: clientIdentity,
target: {
path: "/targets/probe.apk",
bytes: 8524,
sha256: "a".repeat(64),
},
metadata: {
version_name: "1.2.3",
version_code: "7",
min_sdk_version: "24",
target_sdk_version: "34",
package_name: "com.rea.apktool.probe",
},
manifest:
'<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.rea.apktool.probe"/>',
strings: [{ name: "app_name", value: "ApktoolProbe" }],
locale: null,
locales: ["de"],
decoded_file_count: 5,
coverage: "complete",
},
};
it("advertises exact valid Apktool schemas and records inline evidence through MCP", async () => {
const provider: ApktoolResourceAnalysisPort = {
async inspectAvailability() {
return { status: "available", code: null, reason: null, diagnostics: {} };
},
async close() {},
async execute(request) {
return ok(createAnalysisExecution(results[request.operation], identity));
},
};
const session = createTestBinarySession(() => {
throw new Error("deep provider must not start");
});
const server = createServer(
{ kind: "session", session },
{ apktoolAnalysis: provider },
);
onTestFinished(() => server.close());
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
const client = new Client({ name: "apktool-boundary", version: "0.0.0" });
onTestFinished(() => client.close());
await client.connect(clientTransport);
const { tools } = await client.listTools();
const names = tools.map((tool) => tool.name);
const operationNames = [
"inspect_apktool_client",
"decode_android_resources",
] as const;
for (const name of operationNames) expect(names, name).toContain(name);
assertAdvertisedMcpContracts(operationNames, tools);
const decoded = await client.callTool({
name: "decode_android_resources",
arguments: { path: "/targets/probe.apk" },
});
expect(decoded.isError).not.toBe(true);
const text = (decoded.content as { readonly text?: string }[])
.map((part) => part.text ?? "")
.join("");
const evidence = parseEvidence(JSON.parse(text));
expect(evidence.provider.id).toBe("apktool");
expect(evidence.normalized_result).toMatchObject({
metadata: { package_name: "com.rea.apktool.probe", version_name: "1.2.3" },
coverage: "complete",
});
});
@@ -1,6 +1,7 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import type { Client } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { Ajv2020 } from "ajv/dist/2020.js";
import type { BinarySession } from "../../../src/application/binary/BinarySession.js";
import {
@@ -13,6 +14,7 @@ import {
createApplicationMcpHarness,
type ApplicationMcpHarness,
} from "../../fixtures/applicationMcpHarness.js";
import { createHistoricalSourceGraph } from "../../../src/domain/referenceSourceGraph.js";
async function runInlineWorkflowScenarios(
harness: ApplicationMcpHarness,
@@ -89,6 +91,57 @@ async function runInlineWorkflowScenarios(
],
},
});
const referenceWithExclusion = createHistoricalSourceGraph({
...SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference,
root_sha256: undefined,
inventory_state: "partial",
exclusions: [
{
path: "vendor/removed.ts",
reason: "project-ignored",
pattern: "vendor/",
},
],
});
const argumentsWithExclusion = {
...SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
reference: referenceWithExclusion,
};
const advertised = (await harness.client.listTools()).tools.find(
({ name }) => name === "compare_source_to_bundle",
);
if (advertised === undefined) throw new Error("Comparison tool is missing");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
expect(ajv.validateSchema(advertised.inputSchema)).toBe(true);
const validate = ajv.compile(advertised.inputSchema);
expect(validate(argumentsWithExclusion)).toBe(true);
const missingPattern = {
...argumentsWithExclusion,
reference: {
...referenceWithExclusion,
exclusions: [{ path: "vendor/removed.ts", reason: "project-ignored" }],
},
};
expect(validate(missingPattern)).toBe(false);
const rejectedExclusion = await harness.client.callTool({
name: "compare_source_to_bundle",
arguments: missingPattern,
});
expect(rejectedExclusion.isError).toBe(true);
const sourceComparedWithExclusion = await harness.client.callTool({
name: "compare_source_to_bundle",
arguments: argumentsWithExclusion,
});
expect(sourceComparedWithExclusion.isError).not.toBe(true);
expect(sourceComparedWithExclusion.structuredContent).toMatchObject({
normalized_result: {
reference: {
root_sha256: referenceWithExclusion.root_sha256,
inventory_state: "partial",
},
},
});
expect(harness.session.exportEvidenceBundle().records.length).toBeGreaterThan(
2,
);
@@ -6,7 +6,7 @@ import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
import { compareJavaScriptExportShapesEvidence } from "../../../src/application/javascript/JavaScriptApplicationWorkflowService.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { javaScriptExportShapeComparisonResultSchema } from "../../../src/domain/javascript/javascriptExportShapeComparisonSchemas.js";
@@ -7,7 +7,7 @@ import {
projectedExportReturnShapesSchema,
} from "../../../src/domain/javascript/javascriptExportShapeComparisonSchemas.js";
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { javaScriptSemanticTraceResultSchema } from "../../../src/domain/javascript/javascriptSemanticTraceSchemas.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
@@ -1,8 +1,9 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { readFile, writeFile } from "node:fs/promises";
import { readFile, unlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { expect, it } from "vitest";
import { z } from "zod";
@@ -12,8 +13,81 @@ 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";
import {
createEvidence,
parseEvidence,
type Evidence,
} from "../../../src/domain/evidence.js";
import {
artifactInspectionResultSchema,
createArtifactInspection,
} from "../../../src/domain/artifactInspection.js";
import {
artifactInventoryResultSchema,
type ArtifactInventoryResult,
} from "../../../src/domain/artifactGraph.js";
import {
analysisViewResultSchema,
type AnalysisViewResult,
} from "../../../src/domain/analysisView/analysisView.js";
it("inspects a standalone keyed archive through MCP with original object identities", async () => {
const assertInventorySubjectValidation = async (
client: Client,
source: Evidence,
): Promise<void> => {
const result =
source.operation === "inspect_artifact"
? artifactInspectionResultSchema.parse(source.normalized_result)
.substeps[0]?.evidence.normalized_result
: source.normalized_result;
const inventory = artifactInventoryResultSchema.parse(result);
if (source.subject === null)
throw new Error("Fixture requires a known subject");
for (const target of [
undefined,
{
path: source.subject.local_path,
sha256: inventory.manifest.root_sha256,
format: "file" as const,
},
{
path: source.subject.local_path,
sha256: "f".repeat(64),
format: inventory.manifest.root_format,
},
]) {
const inconsistent = createEvidence(target, source.provider, {
operation: source.operation,
parameters: source.parameters,
result: source.normalized_result,
});
for (const view of [
{ kind: "summary" },
{ kind: "inventory", collection: "nodes", offset: 0, limit: 1 },
]) {
const reply = await client.callTool({
name: "inspect_analysis_view",
arguments: { source: { kind: "inline", evidence: inconsistent }, view },
});
expect(parseMcpToolError(reply)).toMatchObject({
error: {
code: "invalid_request",
details: {
issues: [
{
path: ["source"],
reason: "invalid_value",
message: expect.stringContaining("subject does not match"),
},
],
},
},
});
}
}
};
it("preserves keyed archive identities and rejects inconsistent inventory carrier subjects", async () => {
const directory = await createTestTempDirectory("rea-keyed-mcp-");
const path = join(directory, "archive.plist");
await writeFile(
@@ -99,6 +173,19 @@ it("inspects a standalone keyed archive through MCP with original object identit
},
},
});
const inspected = await client.callTool({
name: "inspect_artifact",
arguments: {},
});
expect(inspected.isError).not.toBe(true);
const parent = parseEvidence(inspected.structuredContent);
const inspection = artifactInspectionResultSchema.parse(
parent.normalized_result,
);
const inventory = inspection.substeps[0]?.evidence;
if (inventory === undefined) throw new Error("Missing inventory Evidence");
await assertInventorySubjectValidation(client, inventory);
await assertInventorySubjectValidation(client, parent);
} finally {
await client.close();
await server.close();
@@ -106,7 +193,201 @@ it("inspects a standalone keyed archive through MCP with original object identit
}
});
it("returns all 520 ZIP file occurrences in one inspect_artifact MCP result", async () => {
const createInventoryViewReader = async (client: Client, parent: Evidence) => {
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_analysis_view",
);
if (advertised?.outputSchema === undefined)
throw new Error("Missing advertised view schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
const validateInput = ajv.compile(inputSchema);
const validateOutput = ajv.compile(outputSchema);
expect(
validateInput({
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
view: { kind: "inventory", collection: "nodes", logical_paths: [] },
}),
).toBe(false);
const readView = async (
view: Record<string, unknown>,
source = {
kind: "retained-evidence",
evidence_id: parent.evidence_id,
},
) => {
const arguments_ = { source, view };
expect(
validateInput(arguments_),
JSON.stringify(validateInput.errors),
).toBe(true);
const reply = await client.callTool({
name: "inspect_analysis_view",
arguments: arguments_,
});
if (reply.isError)
throw new Error(JSON.stringify(parseMcpToolError(reply)));
expect(
validateOutput(reply.structuredContent),
JSON.stringify(validateOutput.errors),
).toBe(true);
const evidence = parseEvidence(reply.structuredContent);
return {
evidence,
result: analysisViewResultSchema.parse(evidence.normalized_result),
};
};
return readView;
};
const assertHistoricalInventory = async (
client: Client,
input: {
archive: string;
parent: Evidence;
inventoryEvidence: Evidence;
graph: ArtifactInventoryResult;
},
) => {
const { archive, parent, inventoryEvidence, graph } = input;
// Historical records may omit a later inventory field. Input parsing must
// not insert defaults inside that authenticated child Evidence.
const { integrity_contradictions: _contradictions, ...legacyInventory } =
graph;
const legacyTarget = {
path: archive,
sha256: graph.manifest.root_sha256,
format: "zip" as const,
};
const legacySource = createEvidence(
legacyTarget,
inventoryEvidence.provider,
{
operation: "inventory_artifact",
parameters: {},
result: legacyInventory,
},
);
const legacyInspection = createArtifactInspection(legacySource);
expect(legacyInspection.substeps[0]?.evidence).toEqual(legacySource);
expect(
legacyInspection.substeps[0]?.evidence.normalized_result,
).not.toHaveProperty("integrity_contradictions");
const legacyParent = createEvidence(legacyTarget, parent.provider, {
operation: "inspect_artifact",
parameters: {},
result: legacyInspection,
});
const legacyReply = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "inline", evidence: legacyParent },
view: { kind: "summary" },
},
});
expect(
legacyReply.isError,
JSON.stringify(legacyReply.structuredContent),
).not.toBe(true);
expect(
parseEvidence(legacyReply.structuredContent).normalized_result,
).toMatchObject({
parent_evidence_id: legacyParent.evidence_id,
summary: {
source_complete: true,
inventory_evidence_ids: [legacySource.evidence_id],
},
});
};
const assertPortableRoundtrip = async (
client: Client,
directory: string,
parent: Evidence,
originalView: AnalysisViewResult,
) => {
const saved = join(directory, "evidence.json");
const exported = await client.callTool({
name: "export_evidence_bundle",
arguments: { path: saved },
});
if (exported.isError)
throw new Error(JSON.stringify(parseMcpToolError(exported)));
const closed = await client.callTool({
name: "close_binary",
arguments: {},
});
if (closed.isError)
throw new Error(JSON.stringify(parseMcpToolError(closed)));
const missing = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
view: { kind: "summary" },
},
});
expect(parseMcpToolError(missing)).toMatchObject({
error: { details: { reason: "missing" } },
});
const imported = await client.callTool({
name: "import_evidence_bundle",
arguments: { path: saved },
});
if (imported.isError)
throw new Error(JSON.stringify(parseMcpToolError(imported)));
const restored = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
view: { kind: "summary" },
},
});
if (restored.isError)
throw new Error(JSON.stringify(parseMcpToolError(restored)));
expect(parseEvidence(restored.structuredContent).normalized_result).toEqual(
originalView,
);
};
const assertSummaryDelivery = async (
client: Client,
session: ReturnType<typeof createTestBinarySession>,
complete: Evidence,
) => {
expect(complete.parameters).not.toHaveProperty("detail");
const reply = await client.callTool({
name: "inspect_artifact",
arguments: { detail: "summary" },
});
expect(reply.isError, JSON.stringify(reply.structuredContent)).not.toBe(true);
const projected = parseEvidence(reply.structuredContent);
const view = analysisViewResultSchema.parse(projected.normalized_result);
expect(projected.operation).toBe("inspect_analysis_view");
expect(view.kind).toBe("summary");
const retained = session.evidenceById(view.parent_evidence_id);
if (retained === undefined) throw new Error("Missing complete inspection");
expect(retained.operation).toBe("inspect_artifact");
expect(retained.parameters).toMatchObject({ detail: "summary" });
expect(retained.normalized_result).toEqual(complete.normalized_result);
expect(retained.evidence_id).not.toBe(projected.evidence_id);
const inspection = artifactInspectionResultSchema.parse(
retained.normalized_result,
);
expect(
session.evidenceById(inspection.substeps[0]?.evidence_id ?? ""),
).toEqual(inspection.substeps[0]?.evidence);
const explicit = await client.callTool({
name: "inspect_artifact",
arguments: { detail: "complete" },
});
expect(explicit.isError).not.toBe(true);
expect(parseEvidence(explicit.structuredContent).normalized_result).toEqual(
complete.normalized_result,
);
};
it("keeps complete ZIP output and reads retained inventory views after the source is removed", async () => {
const directory = await createTestTempDirectory("rea-artifact-inline-");
const archive = join(directory, "many.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
@@ -138,27 +419,154 @@ it("returns all 520 ZIP file occurrences in one inspect_artifact MCP result", as
expect(result.isError, JSON.stringify(result.structuredContent)).not.toBe(
true,
);
const inspection = z
.object({
substeps: z.array(
z.object({
evidence: z.object({
normalized_result: z.object({
occurrences: z.array(z.object({ logical_path: z.string() })),
}),
}),
}),
),
})
.parse(
z
.object({ normalized_result: z.unknown() })
.parse(result.structuredContent).normalized_result,
);
const parent = parseEvidence(result.structuredContent);
await assertSummaryDelivery(client, session, parent);
const parsedInspection = artifactInspectionResultSchema.parse(
parent.normalized_result,
);
const inventoryEvidence = parsedInspection.substeps[0]?.evidence;
if (inventoryEvidence === undefined)
throw new Error("Missing inventory Evidence");
const graph = artifactInventoryResultSchema.parse(
inventoryEvidence.normalized_result,
);
expect(graph.occurrences).toHaveLength(fileCount + 1);
// Follow-ups must use retained source facts, not reopen this archive.
await unlink(archive);
const readView = await createInventoryViewReader(client, parent);
const summary = await readView({ kind: "summary" });
expect(summary.result).toMatchObject({
kind: "summary",
parent_evidence_id: parent.evidence_id,
artifact: { path: archive, sha256: graph.manifest.root_sha256 },
summary: {
manifest: graph.manifest,
source_complete: true,
available_counts: { occurrences: fileCount + 1 },
observed_entry_kind_counts: { file: fileCount + 1 },
inventory_evidence_ids: [inventoryEvidence.evidence_id],
},
});
expect(summary.evidence.evidence_links).toEqual([parent.evidence_id]);
const paths = ["files/0.txt", "files/519.txt", "missing.txt"];
const selected = await readView({
kind: "inventory",
collection: "occurrences",
logical_paths: paths,
offset: 0,
limit: 1,
});
expect(selected.result).toMatchObject({
kind: "inventory",
source_complete: true,
items: graph.occurrences
.filter((row) => paths.includes(row.logical_path))
.slice(0, 1),
coverage: { examined: 1, total: 2, next_offset: 1, exhausted: false },
});
const next = await readView({
kind: "inventory",
collection: "occurrences",
logical_paths: paths,
offset: 1,
limit: 1,
});
expect(next.result).toMatchObject({
coverage: { examined: 1, next_offset: null, exhausted: true },
});
const none = await readView({
kind: "inventory",
collection: "occurrences",
logical_paths: [],
});
expect(none.result).toMatchObject({
items: [],
coverage: { total: 0, exhausted: true },
});
const partial = createEvidence(
{ path: archive, sha256: graph.manifest.root_sha256, format: "zip" },
inventoryEvidence.provider,
{
operation: "inventory_artifact",
parameters: {},
result: { ...graph, occurrences: graph.occurrences.slice(0, 1) },
},
);
const partialReply = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "inline", evidence: partial },
view: {
kind: "inventory",
collection: "occurrences",
logical_paths: ["missing.txt"],
},
},
});
expect(
inspection.substeps[0]?.evidence.normalized_result.occurrences,
).toHaveLength(fileCount + 1);
parseEvidence(partialReply.structuredContent).normalized_result,
).toMatchObject({
source_complete: false,
items: [],
unknowns: expect.arrayContaining([
expect.stringContaining("Missing matches do not establish absence"),
]),
});
await assertHistoricalInventory(client, {
archive,
parent,
inventoryEvidence,
graph,
});
await assertPortableRoundtrip(client, directory, parent, summary.result);
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
await client.close();
await server.close();
await session.close();
}
});
it("refuses summary delivery without a retained Evidence owner and preserves complete delivery", async () => {
const directory = await createTestTempDirectory("rea-inventory-fixed-");
const archive = join(directory, "fixture.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("main.js", new TextReader("console.log('fixed');\n"));
await writeFile(archive, await writer.close());
const session = createTestBinarySession(new ArtifactProvider(process.env));
const opened = await session.open(archive);
if (!opened.ok) throw opened.error;
const server = createServer({ kind: "fixed", analysis: session });
const client = new Client({ name: "artifact-fixed-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const summary = await client.callTool({
name: "inspect_artifact",
arguments: { detail: "summary" },
});
expect(parseMcpToolError(summary)).toMatchObject({
error: {
code: "capability_unavailable",
message: expect.stringContaining("does not retain Evidence"),
},
});
const complete = await client.callTool({
name: "inspect_artifact",
arguments: {},
});
expect(complete.isError).not.toBe(true);
expect(
parseEvidence(complete.structuredContent).normalized_result,
).toMatchObject({
substeps: [expect.objectContaining({ operation: "inventory_artifact" })],
});
} finally {
await client.close();
await server.close();
await session.close();
}
});
+9 -6
View File
@@ -18,6 +18,13 @@ import { ARTIFACT_COMPARISON_EXAMPLE } from "../../../src/contracts/artifactComp
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
const integrityMessage = (unpacked: boolean): string =>
`${
unpacked
? "Declared ASAR integrity for unpacked entry main.js contradicts its companion file; packaging tools commonly sign or strip unpacked native binaries after writing the archive."
: "Artifact bytes contradict declared integrity."
} If expected, rerun inspect_artifact with integrity_policy=record-and-continue (CLI: --integrity-policy record-and-continue) to retain observed bytes as untrusted; otherwise get a fresh copy.`;
it.each([
{ unpacked: false, label: "embedded" },
{ unpacked: true, label: "unpacked" },
@@ -69,8 +76,7 @@ it.each([
error: {
code: "artifact_integrity_mismatch",
category: "integrity_mismatch",
message:
"Artifact is invalid or has changed. Get a fresh copy and try again.",
message: integrityMessage(unpacked),
details: {
logical_path: "main.js",
declared_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
@@ -78,10 +84,7 @@ it.each([
unpacked,
},
retryable: false,
remediation: {
action:
"Artifact is invalid or has changed. Get a fresh copy and try again.",
},
remediation: { action: integrityMessage(unpacked) },
},
});
} finally {
@@ -0,0 +1,95 @@
import { readFile, rm } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it, onTestFinished } from "vitest";
import { z } from "zod";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createStrippedAsarAddon } from "../../fixtures/strippedAsarAddon.js";
const openArchive = async (archive: string): Promise<Client> => {
const session = createTestBinarySession(new ArtifactProvider(process.env));
const server = createServer({ kind: "session", session });
const client = new Client({ name: "asar-unpacked-extraction", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
onTestFinished(async () => {
await Promise.allSettled([client.close(), server.close(), session.close()]);
});
const opened = await client.callTool({
name: "open_binary",
arguments: { path: archive },
});
expect(opened.isError).not.toBe(true);
return client;
};
it("extracts a rewritten unpacked companion only when the caller records the mismatch", async () => {
const { archive, addon, stripped } = await createStrippedAsarAddon();
const client = await openArchive(archive);
const strict = await client.callTool({
name: "extract_artifact",
arguments: {},
});
expect(parseMcpToolError(strict).error).toMatchObject({
code: "artifact_integrity_mismatch",
message: expect.stringContaining(
`Declared ASAR integrity for unpacked entry ${addon} contradicts its companion file; packaging tools commonly sign or strip unpacked native binaries after writing the archive. If expected, rerun extract_artifact with integrity_policy=record-and-continue`,
),
details: { logical_path: addon, unpacked: true },
});
const continued = await client.callTool({
name: "extract_artifact",
arguments: { integrity_policy: "record-and-continue" },
});
expect(continued.isError, JSON.stringify(continued)).not.toBe(true);
const evidence = parseEvidence(continued.structuredContent);
expect(evidence.parameters).toMatchObject({
integrity_policy: "record-and-continue",
});
const result = z
.object({
output_root: z.string(),
integrity_contradictions: z.array(
z.object({ logical_path: z.string(), trust: z.string() }),
),
limitations: z.array(z.string()),
})
.parse(evidence.normalized_result);
onTestFinished(() =>
rm(result.output_root, { recursive: true, force: true }),
);
expect(await readFile(join(result.output_root, addon))).toEqual(stripped);
expect(result.integrity_contradictions).toEqual([
{ logical_path: addon, trust: "observed-untrusted" },
]);
expect(result.limitations).toContain(
"1 extracted file(s) contradict declared integrity metadata; their bytes are observed-untrusted.",
);
});
it("names a missing unpacked companion instead of reporting a changed artifact", async () => {
const { archive, addon } = await createStrippedAsarAddon();
await rm(join(`${archive}.unpacked`, addon));
const client = await openArchive(archive);
const extracted = await client.callTool({
name: "extract_artifact",
arguments: {},
});
expect(parseMcpToolError(extracted).error).toMatchObject({
code: "artifact_operation_failed",
category: "unavailable",
message: `ASAR unpacked companion bytes are unavailable for ${addon}. Select the archive in place with its .unpacked directory beside it, then retry.`,
details: { logical_path: addon, unpacked: true },
});
});
+226 -26
View File
@@ -1,4 +1,5 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { crc32, deflateSync } from "node:zlib";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
@@ -7,10 +8,16 @@ import { afterEach, expect, it } from "vitest";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { webPageInspectionSchema } from "../../../src/domain/browserObservationSchemas.js";
import { createWebScreenshotArtifact } from "../../../src/domain/webScreenshot.js";
import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "../../../src/contracts/javascript/javascriptRuntimeReconciliationExample.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import {
TOOL_CONTRACTS,
toolContract,
} from "../../../src/contracts/toolContracts.js";
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { runCliJson } from "../../fixtures/cliJsonProcess.js";
import {
startFakeCdpBrowser,
type FakeCdpBrowser,
@@ -56,16 +63,18 @@ it(
name: "binary_session",
arguments: {},
});
expect(status.structuredContent).toMatchObject({
result: {
tool_availability: expect.arrayContaining([
expect.objectContaining({
name: "inspect_web_page",
reason: expect.any(String),
}),
]),
},
});
const sessionStatus = toolContract("binary_session").outputSchema.parse(
status.structuredContent,
);
const availability = expandToolAvailability(
sessionStatus.result.tool_availability,
);
expect(availability).toContainEqual(
expect.objectContaining({
name: "inspect_web_page",
reason: expect.any(String),
}),
);
const listed = await connected.client.callTool({
name: "list_browser_targets",
arguments: {
@@ -194,9 +203,9 @@ const verifySessionAndComparisonTools = async (
normalized_result: { overall_status: "unknown" },
});
const parsedCapture = webPageInspectionSchema.parse(capture);
const socket = parsedCapture.network.websocket_events.find(
(event) => event.payload_shape?.json_shape != null,
);
const socket = parsedCapture.network.websocket_connections
.flatMap((connection) => connection.events)
.find((event) => event.payload_shape?.json_shape != null);
const payload = socket?.payload_shape;
if (socket === undefined || payload == null || payload.json_shape === null)
throw new Error("Missing deep WebSocket JSON shape fixture");
@@ -204,18 +213,27 @@ const verifySessionAndComparisonTools = async (
...parsedCapture,
network: {
...parsedCapture.network,
websocket_events: [
{
...socket,
payload_shape: {
...payload,
json_shape: {
...payload.json_shape,
properties: [{ path: "/event", types: [42], observations: 1 }],
},
},
},
],
websocket_connections: parsedCapture.network.websocket_connections.map(
(connection) => ({
...connection,
events: connection.events.map((event) =>
event === socket
? {
...event,
payload_shape: {
...payload,
json_shape: {
...payload.json_shape,
properties: [
{ path: "/event", types: [42], observations: 1 },
],
},
},
}
: event,
),
}),
),
},
};
const malformedComparison = await connected.client.callTool({
@@ -253,6 +271,8 @@ const verifySessionAndComparisonTools = async (
expect(visual.structuredContent).toMatchObject({
normalized_result: { status: "identical", changed_pixels: 0 },
});
await assertScreenshotPngFailures(connected.client);
expect(inspected.structuredContent).toMatchObject({
normalized_result: expect.any(Object),
operation: "inspect_web_page",
@@ -261,6 +281,149 @@ const verifySessionAndComparisonTools = async (
});
};
const pngChunk = (type: string, data: Buffer): Buffer => {
const chunk = Buffer.alloc(12 + data.length);
chunk.writeUInt32BE(data.length, 0);
chunk.write(type, 4, 4, "ascii");
data.copy(chunk, 8);
chunk.writeUInt32BE(
crc32(chunk.subarray(4, 8 + data.length)),
8 + data.length,
);
return chunk;
};
const assertScreenshotPngFailures = async (client: Client): Promise<void> => {
const header = Buffer.alloc(13);
header.writeUInt32BE(1, 0);
header.writeUInt32BE(1, 4);
header.set([8, 2, 0, 0, 0], 8);
const malformedPng = Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
pngChunk("IHDR", header),
pngChunk("IDAT", Buffer.from("bad")),
pngChunk("IEND", Buffer.alloc(0)),
]);
const malformedArtifact = createWebScreenshotArtifact(malformedPng);
const malformed = await client.callTool({
name: "compare_web_screenshots",
arguments: {
before: malformedArtifact,
after: malformedArtifact,
},
});
expect(parseMcpToolError(malformed)).toMatchObject({
error: {
code: "invalid_request",
category: "invalid_input",
details: {
operation: "compare_web_screenshots",
issues: [{ path: [], reason: "invalid_format" }],
},
},
});
const grayscaleHeader = Buffer.alloc(13);
grayscaleHeader.writeUInt32BE(1, 0);
grayscaleHeader.writeUInt32BE(1, 4);
grayscaleHeader.set([8, 0, 0, 0, 0], 8);
const unsupportedPng = Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
pngChunk("IHDR", grayscaleHeader),
pngChunk("IDAT", deflateSync(Buffer.from([0, 30]))),
pngChunk("IEND", Buffer.alloc(0)),
]);
const unsupported = createWebScreenshotArtifact(unsupportedPng);
const rejectedFormat = await client.callTool({
name: "compare_web_screenshots",
arguments: { before: unsupported, after: unsupported },
});
expect(parseMcpToolError(rejectedFormat)).toMatchObject({
error: { code: "unsupported_target", category: "unsupported_target" },
});
};
it("delivers the source-map response URL through authenticated MCP Evidence", async () => {
const terminalPath = "/maps/v1/app.js.map?revision=2&token=source-value";
const browser = await startFakeCdpBrowser({
sourceMapRedirect: terminalPath,
sourceMapBody: JSON.stringify({
version: 3,
names: [],
sources: ["../src/original.js"],
sourcesContent: ["export const value = 1;"],
mappings: "AAAA",
}),
});
browsers.push(browser);
const connected = await connectBrowser();
const result = await connected.client.callTool({
name: "analyze_web_bundle",
arguments: {
cdp_endpoint: browser.endpoint,
target_id: "allowed-page",
allowed_origins: [browser.allowedOrigin],
observation_ms: 0,
fetch_source_maps: true,
},
});
expect(result.isError).not.toBe(true);
const evidence = parseEvidence(result.structuredContent);
const expectedResult = {
observations: {
source_maps: {
status: "included",
items: [
{
declared_url: `${browser.allowedOrigin}/app.js.map?token=map-secret`,
effective_url: `${browser.allowedOrigin}${terminalPath}`,
original_sources: [
{ source: `${browser.allowedOrigin}/maps/src/original.js` },
],
},
],
},
},
};
expect(evidence.normalized_result).toMatchObject(expectedResult);
expect(result.content).toHaveLength(1);
expect(result.content[0]).toMatchObject({
type: "text",
text: JSON.stringify(evidence),
});
const cliEvidence = parseEvidence(
await runCliJson([
"analyze-web-bundle",
browser.endpoint,
"allowed-page",
"--allowed-origins",
browser.allowedOrigin,
"--observation-ms",
"0",
"--fetch-source-maps",
"--json",
]),
);
expect(cliEvidence.normalized_result).toMatchObject(expectedResult);
const mapRequests = browser.httpRequests.filter(({ url }) =>
url.includes(".map"),
);
expect(mapRequests.map(({ url }) => url)).toEqual([
"/app.js.map?token=map-secret",
terminalPath,
"/app.js.map?token=map-secret",
terminalPath,
]);
expect(
mapRequests.every(
({ authorization, cookie, referer }) =>
authorization === undefined &&
cookie === undefined &&
referer === undefined,
),
).toBe(true);
});
it("does not attach to a target outside the request's allowed origin scope", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
@@ -286,6 +449,43 @@ it("does not attach to a target outside the request's allowed origin scope", asy
expect(browser.commands).toHaveLength(0);
});
it("projects legal oversized PNG dimensions as a memory constraint", async () => {
const header = Buffer.alloc(13);
header.writeUInt32BE(0x7fffffff, 0);
header.writeUInt32BE(1, 4);
header.set([8, 6, 0, 0, 0], 8);
const artifact = createWebScreenshotArtifact(
Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
pngChunk("IHDR", header),
pngChunk("IDAT", deflateSync(Buffer.from([0]))),
pngChunk("IEND", Buffer.alloc(0)),
]),
);
const connected = await connectBrowser();
const result = await connected.client.callTool({
name: "compare_web_screenshots",
arguments: { before: artifact, after: artifact },
});
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "resource_constraint",
category: "resource_constraint",
details: {
operation: "compare_web_screenshots",
resource: "memory",
reported_limits: {
maximum_working_memory_bytes: 256 * 1024 * 1024,
estimated_working_memory_bytes: "34359738499",
before_dimensions: { width: 0x7fffffff, height: 1 },
after_dimensions: { width: 0x7fffffff, height: 1 },
},
},
},
});
});
const connectBrowser = async () => {
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
@@ -0,0 +1,167 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished, vi } from "vitest";
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import {
createEvidenceBundle,
serializeEvidenceBundle,
} from "../../../src/domain/evidenceBundle.js";
import { createServer } from "../../../src/server/createServer.js";
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { holdFirstFileRead } from "../../support/holdFirstFileRead.js";
it("leaves the session unchanged after bundle comparison cancellation and permits a retry", async () => {
const root = await createTestTempDirectory("rea-mcp-compare-cancel-");
const leftPath = join(root, "left.json");
const rightPath = join(root, "right.json");
const provider = { id: "fixture", name: "Fixture", version: "1" };
const left = createEvidence(undefined, provider, {
operation: "observation",
parameters: { side: "left" },
result: { side: "left" },
});
const right = createEvidence(undefined, provider, {
operation: "observation",
parameters: { side: "right" },
result: { side: "right" },
});
const leftContents =
" ".repeat(8 * 1024 * 1024) +
serializeEvidenceBundle(createEvidenceBundle([left]));
await Promise.all([
// Just over the native-parse budget, without a large JSON tree.
writeFile(leftPath, leftContents),
writeFile(
rightPath,
serializeEvidenceBundle(createEvidenceBundle([right])),
),
]);
const session = createTestBinarySession(() => {
throw new Error("Bundle comparison must not start a binary provider");
});
const existing = createEvidence(undefined, provider, {
operation: "existing_observation",
parameters: {},
result: { retained: true },
});
const recorded = session.recordEvidence(existing);
if (!recorded.ok) throw recorded.error;
const before = session.exportEvidenceBundle();
const server = createServer({ kind: "session", session });
const client = new Client({
name: "bundle-comparison-cancellation",
version: "1",
});
const controller = new AbortController();
let releaseRead: (() => void) | undefined;
onTestFinished(async () => {
controller.abort();
releaseRead?.();
vi.restoreAllMocks();
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const reader = await holdFirstFileRead(leftPath);
releaseRead = reader.release;
let resolveDispatched: (() => void) | undefined;
const dispatched = new Promise<void>((resolve) => {
resolveDispatched = resolve;
});
const send = clientTransport.send.bind(clientTransport);
vi.spyOn(clientTransport, "send").mockImplementation(
async (message, ...args) => {
await send(message, ...args);
if ("method" in message && message.method === "tools/call")
resolveDispatched?.();
},
);
let resolveCompleted: (() => void) | undefined;
const completed = new Promise<void>((resolve) => {
resolveCompleted = resolve;
});
let settledResult: unknown;
const deliver = ToolResultDelivery.prototype.toCallToolResult;
vi.spyOn(ToolResultDelivery.prototype, "toCallToolResult").mockImplementation(
function (this: ToolResultDelivery, result, contract) {
const reply = deliver.call(this, result, contract);
if (contract.name === "compare_bundles") {
settledResult = result;
resolveCompleted?.();
}
return reply;
},
);
const args = {
left_bundle_path: leftPath,
right_bundle_path: rightPath,
record_pairs: [
{
left_evidence_id: left.evidence_id,
right_evidence_id: right.evidence_id,
},
],
};
const cancellation = client
.callTool(
{ name: "compare_bundles", arguments: args },
{ signal: controller.signal },
)
.then(
() => "completed",
(error: unknown) => error,
);
await dispatched;
await reader.firstRead;
await client.ping();
controller.abort(new Error("SDK bundle comparison cancellation"));
reader.release();
expect(await cancellation).toMatchObject({
message: expect.stringContaining("SDK bundle comparison cancellation"),
});
// Wait for the handler's delivered Result as well as the client's rejection.
await completed;
expect(settledResult).toMatchObject({
ok: false,
error: expect.any(AnalysisCancelledError),
});
expect(reader.readCount).toBe(1);
expect(reader.totalReadBytes).toBeLessThan(leftContents.length);
expect(session.exportEvidenceBundle()).toEqual(before);
await client.ping();
const retry = await client.callTool({
name: "compare_bundles",
arguments: args,
});
expect(retry.isError, JSON.stringify(retry)).not.toBe(true);
expect(retry.structuredContent).toMatchObject({
normalized_result: { status: "changed" },
});
const after = session.exportEvidenceBundle();
expect(after.unknowns).toEqual(before.unknowns);
expect(after.records).toEqual(
expect.arrayContaining([
...before.records,
left,
right,
expect.objectContaining({
operation: "compare_bundles",
evidence_links: [left.evidence_id, right.evidence_id],
}),
]),
);
});
@@ -134,7 +134,9 @@ describe("bundle comparison MCP integration", () => {
expect(result.isError).toBe(true);
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "evidence_integrity_mismatch",
code: "invalid_request",
category: "invalid_input",
details: { path: recordPath },
message: expect.stringContaining(
`this JSON is one Evidence record (${record.evidence_id})`,
),
+18 -1
View File
@@ -7,11 +7,25 @@ import {
import { describe, expect, it } from "vitest";
import { createServer } from "../../../src/server/createServer.js";
import {
TOOL_CONTRACTS,
toolContract,
} from "../../../src/contracts/toolContracts.js";
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import {
createCacheProvider,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
const assertCompleteToolAvailability = (structuredContent: unknown): void => {
const status =
toolContract("binary_session").outputSchema.parse(structuredContent);
const availability = expandToolAvailability(status.result.tool_availability);
expect(availability.map(({ name }) => name).sort()).toEqual(
TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
};
describe("per-request client capability reporting", () => {
it.each([
[{ elicitation: {} }, true, false],
@@ -39,6 +53,7 @@ describe("per-request client capability reporting", () => {
[CLIENT_CAPABILITIES_META_KEY]: capabilities,
},
});
assertCompleteToolAvailability(status.structuredContent);
expect(status.structuredContent).toMatchObject({
result: {
client_features: { elicitation_form: form, elicitation_url: url },
@@ -71,13 +86,15 @@ describe("initialize-scoped client metadata", () => {
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
return (
const result = (
await client.callTool({
name: "binary_session",
arguments: {},
...(meta === undefined ? {} : { _meta: meta }),
})
).structuredContent;
assertCompleteToolAvailability(result);
return result;
} finally {
await Promise.allSettled([
client.close(),
@@ -4,7 +4,6 @@ import { Ajv2020 } from "ajv/dist/2020.js";
import { describe, expect, it } from "vitest";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { compactAdvertisedInputSchema } from "../../../src/contracts/compactInputSchema.js";
import {
COMPACT_INPUT_SCHEMA_BUDGET_BYTES,
parseMcpInputSchemaProfile,
@@ -121,29 +120,6 @@ describe("MCP compact input schema profile", () => {
}
});
it("reduces at most the structurally oversized tools", async () => {
const full = fullServer();
registerCatalog(full);
const tools = await listToolsThroughTransport(full);
const reduced: string[] = [];
for (const tool of tools) {
const { presentation } = compactAdvertisedInputSchema(
tool.inputSchema,
COMPACT_INPUT_SCHEMA_BUDGET_BYTES,
);
if (presentation === "reduced") reduced.push(tool.name);
}
expect(reduced.sort()).toEqual([
"build_reconstruction_obligation_ledger",
"capture_browser_scenario",
"compare_application_versions",
"compare_web_captures",
"evaluate_reconstruction_coverage",
"project_managed_application_graph",
]);
expect(tools.length).toBe(TOOL_CONTRACTS.length);
});
it("retains parameter types and avoids client-side reference expansion", async () => {
const server = compactServer();
registerCatalog(server);
@@ -8,11 +8,13 @@ import { z } from "zod";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import {
CPU,
FILE_TYPE,
LC,
buildVersionCommand,
dylibCommand,
dyldEnvironmentCommand,
fatImage,
machoImage,
rpathCommand,
} from "../../../src/artifacts/apple/MachoImage.fixture.js";
@@ -112,6 +114,44 @@ it("traces dylib resolution for an opened app bundle and rejects a changed targe
});
});
it("traces architecture slices from a universal Mach-O target", async () => {
const root = await createTestTempDirectory("rea-dylib-universal-");
const executable = join(root, "Universal");
const cpu = process.arch === "arm64" ? CPU.arm64 : CPU.x86_64;
const architecture = process.arch === "arm64" ? "arm64" : "x86_64";
await writeFile(
executable,
fatImage([
{
cpu,
bytes: machoImage({
cpu,
commands: [buildVersionCommand(1)],
}),
},
]),
);
await withClient(async (client) => {
const opened = await client.callTool({
name: "open_binary",
arguments: { path: executable },
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const called = await client.callTool({
name: "trace_dylib_resolution",
arguments: { architecture },
});
expect(called.isError, JSON.stringify(called.structuredContent)).not.toBe(
true,
);
const trace = dylibResolutionResultSchema.parse(
structuredResult(called.structuredContent),
);
expect(trace.roots).toEqual([{ image: "Universal", architecture }]);
});
});
it("rejects targets that are not Mach-O", async () => {
const directory = await createTestTempDirectory("rea-dylib-mcp-plist-");
const path = join(directory, "Info.plist");
+60 -4
View File
@@ -5,7 +5,7 @@ import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, expect, it } from "vitest";
import { afterEach, expect, it, vi } from "vitest";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -13,7 +13,7 @@ import { createStrippedAsarAddon } from "../../fixtures/strippedAsarAddon.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import type { ElectronActiveObservationPort } from "../../../src/application/javascript/ElectronActiveObservationPort.js";
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
import { CdpElectronProvider } from "../../../src/browser/CdpElectronProvider.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
@@ -24,11 +24,64 @@ import {
import { writeElectronBoundaryFixture } from "../../fixtures/electronBoundaryApplication.js";
import { createElectronActiveObservationFixtureResult } from "../../../src/domain/javascript/electronActiveObservation.fixture.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js";
const browsers: FakeCdpBrowser[] = [];
const resources: Array<{ close(): Promise<unknown> }> = [];
const temporary: string[] = [];
it("retains failed JavaScript inventory cleanup through server shutdown retries", async () => {
const { archive } = await createStrippedAsarAddon();
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer({ kind: "session", session });
const client = new Client({ name: "javascript-cleanup-owner", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const originalClose = AsarArtifactReader.prototype.close;
const owners = new Set<AsarArtifactReader>();
let blocked = true;
const close = vi
.spyOn(AsarArtifactReader.prototype, "close")
.mockImplementation(function (this: AsarArtifactReader) {
owners.add(this);
if (blocked) return Promise.reject(new Error("snapshot cleanup blocked"));
return originalClose.call(this);
});
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const response = await client.callTool({
name: "analyze_javascript_application",
arguments: {
input_path: archive,
integrity_policy: "record-and-continue",
},
});
expect(parseMcpToolError(response)).toMatchObject({
error: {
code: "cleanup_incomplete",
details: {
resources: [expect.stringContaining(archive)],
partial_observation: { kind: "artifact-inventory" },
},
},
});
expect(owners.size).toBe(1);
await expect(server.close()).rejects.toThrow();
blocked = false;
await server.close();
expect(owners.size).toBe(1);
expect(close.mock.calls.length).toBeGreaterThanOrEqual(3);
} finally {
blocked = false;
await Promise.all([client.close(), server.close(), session.close()]);
close.mockRestore();
}
});
afterEach(async () => {
await Promise.all(resources.splice(0).map(async (item) => item.close()));
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
@@ -362,8 +415,11 @@ it("exposes the target-free static JavaScript application workflow", async () =>
);
expect(analyzed.isError).not.toBe(true);
expect(progress[0]).toBe(0);
expect(progress.at(-1)).toBe(1);
expect(progress[0]).toBe(1);
expect(progress.at(-1)).toBeGreaterThan(1);
progress.forEach((value, index) => {
expect(value).toBeGreaterThan(progress[index - 1] ?? 0);
});
const projected = z
.object({
evidence_id: z.string(),
@@ -7,7 +7,7 @@ import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../../../src/contracts/managed/
import { ENHANCED_TOOL_CONTRACTS } from "../../../src/contracts/enhancedToolContracts.js";
import { SESSION_TOOL_CONTRACTS } from "../../../src/contracts/sessionToolContracts.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import {} from "../../../src/domain/jsonValue.js";
import type {} from "../../../src/domain/jsonValue.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
@@ -189,7 +189,7 @@ const fixturePort = (): AnalysisOperationPort => ({
case "analyze_function":
return Promise.resolve(targetObservation(functionDossier));
default:
return Promise.resolve(ok(null));
throw new Error(`Unexpected analysis operation: ${name}`);
}
},
});
@@ -288,11 +288,43 @@ describe("enhanced MCP tools", () => {
failed: 0,
});
expect(results[3]).toEqual({
"0": [{ address: "0x1", status: "ok", calls: ["0x2", "0x3"] }],
"1": [
{ address: "0x2", status: "ok", calls: ["0x1"] },
{ address: "0x3", status: "ok", calls: [] },
],
graph: {
"0": [
{
address: "0x1",
status: "ok",
calls: ["0x2", "0x3"],
limitations: ["Provider did not report relationship coverage."],
relationship_coverage: {
status: "unknown",
reason: "Provider did not report relationship coverage.",
},
},
],
"1": [
{
address: "0x2",
status: "ok",
calls: ["0x1"],
limitations: ["Provider did not report relationship coverage."],
relationship_coverage: {
status: "unknown",
reason: "Provider did not report relationship coverage.",
},
},
{
address: "0x3",
status: "ok",
calls: [],
limitations: ["Provider did not report relationship coverage."],
relationship_coverage: {
status: "unknown",
reason: "Provider did not report relationship coverage.",
},
},
],
},
limitations: [],
});
expect(results[4]).toMatchObject({
total: 1,
@@ -354,7 +386,7 @@ describe("enhanced MCP tools", () => {
{ address: "0x1", depth: 0 },
{ address: "0x2", depth: 1 },
],
truncated: false,
truncated: true,
});
expect(results[11]).toMatchObject({
start: "missing-selector",
@@ -37,17 +37,20 @@ describe("enhanced MCP tools", () => {
expect(graph).toMatchObject({
ok: true,
value: {
"0": [
{
address: "0x1",
status: "error",
error: {
category: "execution_failure",
message:
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
graph: {
"0": [
{
address: "0x1",
status: "error",
error: {
category: "execution_failure",
message:
"Analysis returned an unreadable result. Run `rea doctor` and review the reported details; repeating the unchanged request is not expected to succeed.",
},
},
},
],
],
},
limitations: [],
},
});
expect(unresolved).toEqual({
@@ -130,7 +130,7 @@ describe("enhanced MCP tools", () => {
);
}
default:
return Promise.resolve(ok(null));
throw new Error(`Unexpected analysis operation: ${name}`);
}
},
});
@@ -174,26 +174,29 @@ describe("enhanced MCP tools", () => {
it("rejects a segment with omitted coordinates instead of reporting zero length", async () => {
const client = await connect({
execute: (name) =>
Promise.resolve(
name === "list_segments"
? ok([
{
name: "__TEXT",
end: "0x2000",
readable: null,
writable: null,
executable: null,
},
])
: ok(name === "current_document" ? "fixture" : []),
),
execute: (name) => {
if (name === "list_segments")
return Promise.resolve(
ok([
{
name: "__TEXT",
end: "0x2000",
readable: null,
writable: null,
executable: null,
},
]),
);
if (name === "current_document") return Promise.resolve(ok("fixture"));
if (name === "list_procedures" || name === "list_strings")
return Promise.resolve(ok([]));
throw new Error(`Unexpected analysis operation: ${name}`);
},
});
const result = await client.callTool({
name: "binary_overview",
arguments: {},
});
expect(result.isError).toBe(true);
expect(result.content).toContainEqual({
type: "text",
@@ -225,8 +228,11 @@ const overviewPort = (
},
]),
);
default:
case "list_procedures":
case "list_strings":
return Promise.resolve(ok([]));
default:
throw new Error(`Unexpected analysis operation: ${name}`);
}
},
});
@@ -1,19 +1,304 @@
import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisCancelledError,
AnalysisOutputError,
} from "../../../src/domain/analysisErrorCore.js";
import { err } from "../../../src/domain/result.js";
import type { RelationshipCoverage } from "../../../src/domain/relationshipCoverage.js";
import { err, ok as resultOk } from "../../../src/domain/result.js";
import { closeEnhancedToolResources, connect } from "./enhancedToolsHarness.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
afterEach(closeEnhancedToolResources);
const relationshipExecution = (
result: unknown,
limitations: readonly string[] = [],
relationshipCoverage?: RelationshipCoverage,
) =>
resultOk(
createAnalysisExecution(
result,
{ id: "fixture", name: "Fixture analysis provider", version: "1" },
{
limitations,
...(relationshipCoverage === undefined ? {} : { relationshipCoverage }),
},
),
);
describe("enhanced MCP tools", () => {
it("preserves per-node relationship limitations and keeps observed edges", async () => {
const limitation = "ARM64 call targets are only partially resolved.";
const client = await connect({
execute: async (name, arguments_) => {
if (name === "procedure_address")
return relationshipExecution(String(arguments_.procedure));
if (name !== "procedure_callees")
throw new Error(`Unexpected operation: ${name}`);
return relationshipExecution(
arguments_.procedure === "0x1" ? ["0x2"] : [],
arguments_.procedure === "0x1" ? [limitation] : [],
arguments_.procedure === "0x1"
? { status: "partial", limitations: [limitation] }
: { status: "complete" },
);
},
});
const graph = await client.callTool({
name: "get_call_graph",
arguments: { address: "0x1", direction: "forward" },
});
expect(graph.isError).not.toBe(true);
expect(graph.structuredContent).toMatchObject({
normalized_result: {
graph: {
"0": [
{
address: "0x1",
status: "ok",
calls: ["0x2"],
limitations: [limitation],
relationship_coverage: {
status: "partial",
limitations: [limitation],
},
},
],
},
limitations: [limitation],
},
});
const trace = await client.callTool({
name: "trace_call_path",
arguments: { start: "0x1", goal: "0x2" },
});
expect(trace.isError).not.toBe(true);
expect(trace.structuredContent).toMatchObject({
normalized_result: {
goal_status: "reached",
traversal_path: ["0x1", "0x2"],
edges: [{ source_address: "0x1", target_address: "0x2" }],
truncated: true,
residual_unknowns: [
`Call relationships for 0x1 are limited: ${limitation}`,
],
},
});
});
it("keeps generic provider caveats visible without truncating complete relationships", async () => {
const caveat = "Decompiler output may omit indirect calls.";
const client = await connect({
execute: async (name, arguments_) => {
if (name === "procedure_address")
return relationshipExecution(String(arguments_.procedure));
if (name !== "procedure_callees")
throw new Error(`Unexpected operation: ${name}`);
return relationshipExecution(
arguments_.procedure === "0x1" ? ["0x2"] : [],
[caveat],
{ status: "complete" },
);
},
});
const graph = await client.callTool({
name: "get_call_graph",
arguments: { address: "0x1", direction: "forward" },
});
expect(graph.structuredContent).toMatchObject({
normalized_result: {
graph: {
"0": [
{ status: "ok", relationship_coverage: { status: "complete" } },
],
"1": [
{ status: "ok", relationship_coverage: { status: "complete" } },
],
},
limitations: [caveat],
},
});
expect(JSON.stringify(graph.structuredContent)?.split(caveat)).toHaveLength(
2,
);
const trace = await client.callTool({
name: "trace_call_path",
arguments: { start: "0x1", goal: "0x2" },
});
expect(trace.structuredContent).toMatchObject({
normalized_result: {
truncated: false,
residual_unknowns: [],
limitations: expect.arrayContaining([expect.stringContaining(caveat)]),
relationship_coverage: { "0x1": { status: "complete" } },
},
});
});
it("keeps unclassified legacy caveats on nodes with unknown coverage", async () => {
const caveat = "This legacy provider does not classify call limitations.";
const client = await connect({
execute: async (name, arguments_) => {
if (name === "procedure_address")
return relationshipExecution(String(arguments_.procedure));
if (name !== "procedure_callees")
throw new Error(`Unexpected operation: ${name}`);
return relationshipExecution([], [caveat]);
},
});
const graph = await client.callTool({
name: "get_call_graph",
arguments: { address: "0x1", direction: "forward" },
});
expect(graph.structuredContent).toMatchObject({
normalized_result: {
graph: {
"0": [
{
status: "ok",
relationship_coverage: { status: "unknown" },
limitations: [
"Provider did not report relationship coverage.",
caveat,
],
},
],
},
limitations: [caveat],
},
});
});
});
describe("trace_call_path MCP outcome semantics", () => {
it("reports an unreachable goal as unknown when relationship coverage is partial", async () => {
const client = await connect({
execute: async (name, arguments_) => {
if (name === "procedure_address")
return relationshipExecution(String(arguments_.procedure));
if (name !== "procedure_callees")
throw new Error(`Unexpected operation: ${name}`);
return relationshipExecution([], [], {
status: "partial",
limitations: ["one or more callees may be missing"],
});
},
});
const trace = await client.callTool({
name: "trace_call_path",
arguments: { start: "0x1", goal: "0x2" },
});
expect(trace.isError).not.toBe(true);
expect(trace.structuredContent).toMatchObject({
normalized_result: {
goal_status: "unknown",
truncated: true,
relationship_coverage: { "0x1": { status: "partial" } },
},
});
});
it("reports an unreachable goal as unknown when an expansion fails", async () => {
const client = await connect({
execute: async (name, arguments_) => {
if (name === "procedure_address")
return relationshipExecution(String(arguments_.procedure));
if (name !== "procedure_callees")
throw new Error(`Unexpected operation: ${name}`);
return err(
new AnalysisCapabilityUnavailableError(
"fixture",
name,
"relationship read unavailable",
),
);
},
});
const trace = await client.callTool({
name: "trace_call_path",
arguments: { start: "0x1", goal: "0x2" },
});
expect(trace.isError).not.toBe(true);
expect(trace.structuredContent).toMatchObject({
normalized_result: {
goal_status: "unknown",
failures: [{ address: "0x1" }],
truncated: true,
},
});
});
it("reports an unreachable goal as absent after complete traversal", async () => {
const client = await connect({
execute: async (name, arguments_) => {
if (name === "procedure_address")
return relationshipExecution(String(arguments_.procedure));
if (name !== "procedure_callees")
throw new Error(`Unexpected operation: ${name}`);
return relationshipExecution([], [], { status: "complete" });
},
});
const trace = await client.callTool({
name: "trace_call_path",
arguments: { start: "0x1", goal: "0x2" },
});
expect(trace.isError).not.toBe(true);
expect(trace.structuredContent).toMatchObject({
normalized_result: {
goal_status: "not_reached",
truncated: false,
residual_unknowns: [],
},
});
});
it("propagates cancellation during expansion without visiting another frontier", async () => {
const controller = new AbortController();
const calls: string[] = [];
const client = await connect({
execute: async (name, arguments_, options) => {
calls.push(name);
if (name === "procedure_address")
return relationshipExecution(String(arguments_.procedure));
if (name !== "procedure_callees")
throw new Error(`Unexpected operation: ${name}`);
controller.abort();
if (options?.signal?.aborted !== true)
throw new Error("provider request was not cancelled");
return err(new AnalysisCancelledError(name));
},
});
await expect(
client.callTool(
{
name: "trace_call_path",
arguments: { start: "0x1", goal: "0x3" },
},
{ signal: controller.signal },
),
).rejects.toThrow();
expect(calls).toEqual([
"procedure_address",
"procedure_address",
"procedure_callees",
]);
});
});
describe("enhanced MCP batches", () => {
it("returns every batch item in caller order with its own result", async () => {
const addresses = Array.from(
{ length: 37 },
@@ -96,11 +381,11 @@ describe("enhanced MCP tools", () => {
category: "execution_failure",
details: { operation: "decompile", reason: "failed" },
message:
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
"Analysis returned an unreadable result. Run `rea doctor` and review the reported details; repeating the unchanged request is not expected to succeed.",
retryable: false,
remediation: {
action:
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
"Analysis returned an unreadable result. Run `rea doctor` and review the reported details; repeating the unchanged request is not expected to succeed.",
},
},
},
@@ -0,0 +1,258 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished, vi } from "vitest";
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { createServer } from "../../../src/server/createServer.js";
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("keeps the complete session unchanged after SDK import cancellation and permits a retry", async () => {
const root = await createTestTempDirectory("rea-mcp-import-cancel-");
const path = join(root, "bundle.json");
const session = createTestBinarySession(() => {
throw new Error("Evidence import must not start a binary provider");
});
const provider = { id: "fixture", name: "Fixture", version: "1" };
const existing = createEvidence(undefined, provider, {
operation: "existing_observation",
parameters: {},
result: { retained: true },
});
const recorded = session.recordEvidence(existing);
if (!recorded.ok) throw recorded.error;
const imported = createEvidence(undefined, provider, {
operation: "imported_observation",
parameters: {},
result: { retained: "雪😀" },
});
const bundle = createEvidenceBundle([imported]);
// Valid whitespace crosses the streaming threshold without a large JSON tree.
await writeFile(path, " ".repeat(9 * 1024 * 1024) + JSON.stringify(bundle));
const server = createServer({ kind: "session", session });
const client = new Client({
name: "evidence-import-cancellation",
version: "1",
});
const controller = new AbortController();
onTestFinished(async () => {
controller.abort();
vi.restoreAllMocks();
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const unknown = await client.callTool({
name: "record_unknown",
arguments: {
question: "Which boundary remains unknown?",
domain: "fixture",
severity: "medium",
required_authority: null,
required_confidence: "derived",
required_environment: null,
recommended_probes: [],
relationships: [],
},
});
expect(unknown.isError, JSON.stringify(unknown)).not.toBe(true);
const before = session.exportEvidenceBundle();
let resolveDispatched: (() => void) | undefined;
const dispatched = new Promise<void>((resolve) => {
resolveDispatched = resolve;
});
const send = clientTransport.send.bind(clientTransport);
vi.spyOn(clientTransport, "send").mockImplementation(
async (message, ...args) => {
await send(message, ...args);
if ("method" in message && message.method === "tools/call")
resolveDispatched?.();
},
);
let resolveCompleted: (() => void) | undefined;
const completed = new Promise<void>((resolve) => {
resolveCompleted = resolve;
});
let settledResult: unknown;
const deliver = ToolResultDelivery.prototype.toCallToolResult;
vi.spyOn(ToolResultDelivery.prototype, "toCallToolResult").mockImplementation(
function (this: ToolResultDelivery, result, contract) {
const reply = deliver.call(this, result, contract);
if (contract.name === "import_evidence_bundle") {
settledResult = result;
resolveCompleted?.();
}
return reply;
},
);
const cancellation = client
.callTool(
{ name: "import_evidence_bundle", arguments: { path } },
{ signal: controller.signal },
)
.then(
() => "completed",
(error: unknown) => error,
);
await dispatched;
// The real SDK ping completes while the dispatched file reader awaits I/O.
await client.ping();
controller.abort(new Error("SDK import cancellation verification"));
expect(await cancellation).toMatchObject({
message: expect.stringContaining("SDK import cancellation verification"),
});
// Observe handler settlement, not just the client's local rejection.
await completed;
expect(session.exportEvidenceBundle()).toEqual(before);
expect(settledResult).toMatchObject({
ok: false,
error: expect.any(AnalysisCancelledError),
});
await client.ping();
const retry = await client.callTool({
name: "import_evidence_bundle",
arguments: { path },
});
expect(retry.isError, JSON.stringify(retry)).not.toBe(true);
expect(retry.structuredContent).toMatchObject({
result: {
imported: 1,
unknowns_added: 0,
total: before.records.length + 1,
},
});
const after = session.exportEvidenceBundle();
expect(after.unknowns).toEqual(before.unknowns);
expect(after.records).toHaveLength(before.records.length + 1);
expect(after.records).toEqual(
expect.arrayContaining([...before.records, imported]),
);
await client.ping();
});
it("retains a failed import close in the server scope through SDK error projection", async () => {
const root = await createTestTempDirectory("rea-mcp-import-close-");
const path = join(root, "bundle.json");
const session = createTestBinarySession(() => {
throw new Error("Evidence import must not start a binary provider");
});
const provider = { id: "fixture", name: "Fixture", version: "1" };
const existing = createEvidence(undefined, provider, {
operation: "existing_observation",
parameters: {},
result: { retained: true },
});
const imported = createEvidence(undefined, provider, {
operation: "imported_observation",
parameters: {},
result: { retained: "close failure" },
});
const recorded = session.recordEvidence(existing);
if (!recorded.ok) throw recorded.error;
await writeFile(path, JSON.stringify(createEvidenceBundle([imported])));
let allowClose = false;
let retainedOwner: OwnedFileHandle | undefined;
const originalClose = OwnedFileHandle.prototype.close;
const close = vi
.spyOn(OwnedFileHandle.prototype, "close")
.mockImplementation(async function (this: OwnedFileHandle) {
retainedOwner ??= this;
if (!allowClose) throw new Error("persistent file close failure");
return originalClose.call(this);
});
const server = createServer({ kind: "session", session });
const client = new Client({
name: "evidence-import-close-failure",
version: "1",
});
onTestFinished(async () => {
allowClose = true;
close.mockRestore();
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const before = session.exportEvidenceBundle();
const result = await client.callTool({
name: "import_evidence_bundle",
arguments: { path },
});
expect(result.isError).toBe(true);
expect(session.exportEvidenceBundle()).toEqual(before);
expect(retainedOwner).toBeDefined();
expect(retainedOwner?.handle.fd).toBeGreaterThanOrEqual(0);
await client.close();
await expect(server.close()).rejects.toThrow("REA session cleanup failed");
expect(retainedOwner?.handle.fd).toBeGreaterThanOrEqual(0);
allowClose = true;
close.mockRestore();
await server.close();
expect(retainedOwner?.handle.fd).toBe(-1);
await session.close();
});
it("retries a transient import close failure before admitting the bundle", async () => {
const root = await createTestTempDirectory("rea-mcp-import-close-retry-");
const path = join(root, "bundle.json");
const session = createTestBinarySession(() => {
throw new Error("Evidence import must not start a binary provider");
});
const imported = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: "imported_observation",
parameters: {},
result: { retained: "retry succeeded" },
},
);
await writeFile(path, JSON.stringify(createEvidenceBundle([imported])));
const originalClose = OwnedFileHandle.prototype.close;
const close = vi
.spyOn(OwnedFileHandle.prototype, "close")
.mockImplementationOnce(async () => {
throw new Error("one transient file close failure");
});
const server = createServer({ kind: "session", session });
const client = new Client({
name: "evidence-import-close-retry",
version: "1",
});
onTestFinished(async () => {
close.mockRestore();
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "import_evidence_bundle",
arguments: { path },
});
close.mockRestore();
expect(result.isError).not.toBe(true);
expect(session.exportEvidenceBundle().records).toContainEqual(imported);
await client.ping();
});
+183
View File
@@ -0,0 +1,183 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it, onTestFinished } from "vitest";
import type { FlutterBuildAnalysisPort } from "../../../src/application/flutter/FlutterBuildAnalysisPort.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { assertAdvertisedMcpContracts } from "./mcpContractHarness.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
const identity = {
id: "flutter",
name: "Flutter build identification",
version: null,
};
const SNAPSHOT_HASH = "65817c30a78bb44c3dc3771876b6010a";
/** One shared target identity for both fake operation results. */
const target = {
path: "/targets/gallery.apk",
bytes: 117817550,
sha256: "a".repeat(64),
};
const inspectExecution = () =>
createAnalysisExecution(
{
target,
abi: "arm64-v8a",
libapp: {
coverage: "complete",
bytes: 24691632,
sha256: "b".repeat(64),
snapshot_hash: SNAPSHOT_HASH,
snapshot_hash_candidates: [SNAPSHOT_HASH],
snapshot_hash_sources: 2,
sections: [
{
name: "_kDartVmSnapshotData",
offset: 4096,
size: 52,
magic_valid: true,
kind: 3,
header_length: 48,
},
{
name: "_kDartIsolateSnapshotData",
offset: 8192,
size: 1536,
magic_valid: true,
kind: 3,
header_length: 48,
},
],
},
string_pool: {
coverage: "complete",
package_uris: [
"package:adaptive_breakpoints/src/adaptive_breakpoints.dart",
],
package_uri_count_at_least: 1,
dart_uris: ["dart:_http"],
dart_uri_count_at_least: 1,
class_like_tokens: ["AdaptiveBreakpoint"],
class_like_token_count_at_least: 1,
printable_run_count: 4,
},
coverage: "complete",
},
identity,
);
const identifyExecution = () =>
createAnalysisExecution(
{
target,
flutter_detected: true,
abis: [
{
abi: "arm64-v8a",
libapp: {
present: true,
bytes: 24691632,
sha256: "b".repeat(64),
elf_header_valid: true,
snapshot_hash_sources: 2,
snapshot_hash_candidates: [SNAPSHOT_HASH],
snapshot_hash: SNAPSHOT_HASH,
},
libflutter: {
present: true,
bytes: 9073432,
sha256: "c".repeat(64),
build_id: "e8d907ef7c175ec4313f47111019adc9588c5f61",
build_id_candidates: ["e8d907ef7c175ec4313f47111019adc9588c5f61"],
dart_version: null,
dart_version_capped: false,
toolchain_lines: ["Android (5900059) clang version 9.0.8"],
toolchain_capped: false,
},
},
],
coverage: "complete",
},
identity,
);
/** A recording-free provider answering both Flutter operations inline. */
const fakeProvider = (): FlutterBuildAnalysisPort => ({
async inspectAvailability() {
return { status: "available", code: null, reason: null, diagnostics: {} };
},
async close() {},
async execute(request) {
return ok(
request.operation === "inspect_dart_aot"
? inspectExecution()
: identifyExecution(),
);
},
});
it("advertises an exact valid Flutter schema and records inline evidence through MCP", async () => {
const session = createTestBinarySession(() => {
throw new Error("deep provider must not start");
});
const server = createServer(
{ kind: "session", session },
{ flutterAnalysis: fakeProvider() },
);
onTestFinished(() => server.close());
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
const client = new Client({ name: "flutter-boundary", version: "0.0.0" });
onTestFinished(() => client.close());
await client.connect(clientTransport);
const { tools } = await client.listTools();
assertAdvertisedMcpContracts(
["identify_flutter_build", "inspect_dart_aot"],
tools,
);
const identified = await client.callTool({
name: "identify_flutter_build",
arguments: { path: "/targets/gallery.apk" },
});
expect(identified.isError).not.toBe(true);
const text = (identified.content as { readonly text?: string }[])
.map((part) => part.text ?? "")
.join("");
const evidence = parseEvidence(JSON.parse(text));
expect(evidence.normalized_result).toMatchObject({
flutter_detected: true,
abis: [
{
abi: "arm64-v8a",
libapp: { snapshot_hash: SNAPSHOT_HASH },
},
],
});
const inspected = await client.callTool({
name: "inspect_dart_aot",
arguments: { path: "/targets/gallery.apk", abi: "arm64-v8a" },
});
expect(inspected.isError).not.toBe(true);
const inspectedText = (inspected.content as { readonly text?: string }[])
.map((part) => part.text ?? "")
.join("");
const inspectedEvidence = parseEvidence(JSON.parse(inspectedText));
expect(inspectedEvidence.normalized_result).toMatchObject({
abi: "arm64-v8a",
libapp: {
snapshot_hash: SNAPSHOT_HASH,
snapshot_hash_candidates: [SNAPSHOT_HASH],
snapshot_hash_sources: 2,
},
});
});
+415
View File
@@ -0,0 +1,415 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import type { AnySchema } from "ajv";
import { expect, it, onTestFinished } from "vitest";
import type { FridaInstrumentationPort } from "../../../src/application/frida/FridaInstrumentationPort.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { FridaInstrumentationManager } from "../../../src/frida/FridaInstrumentationManager.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
const createFridaTestProvider = (
overrides: Partial<FridaInstrumentationPort> = {},
): FridaInstrumentationPort => ({
async listDevices() {
return {
ok: true,
value: {
devices: [
{ deviceId: "remote-device", name: "target", type: "remote" },
],
cleanupError: null,
},
};
},
async listProcesses() {
return {
ok: true,
value: { deviceId: "remote-device", processes: [], cleanupError: null },
};
},
async startSession(input) {
return {
ok: true,
value: {
sessionId: "00000000-0000-4000-8000-000000000001",
deviceId: "remote-device",
target: String(input.mode),
pid: 10,
mode: input.mode,
state: input.mode === "spawn" ? "paused" : "running",
},
};
},
async loadScript() {
return {
ok: true,
value: {
scriptId: "00000000-0000-4000-8000-000000000002",
sourceKind: "inline",
sourcePath: null,
sourceSha256: "a".repeat(64),
messages: [],
messagesTruncated: false,
},
};
},
async resumeSession() {
return { ok: true, value: null };
},
async unloadScript() {
return { ok: true, value: null };
},
status(sessionId) {
return {
sessionId,
deviceId: "remote-device",
target: "fixture",
pid: 10,
mode: "attach",
state: "running",
targetResumeObserved: false,
scripts: [],
messages: [],
messagesTruncated: false,
};
},
async closeSession() {
return { ok: true, value: { targetResumeObserved: false } };
},
async closeAll() {},
...overrides,
});
const expectFridaToolsAvailable = async (client: Client) => {
const inventory = await client.callTool({
name: "binary_session",
arguments: {},
});
const parsedInventory = toolContract("binary_session").outputSchema.safeParse(
inventory.structuredContent,
);
if (!parsedInventory.success)
throw new Error("Invalid binary session output");
const toolAvailability = expandToolAvailability(
parsedInventory.data.result.tool_availability,
);
expect(toolAvailability).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "list_frida_devices",
available: true,
reason: "available",
}),
expect.objectContaining({
name: "instrument_with_frida",
available: true,
reason: "available",
}),
]),
);
};
it("advertises Frida MCP schemas and keeps remote credentials out of results", async () => {
const session = createTestBinarySession(() => {
throw new Error("Binary provider must not start");
});
const server = createServer(
{ kind: "session", session },
{
fridaInstrumentation: createFridaTestProvider(),
},
);
const client = new Client({ name: "frida-contract", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const tools = (await client.listTools()).tools;
const advertised = tools.find((tool) => tool.name === "list_frida_devices");
if (
advertised?.inputSchema === undefined ||
advertised.outputSchema === undefined
)
throw new Error("Missing advertised Frida schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const response = await client.callTool({
name: "list_frida_devices",
arguments: {
remote: { address: "127.0.0.1:27042", token: "synthetic-secret-token" },
},
});
expect(response.isError).not.toBe(true);
expect(JSON.stringify(response.structuredContent)).not.toContain(
"synthetic-secret-token",
);
expect(ajv.validate(outputSchema, response.structuredContent)).toBe(true);
expect(toolContract("start_frida_session").effects.mutatesTarget).toBe(true);
const processes = await client.callTool({
name: "list_frida_processes",
arguments: { device_id: "remote-device" },
});
expect(processes.isError).not.toBe(true);
const started = await client.callTool({
name: "start_frida_session",
arguments: {
mode: "attach",
pid: 10,
remote: { address: "127.0.0.1:27042", token: "synthetic-secret-token" },
},
});
expect(started.isError).not.toBe(true);
expect(JSON.stringify(started.structuredContent)).not.toContain(
"synthetic-secret-token",
);
const loaded = await client.callTool({
name: "load_frida_script",
arguments: {
session_id: "00000000-0000-4000-8000-000000000001",
source_kind: "inline",
source: "send('loaded');",
},
});
expect(loaded.isError).not.toBe(true);
expect(JSON.stringify(loaded.structuredContent)).not.toContain(
"synthetic-secret-token",
);
const loadedValue = loaded.structuredContent;
if (
loadedValue === undefined ||
typeof loadedValue !== "object" ||
loadedValue === null ||
!("evidence_id" in loadedValue) ||
typeof loadedValue.evidence_id !== "string"
)
throw new Error("Expected inline Frida Evidence");
const retainedEvidence = session.evidenceById(loadedValue.evidence_id);
expect(JSON.stringify(retainedEvidence)).not.toContain(
"synthetic-secret-token",
);
for (const [name, args] of [
[
"resume_frida_session",
{ session_id: "00000000-0000-4000-8000-000000000001" },
],
[
"unload_frida_script",
{
session_id: "00000000-0000-4000-8000-000000000001",
script_id: "00000000-0000-4000-8000-000000000002",
},
],
[
"frida_session_status",
{ session_id: "00000000-0000-4000-8000-000000000001" },
],
[
"close_frida_session",
{ session_id: "00000000-0000-4000-8000-000000000001" },
],
] as const) {
const result = await client.callTool({ name, arguments: args });
expect(
result.isError,
`${name}: ${JSON.stringify(result.structuredContent)}`,
).not.toBe(true);
}
const invalidAddress = await client.callTool({
name: "list_frida_devices",
arguments: {
remote: { address: "tcp://127.0.0.1:27042?token=synthetic-secret-token" },
},
});
expect(invalidAddress.isError).toBe(true);
const oneShot = await client.callTool({
name: "instrument_with_frida",
arguments: {
mode: "attach",
pid: 10,
source_kind: "inline",
source: "send('one-shot');",
duration_ms: 0,
},
});
expect(oneShot.isError).not.toBe(true);
const oneShotContract = tools.find(
(tool) => tool.name === "instrument_with_frida",
);
if (oneShotContract?.outputSchema === undefined)
throw new Error("Missing one-shot Frida output schema");
const validateOneShot = ajv.compile(
oneShotContract.outputSchema as AnySchema,
);
expect(validateOneShot(oneShot.structuredContent)).toBe(true);
await expectFridaToolsAvailable(client);
});
it("reports Frida tools as unavailable after the optional binding fails to load", async () => {
const session = createTestBinarySession(() => {
throw new Error("Binary provider must not start");
});
const provider = new FridaInstrumentationManager({
deviceManagerLoader: async () => {
throw new Error("Cannot find package 'frida'");
},
});
const server = createServer(
{ kind: "session", session },
{ fridaInstrumentation: provider },
);
const client = new Client({ name: "frida-optional-binding", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const missing = await client.callTool({
name: "list_frida_devices",
arguments: {},
});
expect(missing.isError).toBe(true);
const inventory = await client.callTool({
name: "binary_session",
arguments: {},
});
const parsedInventory = toolContract("binary_session").outputSchema.safeParse(
inventory.structuredContent,
);
if (!parsedInventory.success)
throw new Error("Invalid binary session output");
expect(
expandToolAvailability(parsedInventory.data.result.tool_availability),
).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "list_frida_devices",
available: false,
reason: "provider_unavailable",
remediation: expect.stringContaining("Cannot find package 'frida'"),
}),
]),
);
});
it("retains cancellation Evidence after the MCP client stops waiting", async () => {
const session = createTestBinarySession(() => {
throw new Error("Binary provider must not start");
});
let finishLoad: (() => void) | undefined;
const loadGate = new Promise<void>((resolve) => {
finishLoad = resolve;
});
let markLoadStarted: (() => void) | undefined;
const loadStarted = new Promise<void>((resolve) => {
markLoadStarted = resolve;
});
let markSessionClosed: (() => void) | undefined;
const sessionClosed = new Promise<void>((resolve) => {
markSessionClosed = resolve;
});
const provider = createFridaTestProvider({
async loadScript() {
markLoadStarted?.();
await loadGate;
return {
ok: true,
value: {
scriptId: "00000000-0000-4000-8000-000000000002",
sourceKind: "inline",
sourcePath: null,
sourceSha256: "a".repeat(64),
messages: [{ type: "send", payload: "cancel-observed" }],
messagesTruncated: false,
},
};
},
status(sessionId) {
return {
sessionId,
deviceId: "remote-device",
target: "fixture",
pid: 10,
mode: "attach",
state: "running",
targetResumeObserved: false,
scripts: [],
messages: [{ type: "send", payload: "cancel-observed" }],
messagesTruncated: false,
};
},
async closeSession() {
markSessionClosed?.();
return { ok: true, value: { targetResumeObserved: false } };
},
});
const server = createServer(
{ kind: "session", session },
{ fridaInstrumentation: provider },
);
const client = new Client({ name: "frida-cancellation", version: "1" });
const controller = new AbortController();
onTestFinished(async () => {
finishLoad?.();
controller.abort();
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const call = client.callTool(
{
name: "instrument_with_frida",
arguments: {
mode: "attach",
pid: 10,
source_kind: "inline",
source: "send('cancel-observed');",
duration_ms: 1_000,
},
},
{ signal: controller.signal },
);
await loadStarted;
controller.abort(new Error("cancel Frida observation"));
finishLoad?.();
await expect(call).rejects.toThrow("cancel Frida observation");
await sessionClosed;
await client.ping();
const bundle = await client.callTool({
name: "get_evidence_bundle",
arguments: {},
});
expect(JSON.stringify(bundle.structuredContent)).toContain("cancel-observed");
expect(JSON.stringify(bundle.structuredContent)).toContain(
"instrument_with_frida",
);
});
@@ -0,0 +1,105 @@
import { describe, expect, it } from "vitest";
import { ok } from "../../../src/domain/result.js";
import {
compactReference,
compactInstruction,
compactCallTargets,
} from "../../../src/domain/native/nativeInstruction.fixture.js";
import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js";
describe("compact Ghidra reference MCP evidence", () => {
it("retains access kind, non-primary analyzer references and call-target provenance", async () => {
const base = {
...compactReference(),
call: false,
computed: false,
data: true,
};
const references = [
{ ...base, type: "DATA", primary: true, operand_index: 1 },
{ ...base, type: "READ", primary: true, read: true, operand_index: 1 },
{ ...base, type: "WRITE", primary: false, write: true, operand_index: 0 },
];
const outputs = {
inspect_native_instruction: {
...compactInstruction(references),
incoming_references: references.map((reference) => ({
...reference,
source_address: "ram:00403000",
target_address: "0x401000",
})),
},
resolve_native_call_targets: compactCallTargets([compactReference()]),
};
const harness = await connectGhidraMcp(
"ghidra-compact-provenance",
(operation) => {
if (
operation !== "inspect_native_instruction" &&
operation !== "resolve_native_call_targets"
)
throw new TypeError(`Unexpected operation: ${operation}`);
return Promise.resolve(ok(outputs[operation]));
},
);
try {
for (const name of [
"inspect_native_instruction",
"resolve_native_call_targets",
] as const) {
const result = await harness.mcp.callTool({
name,
arguments: { address: "0x401000" },
});
expect(result.isError).not.toBe(true);
const evidence = sessionEvidence(
harness.session,
result.structuredContent,
);
expect(evidence.normalized_result).toEqual(outputs[name]);
}
} finally {
await harness.close();
}
}, 30_000);
it("preserves empty references and unresolved targets without manufacturing provenance", async () => {
const outputs = {
inspect_native_instruction: {
...compactInstruction(),
status: "data",
incoming_references: [],
},
resolve_native_call_targets: compactCallTargets(),
};
const harness = await connectGhidraMcp(
"ghidra-compact-unknown",
(operation) => {
if (
operation !== "inspect_native_instruction" &&
operation !== "resolve_native_call_targets"
)
throw new TypeError(`Unexpected operation: ${operation}`);
return Promise.resolve(ok(outputs[operation]));
},
);
try {
for (const name of [
"inspect_native_instruction",
"resolve_native_call_targets",
] as const) {
const result = await harness.mcp.callTool({
name,
arguments: { address: "0x401000" },
});
expect(result.isError).not.toBe(true);
expect(
sessionEvidence(harness.session, result.structuredContent)
.normalized_result,
).toEqual(outputs[name]);
}
} finally {
await harness.close();
}
}, 30_000);
});
+151 -1
View File
@@ -4,8 +4,98 @@ import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js";
import { functionDossierSchema } from "../../../src/domain/hopperValues.js";
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import {
jsonValueSchema,
type JsonValue,
} from "../../../src/domain/jsonValue.js";
import { ok } from "../../../src/domain/result.js";
import {
isGhidraFunctionOperation,
type GhidraFunctionOperation,
} from "../../../src/ghidra/GhidraFunctionValues.js";
it("retains terminal-call qualifications across function views and snapshot replay", async () => {
const limitation =
"Ghidra Listing reports a terminal call at 0x401000 to EXTERNAL:0x20 __tls_get_addr (external=true, thunk=false, hasNoReturn=true); fallthrough is excluded by Ghidra's flow model. This records Ghidra's FunctionManager flag, not an independent verification that the callee cannot return.";
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
dossier.limitations.push(limitation);
const { signature, locals, ...identity } = dossier.procedure;
if (!identity.body.available)
throw new Error("The function fixture must include its analyzed body");
const values = new Map<GhidraFunctionOperation, JsonValue>([
["procedure_pseudo_code", dossier.pseudocode],
["procedure_assembly", dossier.assembly.join("\n")],
[
"procedure_info",
{
name: identity.name,
entrypoint: identity.address,
signature,
locals,
basicblock_count: dossier.basic_blocks.length,
length: identity.body.total_bytes,
classification: identity.classification,
body: identity.body,
},
],
[
"read_function_instructions",
{
procedure: identity,
instructions: dossier.assembly,
limitations: [limitation],
},
],
["analyze_function", jsonValueSchema.parse(dossier)],
]);
const harness = await connectGhidraMcp(
"ghidra-terminal-call-evidence",
(operation) => {
if (!isGhidraFunctionOperation(operation))
throw new Error(`Unexpected operation: ${operation}`);
const value = values.get(operation);
if (value === undefined)
throw new Error(`Unexpected operation: ${operation}`);
return Promise.resolve(ok({ value, limitations: [limitation] }));
},
);
try {
for (const [name, value] of values) {
const request = {
name,
arguments:
name === "analyze_function"
? { procedure: identity.address }
: { procedure: identity.address, document: "fixture" },
};
const reply = await harness.mcp.callTool(request);
expect(reply.isError, name).not.toBe(true);
const evidence = sessionEvidence(
harness.session,
reply.structuredContent,
);
expect(evidence.normalized_result, name).toEqual(value);
expect(evidence.raw_result, name).toEqual({
value,
limitations: [limitation],
});
expect(evidence.limitations, name).toContain(limitation);
expect(evidence.analysis_profile?.parameters).toMatchObject({
function_boundary_observations: "ghidra-terminal-call-limitations-v1",
});
const replay = await harness.session.execute(name, evidence.parameters);
if (!replay.ok) throw replay.error;
expect(replay.value.result, name).toEqual(value);
expect(replay.value.limitations, name).toContain(limitation);
expect(replay.value.limitations, name).toContainEqual(
expect.stringContaining("Loaded from a local REA analysis snapshot"),
);
}
expect(harness.calls).toEqual([...values.keys()]);
} finally {
await harness.close();
}
});
it("rejects contradictory annotation readback across the provider and MCP boundaries", async () => {
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
@@ -62,6 +152,66 @@ it("rejects contradictory annotation readback across the provider and MCP bounda
}
});
it("routes address naming to Ghidra with compact per-address results", async () => {
const requests: { operation: string; input: unknown }[] = [];
let output: unknown = null;
const harness = await connectGhidraMcp(
"ghidra-address-naming",
(operation, input) => {
requests.push({ operation, input });
return Promise.resolve(ok(jsonValueSchema.parse(output)));
},
);
try {
output = true;
const single = await harness.mcp.callTool({
name: "set_address_name",
arguments: { address: "0x1000", name: "fixture_entry" },
});
expect(single.isError).not.toBe(true);
expect(single.structuredContent).toMatchObject({ normalized_result: true });
output = { "0x1000": true, "0x2000": false };
const batch = await harness.mcp.callTool({
name: "set_addresses_names",
arguments: { names: { "0x1000": "fixture_entry", "0x2000": "g_value" } },
});
expect(batch.isError).not.toBe(true);
expect(batch.structuredContent).toMatchObject({
normalized_result: { "0x1000": true, "0x2000": false },
});
expect(requests).toEqual([
{
operation: "set_address_name",
input: { document: null, address: "0x1000", name: "fixture_entry" },
},
{
operation: "set_addresses_names",
input: {
document: null,
names: { "0x1000": "fixture_entry", "0x2000": "g_value" },
},
},
]);
const empty = await harness.mcp.callTool({
name: "set_addresses_names",
arguments: { names: {} },
});
expect(empty.isError).toBe(true);
expect(requests).toHaveLength(2);
output = "fixture_entry";
const malformed = await harness.mcp.callTool({
name: "set_address_name",
arguments: { address: "0x1000", name: "fixture_entry" },
});
expect(malformed.isError).toBe(true);
expect(parseMcpToolError(malformed)).toMatchObject({
error: { code: "unreadable_output" },
});
} finally {
await harness.close();
}
});
describe("Ghidra MCP evidence parity", () => {
it("preserves provider evidence, composed parity, and capability routing", async () => {
const harness = await connectGhidraMcp("ghidra-parity");
+60 -1
View File
@@ -3,7 +3,66 @@ import { expect, it } from "vitest";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { ok } from "../../../src/domain/result.js";
import { ghidraFunctionIdentity } from "../../../src/domain/ghidraValues.fixture.js";
import { connectGhidraMcp } from "./ghidraMcpHarness.js";
import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js";
it("retains defined-string coverage in empty and matching search Evidence", async () => {
let output = jsonValueSchema.parse([]);
const harness = await connectGhidraMcp("ghidra-string-coverage", () =>
Promise.resolve(ok(output)),
);
try {
for (const request of [
{ name: "list_strings", arguments: {} },
{ name: "search_strings", arguments: { pattern: "projection" } },
{
name: "search_strings",
arguments: { pattern: "projection.*", mode: "regex" },
},
]) {
const reply = await harness.mcp.callTool(request);
expect(reply.isError).not.toBe(true);
const evidence = sessionEvidence(
harness.session,
reply.structuredContent,
);
expect(evidence.normalized_result).toEqual([]);
expect(evidence.analysis_profile?.parameters).toMatchObject({
string_inventory_evidence: "defined-data-coverage-v1",
});
expect(evidence.limitations).toContainEqual(
expect.stringMatching(
/Only Ghidra-defined string Data.*empty search does not establish/u,
),
);
}
output = jsonValueSchema.parse([
{ address: "0x401000", value: "projection cache ignored" },
]);
const matched = await harness.mcp.callTool({
name: "search_strings",
arguments: { pattern: "projection" },
});
const evidence = sessionEvidence(
harness.session,
matched.structuredContent,
);
expect(evidence.normalized_result).toEqual(output);
expect(evidence.limitations).toContainEqual(
expect.stringContaining("Completeness applies to that inventory"),
);
output = jsonValueSchema.parse([]);
const procedures = await harness.mcp.callTool({
name: "search_procedures",
arguments: { pattern: "projection" },
});
expect(
sessionEvidence(harness.session, procedures.structuredContent)
.limitations,
).not.toContainEqual(expect.stringContaining("Ghidra-defined string Data"));
} finally {
await harness.close();
}
});
it("rejects contradictory provider output before emitting MCP Evidence", async () => {
const bytes = {
+28 -10
View File
@@ -206,15 +206,19 @@ const resultBuilders = new Map<GhidraOperation, GhidraResultBuilder>([
["procedure_callers", () => []],
[
"procedure_info",
() => ({
name: "fixture_main",
entrypoint: "0x401000",
basicblock_count: 1,
length: 6,
signature: "int fixture_main(void)",
locals: [],
classification: ghidraFunctionClassification(),
}),
() => {
const identity = ghidraFunctionIdentity();
return {
name: "fixture_main",
entrypoint: "0x401000",
basicblock_count: 1,
length: 6,
signature: "int fixture_main(void)",
locals: [],
classification: ghidraFunctionClassification(),
body: identity.body,
};
},
],
["procedure_pseudo_code", () => "int fixture_main(void) { return 42; }"],
[
@@ -247,9 +251,23 @@ const resultFor = (
const builder = resultBuilders.get(operation);
if (builder === undefined)
throw new TypeError(`Unexpected Ghidra operation: ${operation}`);
return builder(input, typeof input.limit === "number" ? input.limit : 100);
const value = builder(
input,
typeof input.limit === "number" ? input.limit : 100,
);
return functionObservationOperations.has(operation)
? { value, limitations: [] }
: value;
};
const functionObservationOperations: ReadonlySet<GhidraOperation> = new Set([
"analyze_function",
"procedure_assembly",
"procedure_info",
"procedure_pseudo_code",
"read_function_instructions",
]);
const stringItem = (address: string, value: string): JsonValue => ({
address,
value,
+346
View File
@@ -0,0 +1,346 @@
import { spawn, type ChildProcess } from "node:child_process";
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js";
import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js";
import { LazyAnalysisProvider } from "../../../src/application/binary/LazyAnalysisProvider.js";
import { parseConfig } from "../../../src/config/parseConfig.js";
import { elf } from "../../../src/domain/binaryTarget.fixture.js";
import { ok } from "../../../src/domain/result.js";
import { GhidraClient } from "../../../src/ghidra/GhidraClient.js";
import type { GhidraInstallationHost } from "../../../src/ghidra/GhidraInstallation.js";
import type {
GhidraLaunchSession,
GhidraLauncher,
} from "../../../src/ghidra/GhidraLauncher.js";
import { GhidraProvider } from "../../../src/ghidra/GhidraProvider.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { waitForExit } from "../../support/process/processFixture.js";
const fixturePath = fileURLToPath(
new URL("../../fixtures/fakeGhidra.mjs", import.meta.url),
);
type FixtureLaunch = {
child: ChildProcess;
runtimeRoot: string;
endpointPath: string;
};
class FixtureLauncher implements GhidraLauncher {
readonly launches: FixtureLaunch[] = [];
readonly requests: string[] = [];
cleanupAllowed = true;
cleanupAttempts = 0;
async launch(session: GhidraLaunchSession) {
const projectRoot = join(session.runtimeRoot, "project");
await mkdir(projectRoot, { recursive: true });
const child = spawn(process.execPath, [fixturePath], {
stdio: ["ignore", "pipe", "pipe", "ipc"],
env: {
...process.env,
REA_GHIDRA_FIXTURE_CONFIG: JSON.stringify({
endpointPath: session.endpointPath,
token: session.token,
runId: session.runId,
providerVersion: session.providerVersion,
profileDigest: session.profileDigest,
targetSha256: session.targetSha256,
transport: session.transport,
}),
},
});
this.launches.push({
child,
runtimeRoot: session.runtimeRoot,
endpointPath: session.endpointPath,
});
child.on("message", (value: unknown) => {
if (
typeof value === "object" &&
value !== null &&
"method" in value &&
typeof value.method === "string"
)
this.requests.push(value.method);
});
return ok({
process: child,
ownsProcessLifetime: true as const,
projectRoot,
ghidraLogPath: join(session.runtimeRoot, "ghidra.log"),
scriptLogPath: join(session.runtimeRoot, "script.log"),
cleanup: async () => {
this.cleanupAttempts += 1;
if (!this.cleanupAllowed)
return {
cleaned: false as const,
reason: "fixture cleanup is not yet confirmed",
};
const signaled = child.exitCode === null && child.signalCode === null;
if (signaled) child.kill("SIGTERM");
return (await waitForExit(child, 2_000))
? { cleaned: true as const, signaled }
: { cleaned: false as const, reason: "fixture child did not exit" };
},
});
}
}
const installationHost: GhidraInstallationHost = {
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
major: 21,
home: "/fixture/jdk-21",
bits: 64,
runtime: "jdk",
}),
};
// Only installation discovery and the Java bridge are simulated. Requests use
// the production client, real child/socket and public MCP session routing.
const connectGhidra = async () => {
const directory = await createTestTempDirectory("rea-ghidra-reopen-");
const target = join(directory, "target.elf");
const source = elf(2, 1, 62);
await writeFile(target, source);
const config = parseConfig({
GHIDRA_INSTALL_DIR: "/fixture/ghidra_12.1.4_PUBLIC",
});
if (!config.ok) throw config.error;
const launcher = new FixtureLauncher();
const clients: GhidraClient[] = [];
const provider = new GhidraProvider(
config.value,
silentLogger,
{},
installationHost,
(options) => {
const client = new GhidraClient({
...options,
launcher,
platform: process.platform,
startupTimeoutMs: 5_000,
});
clients.push(client);
return client;
},
);
const lazy = new LazyAnalysisProvider({
identity: provider.identity(),
capabilities: provider.capabilities(),
load: () => Promise.resolve(provider),
});
const session = composeBinarySession(
new AnalysisProviderRegistry([
{
identity: () => provider.identity(),
capabilities: () => provider.capabilities(),
inspectAvailability: () => provider.inspectAvailability(),
inspectTargetSupport: (value) => provider.inspectTargetSupport(value),
resolveAnalysisProfile: (value, options) =>
provider.resolveAnalysisProfile(value, options),
createClient: (value, profile, context) =>
lazy.createClient(value, profile, context),
},
]),
);
const server = createServer(
{ kind: "session", session },
{ logger: silentLogger },
);
const mcp = new Client({ name: "ghidra-reopen", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const close = async () => {
launcher.cleanupAllowed = true;
await Promise.allSettled([mcp.close(), server.close()]);
const closed = await session.close();
try {
for (const client of clients)
expect((await client.close()).ok).toBe(true);
expect(closed.ok).toBe(true);
} finally {
for (const { child } of launcher.launches) {
if (child.exitCode === null && child.signalCode === null)
child.kill("SIGTERM");
expect(await waitForExit(child, 2_000)).toBe(true);
}
}
for (const launched of launcher.launches) await expectReleased(launched);
expect(await readFile(target)).toEqual(source);
};
try {
await server.connect(serverTransport);
await mcp.connect(clientTransport);
} catch (cause) {
await close();
throw cause;
}
return {
clients,
launcher,
close,
open: () =>
mcp.callTool({ name: "open_binary", arguments: { path: target } }),
query: (addressSuffix: number) =>
mcp.callTool({
name: "list_strings",
arguments: { address: `0x200${addressSuffix}` },
}),
};
};
const firstLaunch = (launcher: FixtureLauncher): FixtureLaunch => {
const first = launcher.launches[0];
if (first === undefined) throw new Error("Expected a running Ghidra fixture");
return first;
};
const expectReleased = async ({
child,
runtimeRoot,
endpointPath,
}: FixtureLaunch) => {
expect(await waitForExit(child, 2_000)).toBe(true);
await expect(access(runtimeRoot)).rejects.toMatchObject({ code: "ENOENT" });
await expect(access(endpointPath)).rejects.toMatchObject({ code: "ENOENT" });
};
const disconnect = async (
child: ChildProcess,
client: GhidraClient | undefined,
) => {
if (client === undefined)
throw new Error("Expected a connected Ghidra client");
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
child.off("message", received);
reject(new Error("Fixture did not acknowledge socket disconnection"));
}, 2_000);
const received = (message: unknown) => {
if (
typeof message !== "object" ||
message === null ||
!("event" in message) ||
message.event !== "disconnected"
)
return;
clearTimeout(timer);
child.off("message", received);
resolve();
};
child.on("message", received);
child.send("disconnect");
});
await expect
.poll(async () => (await client.ping({ timeoutMs: 200 })).ok)
.toBe(false);
expect(child.exitCode).toBeNull();
expect(child.signalCode).toBeNull();
};
describe.skipIf(process.platform === "win32")(
"Ghidra MCP session recovery over Unix sockets",
() => {
it("keeps open lazy, reuses a live child, and replaces an exited child on reopen", async () => {
const harness = await connectGhidra();
try {
expect((await harness.open()).isError).not.toBe(true);
expect((await harness.open()).isError).not.toBe(true);
expect(harness.clients).toHaveLength(0);
expect(harness.launcher.launches).toHaveLength(0);
expect((await harness.query(1)).isError).not.toBe(true);
const old = firstLaunch(harness.launcher);
expect((await harness.open()).isError).not.toBe(true);
expect((await harness.query(2)).isError).not.toBe(true);
expect(harness.launcher.launches).toHaveLength(1);
await expect
.poll(
() =>
harness.launcher.requests.filter(
(method) => method === "list_strings",
).length,
)
.toBe(2);
expect(old.child.kill("SIGTERM")).toBe(true);
expect(await waitForExit(old.child, 2_000)).toBe(true);
expect(old.child.signalCode).toBe("SIGTERM");
expect((await harness.open()).isError).not.toBe(true);
await expectReleased(old);
expect(harness.clients).toHaveLength(1);
expect(harness.launcher.launches).toHaveLength(1);
expect((await harness.query(3)).isError).not.toBe(true);
expect(harness.clients).toHaveLength(2);
expect(harness.launcher.launches).toHaveLength(2);
} finally {
await harness.close();
}
});
it("retires a disconnected live child before lazily starting a replacement", async () => {
const harness = await connectGhidra();
try {
expect((await harness.open()).isError).not.toBe(true);
expect((await harness.query(1)).isError).not.toBe(true);
const old = firstLaunch(harness.launcher);
await disconnect(old.child, harness.clients[0]);
expect((await harness.open()).isError).not.toBe(true);
await expectReleased(old);
expect(harness.clients).toHaveLength(1);
expect(harness.launcher.launches).toHaveLength(1);
expect((await harness.query(2)).isError).not.toBe(true);
expect(harness.clients).toHaveLength(2);
expect(harness.launcher.launches).toHaveLength(2);
} finally {
await harness.close();
}
});
it("retains failed cleanup and refuses replacement until cleanup can be retried", async () => {
const harness = await connectGhidra();
try {
expect((await harness.open()).isError).not.toBe(true);
expect((await harness.query(1)).isError).not.toBe(true);
const old = firstLaunch(harness.launcher);
await disconnect(old.child, harness.clients[0]);
harness.launcher.cleanupAllowed = false;
for (let attempt = 1; attempt <= 2; attempt += 1) {
expect(parseMcpToolError(await harness.open())).toMatchObject({
error: { code: "cleanup_incomplete" },
});
expect(harness.launcher.cleanupAttempts).toBe(attempt);
expect(harness.clients).toHaveLength(1);
expect(harness.launcher.launches).toHaveLength(1);
expect(old.child.exitCode).toBeNull();
expect(old.child.signalCode).toBeNull();
await access(old.runtimeRoot);
}
harness.launcher.cleanupAllowed = true;
expect((await harness.open()).isError).not.toBe(true);
await expectReleased(old);
expect(harness.launcher.cleanupAttempts).toBe(3);
expect(harness.clients).toHaveLength(1);
expect(harness.launcher.launches).toHaveLength(1);
expect((await harness.query(2)).isError).not.toBe(true);
expect(harness.clients).toHaveLength(2);
expect(harness.launcher.launches).toHaveLength(2);
} finally {
await harness.close();
}
});
},
);
+29 -36
View File
@@ -1,6 +1,8 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { describe, expect, it } from "vitest";
import { connectGhidraMcp } from "./ghidraMcpHarness.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
describe("Ghidra MCP capability routing", () => {
it("routes composed and capability tools", async () => {
@@ -41,44 +43,35 @@ describe("Ghidra MCP capability routing", () => {
name: "binary_session",
arguments: {},
});
expect(status.structuredContent).toMatchObject({
result: {
open: true,
analysis_provider_binding: {
provider: { id: "ghidra", version: "12.1.4" },
},
tool_availability: expect.arrayContaining([
expect.objectContaining({
name: "binary_overview",
available: true,
}),
expect.objectContaining({
name: "get_objc_classes",
available: true,
}),
expect.objectContaining({
name: "batch_decompile",
available: true,
}),
expect.objectContaining({
name: "trace_feature",
available: true,
}),
expect.objectContaining({
name: "get_call_graph",
available: true,
}),
expect.objectContaining({
name: "find_xrefs_to_name",
available: true,
}),
expect.objectContaining({
name: "set_comment",
available: false,
}),
]),
const sessionStatus = toolContract("binary_session").outputSchema.parse(
status.structuredContent,
);
expect(sessionStatus.result).toMatchObject({
open: true,
analysis_provider_binding: {
provider: { id: "ghidra", version: "12.1.4" },
},
});
const availability = expandToolAvailability(
sessionStatus.result.tool_availability,
);
expect(availability).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "binary_overview", available: true }),
expect.objectContaining({
name: "get_objc_classes",
available: true,
}),
expect.objectContaining({ name: "batch_decompile", available: true }),
expect.objectContaining({ name: "trace_feature", available: true }),
expect.objectContaining({ name: "get_call_graph", available: true }),
expect.objectContaining({
name: "find_xrefs_to_name",
available: true,
}),
expect.objectContaining({ name: "set_comment", available: false }),
]),
);
} finally {
await harness.close();
}
+285
View File
@@ -0,0 +1,285 @@
import type { Client } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { readAnalysisSnapshot } from "../../../src/application/binary/AnalysisSnapshotFiles.js";
import { GoBinaryService } from "../../../src/application/go/GoBinaryService.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { GoBinaryProvider } from "../../../src/go/GoBinaryProvider.js";
import { createServer } from "../../../src/server/createServer.js";
import {
createCacheProvider,
createDeferred,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import {
createGoBinaryByteStringFixture,
createGoBinaryDiagnosticFixtures,
createGoBinaryFixture,
createGoBinaryPathFailureFixture,
} from "../../fixtures/go/image.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { mcpTest } from "../../support/mcp/mcpFixture.js";
const goMcpTest = mcpTest.extend<{
go: {
client: Client;
session: ReturnType<typeof createTestBinarySession>;
};
}>({
go: async ({ mcp }, use) => {
const session = createTestBinarySession(() => {
throw new Error("Go metadata must not start a deep provider");
});
try {
const client = await mcp.connect(
createServer({ kind: "session", session }),
);
await use({ client, session });
} finally {
await session.close();
}
},
});
mcpTest(
"retains MIPS identity and in-flight Go inspection in the saved session snapshot",
async ({ mcp }) => {
const root = await createTestTempDirectory("rea-go-mcp-close-");
const path = join(root, "application");
const snapshotPath = join(root, "analysis.json");
const fixture = createGoBinaryFixture({ bits: 32, byteOrder: "big" });
fixture.bytes.writeUInt16BE(8, 18); // ELF EM_MIPS.
await writeFile(path, fixture.bytes);
const entered = createDeferred<void>();
const release = createDeferred<void>();
const closeStarted = createDeferred<void>();
const provider = new GoBinaryProvider();
const session = createTestBinarySession(createCacheProvider([]));
const service = new GoBinaryService({
identity: provider.identity,
inspect: async (input, options) => {
const result = await provider.inspect(input, options);
entered.resolve();
await release.promise;
return result;
},
});
try {
const client = await mcp.connect(
createServer({ kind: "session", session }, { goBinary: service }),
);
const opened = await client.callTool({
name: "open_binary",
arguments: { path },
});
expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true);
client.setNotificationHandler("notifications/progress", () => {
closeStarted.resolve();
});
const inspection = client.callTool({
name: "inspect_go_binary",
arguments: { path },
});
await entered.promise;
const closing = client.callTool({
name: "close_binary",
arguments: { snapshot_path: snapshotPath },
_meta: { progressToken: "go-close-race" },
});
await closeStarted.promise;
release.resolve();
const inspected = await inspection;
expect(inspected.isError, JSON.stringify(inspected.content)).not.toBe(
true,
);
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
inspected.structuredContent,
);
expect(evidence.subject?.architecture).toBe("mips");
expect(evidence.normalized_result).toMatchObject({
architecture: "mips",
bits: 32,
byte_order: "big",
});
const closed = await closing;
expect(closed.isError, JSON.stringify(closed.content)).not.toBe(true);
const snapshot = await readAnalysisSnapshot(snapshotPath);
if (!snapshot.ok) throw snapshot.error;
expect(snapshot.value.evidence_bundle.records).toContainEqual(evidence);
expect(session.evidenceById(evidence.evidence_id)).toBeUndefined();
} finally {
release.resolve();
await session.close();
}
},
);
for (const expectedErrno of ["ELOOP", "ENAMETOOLONG"] as const) {
goMcpTest.skipIf(expectedErrno === "ELOOP" && process.platform === "win32")(
`reports native ${expectedErrno} path failure as invalid selected-path input through Go MCP`,
async ({ go: { client } }) => {
const root = await createTestTempDirectory("rea-go-mcp-path-failure-");
const { path, errno } = await createGoBinaryPathFailureFixture(
root,
expectedErrno,
);
const response = await client.callTool({
name: "inspect_go_binary",
arguments: { path },
});
const diagnostic = parseMcpToolError(response);
expect(diagnostic.error).toMatchObject({
code: "invalid_request",
details: {
operation: "inspect_go_binary",
issues: [
{
path: ["path"],
reason: "invalid_value",
message: expect.stringContaining(errno),
},
],
},
});
expect(diagnostic.error.details).toMatchObject({
issues: [{ message: expect.stringContaining(path) }],
});
},
);
}
goMcpTest(
"preserves invalid embedded Go text bytes through MCP",
async ({ go: { client, session } }) => {
const root = await createTestTempDirectory("rea-go-mcp-byte-strings-");
const path = join(root, "byte-strings.elf");
const fixture = createGoBinaryByteStringFixture();
await writeFile(path, fixture.bytes);
const response = await client.callTool({
name: "inspect_go_binary",
arguments: { path },
});
expect(response.isError).not.toBe(true);
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
response.structuredContent,
);
expect(evidence.normalized_result.build_info).toEqual(
fixture.expectedBuildInfo,
);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
},
);
goMcpTest(
"distinguishes unsupported MZ carriers from malformed PE through MCP",
async ({ go: { client } }) => {
const root = await createTestTempDirectory("rea-go-mcp-mz-");
for (const fixture of createGoBinaryDiagnosticFixtures()) {
const path = join(root, `${fixture.name}.exe`);
await writeFile(path, fixture.bytes);
const response = await client.callTool({
name: "inspect_go_binary",
arguments: { path },
});
expect(response.isError).toBe(true);
expect(parseMcpToolError(response)).toMatchObject({
error: {
code: fixture.code,
details: {
...fixture.details,
...(fixture.code === "unsupported_target" ? { path } : {}),
},
},
});
}
},
);
goMcpTest(
"advertises valid schemas and inspects real file bytes through MCP without an active target",
async ({ go: { client, session } }) => {
const status = await client.callTool({
name: "binary_session",
arguments: {},
});
const availability = expandToolAvailability(
toolContract("binary_session").outputSchema.parse(
status.structuredContent,
).result.tool_availability,
);
expect(availability).toContainEqual(
expect.objectContaining({
name: "inspect_go_binary",
available: true,
reason: "available",
}),
);
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_go_binary",
);
if (advertised?.outputSchema === undefined)
throw new Error("Go metadata must publish both schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
expect(
ajv.validate(inputSchema, { path: "/artifacts/program", execute: true }),
).toBe(false);
expect(ajv.validate(inputSchema, { path: "/artifacts/\0program" })).toBe(
false,
);
expect(advertised.annotations).toMatchObject({
readOnlyHint: false,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
});
const root = await createTestTempDirectory("rea-go-mcp-");
const path = join(root, "application");
const fixture = createGoBinaryFixture({
moduleText: "path\texample.com/tool\nnew-record\tfuture\n",
});
await writeFile(path, fixture.bytes);
const response = await client.callTool({
name: "inspect_go_binary",
arguments: { path },
});
expect(response.isError).not.toBe(true);
expect(
ajv.validate(outputSchema, response.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const parsed = toolContract("inspect_go_binary").outputSchema.parse(
response.structuredContent,
);
const evidence = parseEvidence(parsed);
expect(evidence.confidence).toBe("observed");
expect(parsed.normalized_result.build_info?.module).toMatchObject({
path: "example.com/tool",
complete: false,
unparsed_lines: ["new-record\tfuture"],
});
expect(evidence.limitations.join(" ")).toContain(
"could not be parsed completely",
);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
const invalid = await client.callTool({
name: "inspect_go_binary",
arguments: { path: "relative.bin" },
});
expect(invalid.isError).toBe(true);
expect(parseMcpToolError(invalid)).toMatchObject({
error: {
code: "invalid_request",
details: { issues: [{ path: ["path"], reason: "invalid_format" }] },
},
});
},
);
@@ -3,7 +3,14 @@ import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import {
createBinarySessionTargets,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import {
createAnalysisExecution,
type AnalysisOperationPort,
} from "../../../src/application/AnalysisProvider.js";
import type { BinarySession } from "../../../src/application/binary/BinarySession.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
import { INVESTIGATION_EXAMPLES } from "../../../src/contracts/investigationExamples.js";
@@ -20,6 +27,7 @@ import {
} from "../../../src/domain/jsonValue.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
import type { RelationshipCoverage } from "../../../src/domain/relationshipCoverage.js";
it("aggregates comparison Evidence and records an approved runtime gap", async () => {
const { session, server, client } = await connected();
@@ -149,6 +157,183 @@ const dossierWithCallees = (addresses: readonly string[]) => {
);
};
it.each([
{
label: "complete",
coverage: { status: "complete" } as RelationshipCoverage,
providerLimitations: ["The provider version identity is unavailable."],
dossierLimitations: ["The dossier has no native value-flow observation."],
status: "not_found",
exhaustive: true,
},
{
label: "partial",
coverage: {
status: "partial",
limitations: ["Callee output was capped."],
} as RelationshipCoverage,
providerLimitations: [],
dossierLimitations: [],
status: "unknown",
exhaustive: false,
},
{
label: "unknown",
coverage: {
status: "unknown",
reason: "Callee coverage was not established.",
} as RelationshipCoverage,
providerLimitations: [],
dossierLimitations: [],
status: "unknown",
exhaustive: false,
},
{
label: "legacy limited",
coverage: undefined,
providerLimitations: [
"Legacy relationship completeness was not established.",
],
dossierLimitations: [],
status: "unknown",
exhaustive: false,
},
{
label: "legacy unlimited",
coverage: undefined,
providerLimitations: [],
dossierLimitations: [],
status: "not_found",
exhaustive: true,
},
])(
"preserves $label coverage through public analyze_function then build_call_path",
async (scenario) => {
const base = FUNCTION_COMPARISON_EXAMPLE.left;
if (base.subject === null) throw new Error("missing fixture subject");
const provider = {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
};
const rawResult = { fixture_reply: scenario.label };
const execution = createAnalysisExecution(
{
...jsonObjectSchema.parse(base.normalized_result),
callees: [],
limitations: scenario.dossierLimitations,
},
provider,
{
rawResult,
limitations: scenario.providerLimitations,
locations: base.locations,
...(scenario.coverage === undefined
? {}
: { relationshipCoverage: scenario.coverage }),
},
);
const { session, server, client } = await connected({
execute: async (operation, parameters) => {
if (operation === "health") return observed(null);
if (operation !== "analyze_function")
throw new Error(`Unexpected operation: ${operation}`);
expect(parameters.procedure).toBe("0x1000");
return resultOk(execution);
},
});
try {
const [path] = await createBinarySessionTargets();
const opened = await client.callTool({
name: "open_binary",
arguments: { path },
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const analyzed = await client.callTool({
name: "analyze_function",
arguments: { procedure: "0x1000" },
});
expect(analyzed.isError, JSON.stringify(analyzed)).not.toBe(true);
const dossier = inlineEvidence(analyzed.structuredContent);
expect(dossier).toMatchObject({
operation: "analyze_function",
parameters: { procedure: "0x1000" },
provider,
subject: {
local_path: path,
digest: { sha256: session.activeTarget()?.sha256 },
format: session.activeTarget()?.format,
},
raw_result: rawResult,
limitations: scenario.providerLimitations,
locations: base.locations,
normalized_result: {
callees: [],
limitations: scenario.dossierLimitations,
},
});
const response = await client.callTool({
name: "build_call_path",
arguments: {
functions: [dossier],
start: { address: "0x1000" },
goal: { address: "0x4000" },
},
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const evidence = inlineEvidence(response.structuredContent);
const coverage = scenario.coverage;
const reasons =
coverage?.status === "partial"
? coverage.limitations
: coverage?.status === "unknown"
? [coverage.reason]
: [];
expect(evidence.normalized_result).toMatchObject({
status: scenario.status,
shortest_hops: null,
paths: [],
search_scope: { exhaustive: scenario.exhaustive },
limitations: expect.arrayContaining([
...scenario.providerLimitations,
...scenario.dossierLimitations,
...reasons,
]),
});
expect(evidence.evidence_links).toEqual([dossier.evidence_id]);
expect(dossier.relationship_coverage).toEqual(coverage ?? null);
if (coverage?.status === "partial") {
const tampered = {
...dossier,
relationship_coverage: { status: "complete" },
};
expect(() => parseEvidence(tampered)).toThrow();
const rejected = await client.callTool({
name: "build_call_path",
arguments: {
functions: [tampered],
start: { address: "0x1000" },
goal: { address: "0x4000" },
},
});
expect(rejected.isError, JSON.stringify(rejected)).toBe(true);
}
if (scenario.exhaustive)
expect(session.listUnknowns({ domain: "call-path" })).toEqual([]);
else
expect(session.listUnknowns({ domain: "call-path" })).toMatchObject([
{
question:
"Can the requested call path be established from complete analysis?",
supporting_evidence_ids: [evidence.evidence_id],
},
]);
} finally {
await close(session, server, client);
}
},
);
it("records a safe unresolved call-path question", async () => {
const { session, server, client } = await connected();
const dossier = dossierWithCallees(["0x2000"]);
@@ -326,10 +511,12 @@ it("cannot omit a session-owned active unknown from reconstruction input", async
}
});
const connected = async () => {
const connected = async (analysis?: AnalysisOperationPort) => {
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
execute:
analysis?.execute.bind(analysis) ??
(() => Promise.resolve(observed(null))),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer({ kind: "session", session });
@@ -12,99 +12,143 @@ import {
} from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("stops a cancelled SDK request on the server, retains prior Evidence, and accepts subsequent work", async () => {
const root = await createTestTempDirectory("rea-mcp-js-cancellation-");
await writeFile(join(root, "main.js"), "export const observed = 1;\n");
const session = createTestBinarySession(() => {
throw new Error(
"Static JavaScript analysis must not start a binary provider",
it.each([
{ phase: "parse_javascript_source", message: "second.js", parsedFiles: 1 },
{
phase: "analyze_javascript_application",
message: "Application graph and Electron boundaries reconstructed",
parsedFiles: 2,
},
])(
"retains completed facts and prior Evidence after SDK cancellation during $phase, then accepts subsequent work",
async ({ phase, message, parsedFiles }) => {
const root = await createTestTempDirectory("rea-mcp-js-cancellation-");
await writeFile(join(root, "main.js"), "export const observed = 1;\n");
await writeFile(join(root, "second.js"), "export const pending = 2;\n");
const session = createTestBinarySession(() => {
throw new Error(
"Static JavaScript analysis must not start a binary provider",
);
});
const prior = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: "prior_observation",
parameters: {},
result: { preserved: true },
},
);
});
const prior = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: "prior_observation",
parameters: {},
result: { preserved: true },
},
);
expect(session.recordEvidence(prior).ok).toBe(true);
const completed = createDeferred<string>();
const completionSchema = z.object({
tool: z.string(),
status: z.string(),
msg: z.string(),
});
const logger = pino(
{ level: "info" },
{
write(line) {
const value: unknown = JSON.parse(line);
const parsed = completionSchema.safeParse(value);
if (
parsed.success &&
parsed.data.tool === "analyze_javascript_application" &&
parsed.data.msg === "MCP tool execution completed"
)
completed.resolve(parsed.data.status);
expect(session.recordEvidence(prior).ok).toBe(true);
const completed = createDeferred<string>();
const completionSchema = z.object({
tool: z.string(),
status: z.string(),
msg: z.string(),
});
const logger = pino(
{ level: "info" },
{
write(line) {
const value: unknown = JSON.parse(line);
const parsed = completionSchema.safeParse(value);
if (
parsed.success &&
parsed.data.tool === "analyze_javascript_application" &&
parsed.data.msg === "MCP tool execution completed"
)
completed.resolve(parsed.data.status);
},
},
},
);
const server = createServer({ kind: "session", session }, { logger });
const client = new Client({ name: "javascript-cancellation", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const controller = new AbortController();
let requested = false;
const call = client.callTool(
{
name: "analyze_javascript_application",
arguments: {
input_path: root,
format: "directory",
);
const server = createServer({ kind: "session", session }, { logger });
const client = new Client({
name: "javascript-cancellation",
version: "1",
});
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const controller = new AbortController();
let requested = false;
const call = client.callTool(
{
name: "analyze_javascript_application",
arguments: {
input_path: root,
format: "directory",
},
},
},
{
signal: controller.signal,
onprogress() {
requested = true;
controller.abort(new Error("SDK cancellation verification"));
{
signal: controller.signal,
onprogress(update) {
if (
!update.message?.startsWith(`${phase}:`) ||
!update.message.includes(message)
)
return;
requested = true;
controller.abort(new Error("SDK cancellation verification"));
},
},
},
);
await expect(call).rejects.toThrow("SDK cancellation verification");
expect(requested).toBe(true);
// A rejected client promise alone does not prove that the server stopped.
expect(await completed.promise).toBe("error");
await client.ping();
const bundle = await client.callTool({
name: "get_evidence_bundle",
arguments: {},
});
expect(
z
);
await expect(call).rejects.toThrow("SDK cancellation verification");
expect(requested).toBe(true);
// A rejected client promise alone does not prove that the server stopped.
expect(await completed.promise).toBe("error");
await client.ping();
const bundle = await client.callTool({
name: "get_evidence_bundle",
arguments: {},
});
const records = z
.object({
result: z.object({
records: z.array(z.object({ evidence_id: z.string() })),
}),
})
.parse(bundle.structuredContent).result.records,
).toEqual([{ evidence_id: prior.evidence_id }]);
const next = await client.callTool({
name: "analyze_javascript_application",
arguments: {
input_path: root,
format: "directory",
},
});
expect(next.isError, JSON.stringify(next)).not.toBe(true);
await client.ping();
});
.parse(bundle.structuredContent).result.records;
expect(records).toContainEqual({ evidence_id: prior.evidence_id });
const partial = records.find(
({ evidence_id }) => evidence_id !== prior.evidence_id,
);
if (partial === undefined)
throw new Error(
"Cancelled analysis discarded its completed source facts",
);
expect(
z
.object({
statistics: z.object({
parsed_javascript_files: z.number(),
parse_failures: z.number(),
}),
})
.parse(session.evidenceById(partial.evidence_id)?.normalized_result)
.statistics,
).toEqual({ parsed_javascript_files: parsedFiles, parse_failures: 0 });
const view = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "retained-evidence", evidence_id: partial.evidence_id },
view: { kind: "summary" },
},
});
expect(view.isError, JSON.stringify(view)).not.toBe(true);
const next = await client.callTool({
name: "analyze_javascript_application",
arguments: {
input_path: root,
format: "directory",
},
});
expect(next.isError, JSON.stringify(next)).not.toBe(true);
await client.ping();
},
);
@@ -0,0 +1,331 @@
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { expect, it } from "vitest";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("retains every static finding through public module views when application expansion exceeds memory, then accepts more work", async () => {
const root = await createTestTempDirectory("rea-js-resource-boundary-");
const nextRoot = await createTestTempDirectory("rea-js-resource-recovery-");
await writeFile(join(nextRoot, "main.js"), "export const recovered = 9;\n");
const source = Array.from(
{ length: 4000 },
(_, index) =>
`import { observed as binding${String(index)} } from "./target.js";`,
).join("\n");
const path = join(root, "main.js");
await writeFile(path, source);
await writeFile(join(root, "target.js"), "export const observed = 7;\n");
const digest = createHash("sha256").update(source).digest("hex");
const { client, transport, diagnostics } = createResourceClient();
try {
await client.connect(transport);
const response = await client.callTool(
{
name: "analyze_javascript_application",
arguments: {
input_path: root,
format: "directory",
max_heap_mb: 128,
detail: "summary",
},
},
{ timeout: 60000 },
);
expect(response.isError).not.toBe(true);
const summary = z
.object({
normalized_result: z.object({
parent_evidence_id: z.string(),
summary: z.object({
coverage: z.object({
application: z.object({ status: z.string() }),
}),
}),
}),
})
.parse(response.structuredContent).normalized_result;
expect(summary.summary.coverage.application.status).toBe("partial");
const retained = {
kind: "retained-evidence",
evidence_id: summary.parent_evidence_id,
};
const pageResponse = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: retained,
view: { kind: "page", collection: "modules", offset: 0, limit: 100 },
},
});
expect(pageResponse.isError).not.toBe(true);
const page = z
.object({
normalized_result: z.object({
items: z.array(
z.object({
node_id: z.string(),
kind: z.string(),
path: z.string().nullable(),
}),
),
}),
})
.parse(pageResponse.structuredContent).normalized_result;
const module = page.items.find(
(item) => item.kind === "javascript-asset" && item.path === "main.js",
);
if (module === undefined)
throw new Error("The analyzed file disappeared from public module views");
const itemResponse = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: retained,
view: {
kind: "item",
collection: "modules",
selector: { node_id: module.node_id },
},
},
});
expect(itemResponse.isError).not.toBe(true);
const item = z
.object({
normalized_result: z.object({
item: z.object({
identity: z.object({ sha256: z.string() }),
observations: z.array(
z.object({
properties: z.object({
static_analysis: z
.object({
parse_status: z.string(),
references: z.array(
z.object({
specifier: z.string(),
location: z.object({
start: z.object({ line: z.number() }),
}),
}),
),
})
.optional(),
}),
}),
),
}),
}),
})
.parse(itemResponse.structuredContent).normalized_result.item;
expect(item.identity.sha256).toBe(digest);
const facts = item.observations.find(
(observation) => observation.properties.static_analysis !== undefined,
)?.properties.static_analysis;
if (facts === undefined)
throw new Error("Completed static observations were discarded");
expect(facts.parse_status).toBe("complete");
expect(
facts.references.map((reference) => [
reference.specifier,
reference.location.start.line,
]),
).toEqual(
Array.from({ length: 4000 }, (_, index) => ["./target.js", index + 1]),
);
await client.ping();
const next = await client.callTool({
name: "analyze_javascript_application",
arguments: {
input_path: nextRoot,
format: "directory",
max_heap_mb: 128,
detail: "summary",
},
});
expect(next.isError).not.toBe(true);
await client.ping();
expect(
createHash("sha256")
.update(await readFile(path))
.digest("hex"),
).toBe(digest);
expect(diagnostics()).not.toMatch(/FATAL ERROR:.*heap/iu);
} finally {
await client.close();
await transport.close();
}
}, 90000);
it("returns a directly usable partial analysis reference for an oversized timeout observation", async () => {
const root = await createTestTempDirectory("rea-js-large-timeout-");
for (let offset = 0; offset < 1500; offset += 50)
await Promise.all(
Array.from({ length: 50 }, (_, index) =>
writeFile(
join(root, `file-${String(offset + index)}.js`),
"export const observed = 7;\n",
),
),
);
const nextRoot = await createTestTempDirectory("rea-js-timeout-recovery-");
await writeFile(join(nextRoot, "main.js"), "export const recovered = 9;\n");
const { client, transport, diagnostics } = createResourceClient();
try {
await client.connect(transport);
const response = await client.callTool(
{
name: "analyze_javascript_application",
arguments: {
input_path: root,
format: "directory",
max_heap_mb: 128,
analysis_timeout_ms: 1,
},
},
{ timeout: 60000 },
);
expect(response.isError).toBe(true);
const text = response.content.find((item) => item.type === "text");
if (text?.type !== "text")
throw new Error("Missing actionable timeout response");
const projected = z
.object({
error: z.object({
code: z.string(),
details: z.object({
partial_observation: z.object({
kind: z.literal("retained-evidence"),
evidence_id: z.string(),
}),
}),
}),
})
.parse(JSON.parse(text.text));
expect(projected.error.code).toBe("provider_timeout");
const summaryResponse = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: projected.error.details.partial_observation,
view: { kind: "summary" },
},
});
expect(summaryResponse.isError).not.toBe(true);
const summary = z
.object({
normalized_result: z.object({
summary: z.object({
statistics: z.object({
relevant_files: z.number(),
parsed_javascript_files: z.number(),
parse_failures: z.number(),
}),
coverage: z.object({ semantic_unknowns: z.number() }),
}),
}),
})
.parse(summaryResponse.structuredContent).normalized_result.summary;
expect(summary.statistics).toEqual({
relevant_files: 1500,
parsed_javascript_files: 0,
parse_failures: 0,
});
expect(summary.coverage.semantic_unknowns).toBeGreaterThan(1500);
await verifyRepeatedSourcePaths(
client,
projected.error.details.partial_observation,
);
await client.ping();
const next = await client.callTool({
name: "analyze_javascript_application",
arguments: {
input_path: nextRoot,
format: "directory",
max_heap_mb: 128,
detail: "summary",
},
});
expect(next.isError).not.toBe(true);
await client.ping();
expect(diagnostics()).not.toMatch(/FATAL ERROR:.*heap/iu);
} finally {
await client.close();
await transport.close();
}
}, 90000);
const createResourceClient = () => {
const client = new Client({ name: "javascript-resources", version: "1" });
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
cwd: process.cwd(),
env: {
PATH: process.env.PATH ?? "",
NODE_OPTIONS: "--max-old-space-size=512 --max-semi-space-size=8",
},
stderr: "pipe",
});
let diagnostics = "";
transport.stderr?.on("data", (chunk: Buffer) => {
if (diagnostics.length < 262144) diagnostics += chunk.toString();
});
return { client, transport, diagnostics: () => diagnostics };
};
const verifyRepeatedSourcePaths = async (
client: Client,
source: { readonly kind: "retained-evidence"; readonly evidence_id: string },
): Promise<void> => {
const page = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source,
view: { kind: "page", collection: "modules", offset: 0, limit: 4 },
},
});
expect(page.isError).not.toBe(true);
const modules = z
.object({
normalized_result: z.object({
items: z.array(z.object({ kind: z.string(), node_id: z.string() })),
}),
})
.parse(page.structuredContent);
const asset = modules.normalized_result.items.find(
({ kind }) => kind === "javascript-asset",
);
if (asset === undefined)
throw new Error(
"Identical source files disappeared from the retained graph",
);
const item = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source,
view: {
kind: "item",
collection: "modules",
selector: { node_id: asset.node_id },
},
},
});
expect(item.isError).not.toBe(true);
const observations = z
.object({
normalized_result: z.object({
item: z.object({
observations: z.array(z.object({ label: z.string() })),
}),
}),
})
.parse(item.structuredContent).normalized_result.item.observations;
expect(observations.map(({ label }) => label).sort()).toEqual(
Array.from(
{ length: 1500 },
(_, index) => `file-${String(index)}.js`,
).sort(),
);
};
@@ -1,4 +1,6 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished } from "vitest";
import { toolContract } from "../../../src/contracts/toolContracts.js";
@@ -10,9 +12,11 @@ import {
recoveryFixture,
} from "../../fixtures/javascript-recovery/provider.js";
it.skipIf(process.platform !== "linux" || process.arch !== "x64")(
"advertises and executes recovery through the named SDK contract without a binary target",
async () => {
it
.skipIf(process.platform !== "linux" || process.arch !== "x64")
.each([false, true])(
"advertises and executes recovery through the named SDK contract (multiple inputs: %s)",
async (multiple) => {
const fixture = await recoveryFixture();
const session = createTestBinarySession(() => {
throw new Error("no binary provider should start");
@@ -44,7 +48,13 @@ it.skipIf(process.platform !== "linux" || process.arch !== "x64")(
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const args = { path: fixture.path, output_directory: fixture.output };
const additional = join(fixture.root, "chunk.js");
if (multiple) await writeFile(additional, "export const chunk = 1;");
const args = {
path: fixture.path,
output_directory: fixture.output,
...(multiple ? { additional_paths: [additional] } : {}),
};
expect(ajv.validate(inputSchema, args)).toBe(true);
const response = await client.callTool({
name: "recover_javascript_sources",
@@ -0,0 +1,225 @@
import { Client } from "@modelcontextprotocol/client";
import { createPackageWithOptions } from "@electron/asar";
import { Ajv2020 } from "ajv/dist/2020.js";
import { rm } from "node:fs/promises";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { join, resolve } from "node:path";
import { expect, it } from "vitest";
import { z } from "zod";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { writeJavaScriptSourceSelectionFixture } from "../../fixtures/javascriptSourceSelection.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const createSelectionClient = () => {
const client = new Client({
name: "javascript-source-selection",
version: "1",
});
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
cwd: process.cwd(),
env: {
PATH: process.env.PATH ?? "",
NODE_OPTIONS: "--max-old-space-size=512 --max-semi-space-size=8",
},
stderr: "pipe",
});
return { client, transport };
};
it("advertises exact source selection and retains its scope through summary, Evidence retrieval and invalid-input recovery", async () => {
const root = await createTestTempDirectory("rea-js-selected-mcp-");
await writeJavaScriptSourceSelectionFixture(root);
const { client, transport } = createSelectionClient();
try {
await client.connect(transport);
const tools = await client.listTools();
const definition = tools.tools.find(
({ name }) => name === "analyze_javascript_application",
);
const schema = definition?.inputSchema;
if (schema === undefined)
throw new Error("Missing advertised application contract");
expect(schema.properties?.source_paths).toBeDefined();
const validate = new Ajv2020({
strict: false,
validateFormats: false,
}).compile(schema);
expect(validate({ input_path: root, source_paths: ["main.mjs"] })).toBe(
true,
);
for (const source_paths of [[], [""], [1]])
expect(validate({ input_path: root, source_paths })).toBe(false);
const selected = await client.callTool({
name: "analyze_javascript_application",
arguments: {
input_path: root,
source_paths: ["main.mjs", "package.json"],
detail: "summary",
},
});
expect(selected.isError, JSON.stringify(selected.content)).not.toBe(true);
if (definition?.outputSchema === undefined)
throw new Error("Missing advertised application output contract");
const validateOutput = new Ajv2020({
strict: false,
validateFormats: false,
}).compile(
z.record(z.string(), z.unknown()).parse(definition.outputSchema),
);
expect(
validateOutput(selected.structuredContent),
JSON.stringify(validateOutput.errors),
).toBe(true);
const summary = z
.object({
normalized_result: z.object({
parent_evidence_id: z.string(),
summary: z.object({
source_selection: z.object({
requested_paths: z.array(z.string()),
unselected_files: z.number(),
}),
coverage: z.object({
application: z.object({ status: z.string() }),
}),
}),
}),
})
.parse(selected.structuredContent).normalized_result;
expect(summary.summary.source_selection).toEqual({
requested_paths: ["main.mjs", "package.json"],
unselected_files: 4,
});
expect(summary.summary.coverage.application.status).toBe("partial");
const bundle = await client.callTool({
name: "get_evidence_bundle",
arguments: { detail: "complete" },
});
expect(bundle.isError).not.toBe(true);
const retained = z
.object({ result: z.object({ records: z.array(z.unknown()) }) })
.parse(bundle.structuredContent)
.result.records.map(parseEvidence)
.find(({ evidence_id }) => evidence_id === summary.parent_evidence_id);
expect(retained).toBeDefined();
const result = javascriptApplicationAnalysisResultSchema.parse(
retained!.normalized_result,
);
expect(result.statistics.parsed_javascript_files).toBe(1);
expect(result.source_selection).toEqual(summary.summary.source_selection);
expect(
result.semantic_graph.nodes.some(
({ kind, label }) => kind === "function" && label === "selected",
),
).toBe(true);
for (const source_paths of [
["missing.mjs"],
["./main.mjs"],
["../main.mjs"],
["*.mjs"],
]) {
const invalid = await client.callTool({
name: "analyze_javascript_application",
arguments: { input_path: root, source_paths },
});
expect(invalid.isError).toBe(true);
const text = invalid.content.find((item) => item.type === "text");
if (text?.type !== "text")
throw new Error("Missing source-selection correction");
expect(JSON.parse(text.text)).toMatchObject({
error: {
code: "invalid_request",
details: {
issues: [{ path: ["source_paths", 0], reason: "invalid_value" }],
},
},
});
await client.ping();
}
const next = await client.callTool({
name: "analyze_javascript_application",
arguments: { input_path: root, source_paths: ["main.mjs"] },
});
expect(next.isError).not.toBe(true);
expect(
javascriptApplicationAnalysisResultSchema.parse(
parseEvidence(next.structuredContent).normalized_result,
).statistics.parsed_javascript_files,
).toBe(1);
await client.ping();
} finally {
await client.close();
await transport.close();
}
}, 60_000);
it("selects nested ASAR paths and distinguishes missing inventoried bytes from invalid paths", async () => {
const root = await createTestTempDirectory("rea-js-selected-containers-");
await writeJavaScriptSourceSelectionFixture(root);
const { client, transport } = createSelectionClient();
try {
await client.connect(transport);
const nestedRoot = await createTestTempDirectory(
"rea-js-nested-selection-",
);
await createPackageWithOptions(root, join(nestedRoot, "nested.asar"), {});
const nested = await client.callTool({
name: "analyze_javascript_application",
arguments: {
input_path: nestedRoot,
source_paths: ["nested.asar/main.mjs"],
},
});
expect(nested.isError).not.toBe(true);
const nestedResult = javascriptApplicationAnalysisResultSchema.parse(
parseEvidence(nested.structuredContent).normalized_result,
);
expect(nestedResult.source_selection).toEqual({
requested_paths: ["nested.asar/main.mjs"],
unselected_files: 5,
});
expect(nestedResult.statistics).toMatchObject({
nested_asar_containers: 1,
parsed_javascript_files: 1,
parse_failures: 0,
});
expect(
nestedResult.semantic_graph.nodes.some(
({ identity, kind, label }) =>
identity.module_path === "nested.asar/main.mjs" &&
kind === "function" &&
label === "selected",
),
).toBe(true);
const unpacked = join(
await createTestTempDirectory("rea-js-unavailable-selection-"),
"app.asar",
);
await createPackageWithOptions(root, unpacked, { unpack: "main.mjs" });
await rm(join(unpacked + ".unpacked", "main.mjs"));
const unavailable = await client.callTool({
name: "analyze_javascript_application",
arguments: { input_path: unpacked, source_paths: ["main.mjs"] },
});
expect(unavailable.isError).toBe(true);
const unavailableText = unavailable.content.find(
(item) => item.type === "text",
);
if (unavailableText?.type !== "text")
throw new Error("Missing selected-source availability reason");
expect(JSON.parse(unavailableText.text)).toMatchObject({
error: {
code: "artifact_operation_failed",
details: { reason: "unavailable" },
},
});
await client.ping();
} finally {
await client.close();
await transport.close();
}
}, 60_000);
+185
View File
@@ -0,0 +1,185 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished } from "vitest";
import type { JebAnalysisPort } from "../../../src/application/jeb/JebAnalysisPort.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
const identity = { id: "jeb", name: "JEB", version: "5.48.0" } as const;
it("advertises exact valid JEB schemas and records inline evidence through MCP", async () => {
const execution = createAnalysisExecution(
{
engine: {
name: "jeb",
version: "5.48.0",
endpoint: "http://127.0.0.1:8425/mcp",
gui_client: false,
},
startup_ts: 1791623439,
message: null,
},
identity,
);
const provider: JebAnalysisPort = {
async inspectAvailability() {
return { status: "available", code: null, reason: null, diagnostics: {} };
},
async close() {},
async execute() {
return ok(execution);
},
};
const session = createTestBinarySession(() => {
throw new Error("deep provider must not start");
});
const server = createServer(
{ kind: "session", session },
{ jebAnalysis: provider },
);
const client = new Client({ name: "jeb-contract", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_jeb_client",
);
if (advertised?.inputSchema === undefined)
throw new Error("JEB tools must publish both schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
expect(ajv.validateSchema(advertised.inputSchema)).toBe(true);
const outputSchema: Record<string, unknown> = advertised.outputSchema ?? {};
expect(ajv.validateSchema(outputSchema)).toBe(true);
expect(ajv.validate(advertised.inputSchema, {})).toBe(true);
expect(ajv.validate(advertised.inputSchema, { unexpected: 1 })).toBe(false);
const called = await client.callTool({
name: "inspect_jeb_client",
arguments: {},
});
expect(called.isError).not.toBe(true);
const text = (called.content ?? [])
.map((block) => (block.type === "text" ? block.text : ""))
.join("");
const evidence = parseEvidence(JSON.parse(text));
expect(evidence.provider.id).toBe("jeb");
expect(evidence.normalized_result).toEqual(execution.result);
});
it("preserves JEB provider failure reasons through the MCP boundary", async () => {
const contract = toolContract("list_jeb_units");
const provider: JebAnalysisPort = {
async inspectAvailability() {
return { status: "available", code: null, reason: null, diagnostics: {} };
},
async close() {},
async execute() {
return ok(
createAnalysisExecution(
{ engine: null, units: [], coverage: "complete" } as never,
identity,
),
);
},
};
void contract;
const unavailable: JebAnalysisPort = {
...provider,
async execute() {
const { AnalysisCapabilityUnavailableError } =
await import("../../../src/domain/analysisErrorCore.js");
return {
ok: false as const,
error: new AnalysisCapabilityUnavailableError(
"jeb",
"list_jeb_units",
"connect ECONNREFUSED 127.0.0.1:8425",
{
userMessage:
"Start a JEB client serving MCP (default http://127.0.0.1:8425/mcp) or set REA_JEB_MCP_URL to the running endpoint.",
},
),
};
},
};
const session = createTestBinarySession(() => {
throw new Error("deep provider must not start");
});
const server = createServer(
{ kind: "session", session },
{ jebAnalysis: unavailable },
);
const client = new Client({ name: "jeb-failure", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const failed = await client.callTool({
name: "list_jeb_units",
arguments: {},
});
expect(failed.isError).toBe(true);
const text = (failed.content ?? [])
.map((block) => (block.type === "text" ? block.text : ""))
.join("");
expect(text).toContain("ECONNREFUSED");
expect(text).toContain("REA_JEB_MCP_URL");
});
it("keeps the MCP server usable when REA_JEB_MCP_URL is invalid", async () => {
const session = createTestBinarySession(() => {
throw new Error("deep provider must not start");
});
const server = createServer(
{ kind: "session", session },
{ environment: { REA_JEB_MCP_URL: "http://localhost:8425/mcp" } },
);
const client = new Client({ name: "jeb-invalid-endpoint", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
expect((await client.listTools()).tools.length).toBeGreaterThan(0);
const failed = await client.callTool({
name: "inspect_jeb_client",
arguments: {},
});
expect(failed.isError).toBe(true);
const text = (failed.content ?? [])
.map((block) => (block.type === "text" ? block.text : ""))
.join("");
expect(JSON.parse(text)).toMatchObject({
error: {
code: "configuration_invalid",
details: {
settings: [
{
setting: "REA_JEB_MCP_URL",
constraint: expect.stringContaining("loopback"),
},
],
},
},
});
});
@@ -0,0 +1,49 @@
import { expect } from "vitest";
import { z } from "zod";
import { createBinarySession } from "../../../src/composition/binary.js";
import { parseConfig } from "../../../src/config/parseConfig.js";
import { keyedArchiveResultSchema } from "../../../src/domain/apple/keyedArchive.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import {
expectKeyedArchivePrototypeKeys,
keyedArchivePrototypeKeyFixture,
} from "../../fixtures/keyedArchivePrototypeKeys.js";
import { mcpTest } from "../../support/mcp/mcpFixture.js";
mcpTest(
"MCP retains ordinary evidence with formatted XML prototype keys",
async ({ mcp, onTestFinished }) => {
const fixture = await keyedArchivePrototypeKeyFixture();
const configured = parseConfig({ REA_ANALYSIS_PROVIDER: "auto" });
if (!configured.ok) throw configured.error;
const session = createBinarySession(
configured.value,
silentLogger,
process.env,
);
onTestFinished(async () => {
await session.close();
});
const client = await mcp.connect(
createServer({ kind: "session", session }),
);
const opened = await client.callTool({
name: "open_binary",
arguments: { path: fixture.path },
});
expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true);
const result = await client.callTool({
name: "inspect_keyed_archive",
arguments: {},
});
expect(result.isError, JSON.stringify(result.content)).not.toBe(true);
expectKeyedArchivePrototypeKeys(
z
.object({ normalized_result: keyedArchiveResultSchema })
.parse(result.structuredContent).normalized_result,
fixture.digest,
);
},
);
+82
View File
@@ -29,8 +29,16 @@ it("runs every managed static inspection independently of an active native targe
);
const path = join(directory, "fixture.dll");
const otherPath = join(directory, "other-fixture.dll");
const partialPath = join(directory, "partial-method.dll");
await writeFile(path, buildManagedPeFixture());
await writeFile(otherPath, buildManagedPeFixture({ methodName: "Other" }));
await writeFile(
partialPath,
buildManagedPeFixture({
virtualSectionSize: 0x801,
ilBody: Buffer.from([0x06, 0x2a]),
}),
);
const session = composeBinarySession(new AnalysisProviderRegistry([]), [
new ManagedStaticProvider(),
]);
@@ -105,6 +113,7 @@ it("runs every managed static inspection independently of an active native targe
operation: "inspect_managed_members",
subject: { local_path: otherPath, format: "pe" },
});
await verifyManagedTypeSelection(client, path, otherPath);
const boundaries = structured(
await client.callTool({
name: "inspect_managed_native_boundaries",
@@ -116,6 +125,27 @@ it("runs every managed static inspection independently of an active native targe
provider: { id: "rea-dotnet-static" },
subject: { local_path: path, format: "pe" },
});
const partial = structured(
await client.callTool({
name: "inspect_managed_members",
arguments: { path: partialPath },
}),
);
expect(partial).toMatchObject({
subject: { local_path: partialPath, format: "pe" },
normalized_result: {
methods: [
{
body: {
status: "malformed",
normalized_il_sha256: null,
issue: "Method body leaves file-backed PE section data",
},
},
],
coverage: { state: "partial" },
},
});
} finally {
await Promise.all([client.close(), server.close()]);
await session.close();
@@ -416,6 +446,58 @@ const verifyImport = async (
});
};
/** Selected type names reach the provider and unmatched names stay visible. */
const verifyManagedTypeSelection = async (
client: Client,
path: string,
otherPath: string,
): Promise<void> => {
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_managed_members",
);
if (advertised === undefined) throw new Error("missing managed member tool");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
expect(ajv.validateSchema(advertised.inputSchema)).toBe(true);
const validate = ajv.compile(advertised.inputSchema);
expect(
validate({ path, type_names: ["Fixture.Program", "Missing.Type"] }),
).toBe(true);
expect(
validate({ path, type_names: ["Fixture.Program", "Fixture.Program"] }),
).toBe(false);
const selected = structured(
await client.callTool({
name: "inspect_managed_members",
arguments: { path, type_names: ["Fixture.Program", "Missing.Type"] },
}),
);
expect(selected).toMatchObject({
parameters: { path, type_names: ["Fixture.Program", "Missing.Type"] },
normalized_result: {
types: [expect.objectContaining({ full_name: "Fixture.Program" })],
methods: [expect.objectContaining({ declaring_type: "Fixture.Program" })],
selection: {
type_names: ["Fixture.Program", "Missing.Type"],
unmatched_type_names: ["Missing.Type"],
},
},
});
const repeatedSelection = await client.callTool({
name: "inspect_managed_members",
arguments: { path, type_names: ["Fixture.Program", "Fixture.Program"] },
});
expect(repeatedSelection.isError).toBe(true);
const reselectedOtherTarget = structured(
await client.callTool({
name: "inspect_managed_artifact",
arguments: { path: otherPath },
}),
);
expect(reselectedOtherTarget).toMatchObject({
subject: { local_path: otherPath, format: "pe" },
});
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (result.isError === true) return parseMcpToolError(result);
if (
+39
View File
@@ -0,0 +1,39 @@
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect } from "vitest";
import {
TOOL_CONTRACTS,
toolContract,
} from "../../../src/contracts/toolContracts.js";
type ToolName = (typeof TOOL_CONTRACTS)[number]["name"];
/** Advertised tool listing shape needed for contract validation. */
export interface AdvertisedMcpTool {
readonly name: string;
readonly inputSchema?: unknown;
}
/**
* Assert every named operation is advertised and its input schema compiles,
* accepts the contract's own examples, and rejects unknown input. The server
* may present a compacted form of the contract schema.
*/
export const assertAdvertisedMcpContracts = (
operationNames: readonly ToolName[],
tools: readonly AdvertisedMcpTool[],
): void => {
const ajv = new Ajv2020({ strict: false, allErrors: true });
for (const name of operationNames) {
const contract = toolContract(name);
const listed = tools.find((tool) => tool.name === name);
expect(listed, name).toBeTruthy();
if (listed?.inputSchema === undefined) continue;
const validate = ajv.compile(
JSON.parse(JSON.stringify(listed.inputSchema)),
);
for (const example of contract.examples)
expect(validate(example.input), `${name} example`).toBe(true);
expect(validate({ unknown_argument: true }), `${name} rejects`).toBe(false);
}
};
@@ -108,3 +108,42 @@ it("advertises and executes Android and Apple inventory projections", async () =
provider: { id: "rea-apple-application" },
});
});
it("retains Harmony unavailable components and their source Evidence through MCP", async () => {
const client = await connect();
const root = await createTestTempDirectory("rea-harmony-graph-mcp-");
const path = join(root, "Locked.hap");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("module.json", new TextReader("{}"));
await writer.add("ets/modules.abc", new TextReader("opaque bytecode"), {
password: "fixture-only",
});
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const reply = await client.callTool({
name: "project_harmony_application_graph",
arguments: { inventory_evidence: [inventory] },
});
if (reply.isError === true) throw new Error(JSON.stringify(reply));
const evidence = parseEvidence(reply.structuredContent);
expect(evidence.normalized_result).toMatchObject({
unavailable_components: [
expect.objectContaining({
path: "ets/modules.abc",
artifact_id: null,
sha256: null,
encrypted: true,
}),
],
coverage: { status: "partial", inventory_complete: true },
});
const bundle = await client.callTool({
name: "get_evidence_bundle",
arguments: {},
});
expect(bundle.structuredContent).toMatchObject({
result: { records: expect.arrayContaining([inventory, evidence]) },
});
});
@@ -7,57 +7,75 @@ import { NativeMacOSProvider } from "../../../src/native/NativeMacOSProvider.js"
import {
machoImage,
rpathCommand,
CPU,
fatImage,
} from "../../../src/artifacts/apple/MachoImage.fixture.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { NativeFixtureRunner } from "../../fixtures/nativeCommands.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
it("rejects changed signature targets through MCP and accepts reopening the new version", async () => {
const path = join(
await createTestTempDirectory("rea-signature-binding-mcp-"),
"program",
);
await writeFile(path, machoImage({}));
const session = createTestBinarySession(
new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin"),
);
const server = createServer({ kind: "session", session });
const client = new Client({ name: "signature-binding-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const open = () =>
client.callTool({ name: "open_binary", arguments: { path } });
expect((await open()).isError).not.toBe(true);
await writeFile(
path,
machoImage({ commands: [rpathCommand("new-version")] }),
it.each(["mach-o", "mach-o-universal"] as const)(
"rejects changed %s signature targets through MCP and accepts reopening the new version",
async (format) => {
const path = join(
await createTestTempDirectory("rea-signature-binding-mcp-"),
"program",
);
const changed = await client.callTool({
name: "inspect_signature",
arguments: {},
});
expect(changed.isError).toBe(true);
expect(parseMcpToolError(changed)).toMatchObject({
error: { code: "artifact_changed", details: { path } },
});
expect((await open()).isError).not.toBe(true);
const inspected = await client.callTool({
name: "inspect_signature",
arguments: {},
});
expect(
inspected.isError,
JSON.stringify(inspected.structuredContent),
).not.toBe(true);
expect(inspected.structuredContent).toMatchObject({
normalized_result: { signed: true, identifier: "com.example.fixture" },
});
} finally {
await client.close();
await server.close();
}
});
const image = (commands: readonly Uint8Array[] = []) =>
format === "mach-o"
? machoImage({ commands })
: fatImage(
[CPU.arm64, CPU.x86_64].map((cpu) => ({
cpu,
bytes: machoImage({ cpu, commands }),
})),
);
await writeFile(path, image());
const session = createTestBinarySession(
new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin"),
);
const server = createServer({ kind: "session", session });
const client = new Client({ name: "signature-binding-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const open = () =>
client.callTool({ name: "open_binary", arguments: { path } });
const opened = await open();
expect(opened.isError).not.toBe(true);
expect(
toolContract("open_binary").outputSchema.parse(opened.structuredContent)
.result,
).toMatchObject({ format });
await writeFile(path, image([rpathCommand("new-version")]));
const changed = await client.callTool({
name: "inspect_signature",
arguments: {},
});
expect(changed.isError).toBe(true);
expect(parseMcpToolError(changed)).toMatchObject({
error: { code: "artifact_changed", details: { path } },
});
expect((await open()).isError).not.toBe(true);
const inspected = await client.callTool({
name: "inspect_signature",
arguments: {},
});
expect(
inspected.isError,
JSON.stringify(inspected.structuredContent),
).not.toBe(true);
expect(inspected.structuredContent).toMatchObject({
subject: { format },
normalized_result: { signed: true, identifier: "com.example.fixture" },
});
} finally {
await client.close();
await server.close();
}
},
);
@@ -14,6 +14,7 @@ import {
TOOL_CONTRACTS,
toolContract,
} from "../../../src/contracts/toolContracts.js";
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { run } from "../../../src/main.js";
import { createServer } from "../../../src/server/createServer.js";
import { optionalObservationFactories } from "../../fixtures/optionalObservationProviders.js";
@@ -154,33 +155,37 @@ mcpTest.for(failedAdapters)(
name: "binary_session",
arguments: {},
});
expect(status.structuredContent).toMatchObject({
result: {
tool_availability: expect.arrayContaining([
expect.objectContaining({
name: operation,
available: false,
reason: "provider_unavailable",
remediation: expect.stringContaining(failure),
}),
expect.objectContaining({
name: "analyze_javascript_application",
available: true,
}),
expect.objectContaining({
name: "reconcile_javascript_runtime",
available: true,
}),
expect.objectContaining({
name:
port === "electronActiveObservation"
? "list_electron_targets"
: "capture_electron_scenario",
available: true,
}),
]),
},
});
const sessionStatus = toolContract("binary_session").outputSchema.parse(
status.structuredContent,
);
const availability = expandToolAvailability(
sessionStatus.result.tool_availability,
);
expect(availability).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: operation,
available: false,
reason: "provider_unavailable",
remediation: expect.stringContaining(failure),
}),
expect.objectContaining({
name: "analyze_javascript_application",
available: true,
}),
expect.objectContaining({
name: "reconcile_javascript_runtime",
available: true,
}),
expect.objectContaining({
name:
port === "electronActiveObservation"
? "list_electron_targets"
: "capture_electron_scenario",
available: true,
}),
]),
);
const healthy =
port === "javascriptRuntimeObservation"
? "list_browser_targets"
@@ -8,7 +8,11 @@ import { expect, it, onTestFinished } from "vitest";
import { compareProcessEvidenceFiles } from "../../../src/application/process/ProcessCli.js";
import { PROCESS_PROVIDER } from "../../../src/domain/process/processEvidenceProvider.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/domain/process/processCaptureExample.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import {
createEvidence,
parseEvidence,
type EvidenceProvider,
} from "../../../src/domain/evidence.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { digestProcessCommitment } from "../../../src/domain/process/processScenario.js";
import { createServer } from "../../../src/server/createServer.js";
@@ -18,8 +22,9 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const captureEvidence = (
side: "left" | "right",
comparisonContract: Readonly<Record<string, string>> = {},
provider: EvidenceProvider = PROCESS_PROVIDER,
) =>
createEvidence(undefined, PROCESS_PROVIDER, {
createEvidence(undefined, provider, {
predicateType: "rea.process-capture",
operation: "capture_process_scenario",
parameters: { side },
@@ -56,6 +61,118 @@ const connect = async () => {
return client;
};
const compareViaCli = async (
left: ReturnType<typeof captureEvidence>,
right: ReturnType<typeof captureEvidence>,
) => {
const root = await createTestTempDirectory("rea-process-provider-");
const leftPath = join(root, "left.json");
const rightPath = join(root, "right.json");
await Promise.all([
writeFile(leftPath, JSON.stringify(left)),
writeFile(rightPath, JSON.stringify(right)),
]);
return compareProcessEvidenceFiles(leftPath, rightPath);
};
it.each(
(["left", "right"] as const).flatMap((side) =>
[
{ id: "unrelated-provider" },
{ version: "1" },
{ name: "unrelated provider" },
].map((change) => ({ side, change })),
),
)(
"rejects an authenticated $side capture with provider $change",
async ({ side, change }) => {
const wrongProvider = captureEvidence(
side,
{},
{ ...PROCESS_PROVIDER, ...change },
);
expect(parseEvidence(wrongProvider)).toEqual(wrongProvider);
const left = side === "left" ? wrongProvider : captureEvidence("left");
const right = side === "right" ? wrongProvider : captureEvidence("right");
const issue = {
path: [side, "provider"],
reason: "invalid_value",
message: expect.stringContaining("process capture provider"),
};
expect(await compareViaCli(left, right)).toMatchObject({
category: "invalid_input",
details: { operation: "compare_process_captures", issues: [issue] },
});
const client = await connect();
const response = await client.callTool({
name: "compare_process_captures",
arguments: { left, right },
});
expect(response.isError).toBe(true);
expect(parseMcpToolError(response)).toMatchObject({
error: { code: "invalid_request", details: { issues: [issue] } },
});
await client.ping();
},
);
it.each([PROCESS_PROVIDER.name, "REA deterministic process harness"])(
"preserves authenticated CLI/MCP comparison Evidence for provider name %s",
async (name) => {
const provider = { ...PROCESS_PROVIDER, name };
const left = captureEvidence("left", {}, provider);
const right = captureEvidence("right", {}, provider);
const cli = parseEvidence(await compareViaCli(left, right));
const client = await connect();
const response = await client.callTool({
name: "compare_process_captures",
arguments: { left, right },
});
expect(response.isError).not.toBe(true);
expect(parseEvidence(response.structuredContent)).toEqual(cli);
const text = response.content.find((block) => block.type === "text");
expect(text?.type).toBe("text");
if (text?.type !== "text") throw new Error("Missing comparison text");
expect(JSON.parse(text.text)).toEqual(cli);
expect(cli.evidence_links).toEqual([left.evidence_id, right.evidence_id]);
},
);
it.each(["left", "right"] as const)(
"authenticates the %s Evidence before provider admission",
async (side) => {
const mismatched = captureEvidence(
side,
{},
{ ...PROCESS_PROVIDER, id: "unrelated-provider" },
);
const tampered = { ...mismatched, parameters: { side: "tampered" } };
const left = side === "left" ? tampered : captureEvidence("left");
const right = side === "right" ? tampered : captureEvidence("right");
expect(await compareViaCli(left, right)).toMatchObject({
category: "invalid_input",
details: {
issues: [
{
path: ["evidence_id"],
message: expect.stringContaining(
"Evidence semantic identifier does not match its record",
),
},
],
},
});
const client = await connect();
const response = await client.callTool({
name: "compare_process_captures",
arguments: { left, right },
});
expect(parseMcpToolError(response)).toMatchObject({
error: { code: "evidence_integrity_mismatch" },
});
},
);
it("names differing comparison contract fields through MCP and the CLI", async () => {
const client = await connect();
const response = await client.callTool({
@@ -91,6 +91,29 @@ const captureEvidence = (side: "left" | "right") =>
locations: [{ kind: "artifact-path", path: `/fixture/${side}` }],
});
const comparisonClient = async (
left: ReturnType<typeof captureEvidence>,
right: ReturnType<typeof captureEvidence>,
) => {
const session = createTestBinarySession(
(_path) =>
({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(resultOk(null)),
}) satisfies AnalysisClient,
);
expect(session.recordEvidence(left).ok).toBe(true);
expect(session.recordEvidence(right).ok).toBe(true);
const server = createServer({ kind: "session", session });
const client = new Client({ name: "trace-parity", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
return client;
};
afterEach(async () => {
await Promise.all(resources.splice(0).map((resource) => resource.close()));
await Promise.all(
@@ -117,22 +140,7 @@ describe("declared trace adapter parity", () => {
const cliEvidence = parseEvidence(
await compareProcessEvidenceFiles(leftPath, rightPath, specificationPath),
);
const session = createTestBinarySession(
(_path) =>
({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(resultOk(null)),
}) satisfies AnalysisClient,
);
expect(session.recordEvidence(left).ok).toBe(true);
expect(session.recordEvidence(right).ok).toBe(true);
const server = createServer({ kind: "session", session });
const client = new Client({ name: "trace-parity", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
const client = await comparisonClient(left, right);
const response = await client.callTool({
name: "compare_process_captures",
arguments: {
@@ -157,4 +165,54 @@ describe("declared trace adapter parity", () => {
{ kind: "artifact-path", path: "/fixture/right" },
]);
});
it("reports one complete missing-pair diagnostic through CLI and MCP", async () => {
const left = captureEvidence("left");
const right = captureEvidence("right");
const incompleteSpecification = {
events: Array.from({ length: 200 }, (_, index) => ({
id: `e${String(index)}`,
source: "lifecycle",
exact: { fixture: index },
cardinality: { kind: "optional" },
})),
language: { kind: "partial_order" },
};
const root = await createTestTempDirectory("rea-trace-diagnostics-");
temporaryRoots.push(root);
const leftPath = join(root, "left.json");
const rightPath = join(root, "right.json");
const specificationPath = join(root, "trace.json");
await Promise.all([
writeFile(leftPath, JSON.stringify(left)),
writeFile(rightPath, JSON.stringify(right)),
writeFile(specificationPath, JSON.stringify(incompleteSpecification)),
]);
const message =
"19900 event pairs must be explicitly ordered or unordered; first undeclared pair: e0/e1";
const cli = await compareProcessEvidenceFiles(
leftPath,
rightPath,
specificationPath,
);
expect(cli).toMatchObject({
category: "invalid_input",
details: {
issues: [{ path: ["trace_spec", "language"], message }],
},
});
const client = await comparisonClient(left, right);
const response = await client.callTool({
name: "compare_process_captures",
arguments: { left, right, trace_spec: incompleteSpecification },
});
expect(response.isError).toBe(true);
const text = response.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("\n");
expect(text).toContain(message);
expect(text.match(/first undeclared pair/g)).toHaveLength(1);
await client.ping();
});
});
+33 -9
View File
@@ -1,4 +1,5 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { setTimeout as delay } from "node:timers/promises";
import { describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
@@ -8,29 +9,52 @@ import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
describe("ordinary MCP progress and cancellation", () => {
it("emits bounded progress for a normal tool request", async () => {
it("advances MCP progress when provider waiting does not advance completed work", async () => {
const analysis: AnalysisOperationPort = {
execute: () => Promise.resolve(observed("0x1000")),
execute: async (_operation, _parameters, options) => {
for (const message of ["import pending", "analysis pending"]) {
await delay(120);
await options?.progress?.report({
phase: "ghidra_startup",
completed: 0,
total: null,
message,
});
}
return observed("0x1000");
},
};
const server = createServer({ kind: "fixed", analysis });
const client = new Client({ name: "progress-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const progress: number[] = [];
const progress: {
progress: number;
total?: number | undefined;
message?: string | undefined;
}[] = [];
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool(
{ name: "current_address", arguments: {} },
{ onprogress: (update) => progress.push(update.progress) },
{ onprogress: (update) => progress.push(update) },
);
expect(result.isError).not.toBe(true);
expect(progress[0]).toBe(0);
expect(progress.at(-1)).toBe(1);
progress.forEach((value, index) => {
expect(value).toBeGreaterThanOrEqual(progress[index - 1] ?? 0);
expect(value).toBeLessThanOrEqual(1);
expect(progress[0]?.progress).toBe(1);
expect(progress.map((update) => update.message)).toEqual(
expect.arrayContaining([
"ghidra_startup: import pending",
"ghidra_startup: analysis pending",
]),
);
expect(progress.at(-1)?.message).toContain("completed");
progress.forEach((update, index) => {
expect(update.progress).toBeGreaterThan(
progress[index - 1]?.progress ?? 0,
);
expect(update.total).toBeUndefined();
});
} finally {
await Promise.allSettled([client.close(), server.close()]);
+48 -24
View File
@@ -5,7 +5,11 @@ import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
import {
createAnalysisExecution,
type AnalysisClient,
} from "../../../src/application/AnalysisProvider.js";
import type { AnalysisProfileCommitment } from "../../../src/domain/analysisProfile.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { ARTIFACT_COMPARISON_EXAMPLE } from "../../../src/contracts/artifactComparisonExample.js";
import { PROCESS_CAPTURE_REFERENCE } from "../../../src/contracts/investigationExamples.js";
@@ -29,26 +33,33 @@ afterEach(async () => {
describe("guided prompt completion from live analysis", () => {
it("reads live documents and complete procedures without ambiguous names", async () => {
const requests: Array<Readonly<Record<string, unknown>>> = [];
const session = createTestBinarySession(() => client(requests), {
resolveAnalysisProfile: () =>
Promise.resolve(
resultOk({
profile: createAnalysisProfile(
{
id: "fixture",
name: "Fixture analysis provider",
version: "1",
},
{ fixture: true },
),
}),
),
});
const session = createTestBinarySession(
(_target, profile) => client(requests, profile),
{
resolveAnalysisProfile: () =>
Promise.resolve(
resultOk({
profile: createAnalysisProfile(
{
id: "fixture",
name: "Fixture analysis provider",
version: "1",
},
{ fixture: true },
),
}),
),
},
);
directory = await createTestTempDirectory("rea-prompt-completion-");
const target = join(directory, "fixture.hop");
await writeFile(target, "fixture");
expect((await session.open(target)).ok).toBe(true);
const completion = createPromptCompletionSource(session, session);
expect(await completion.complete("document", "app")).toEqual([]);
expect(await completion.complete("procedure", "")).toEqual([]);
const warmed = await session.execute("list_documents", {});
if (!warmed.ok) throw warmed.error;
expect(await completion.complete("document", "app")).toEqual([
"App",
@@ -269,14 +280,23 @@ const fixtureEnvironment = {
const client = (
requests: Array<Readonly<Record<string, unknown>>>,
): AnalysisClient => ({
execute(operation, parameters) {
analysisProfile?: AnalysisProfileCommitment,
): AnalysisClient => {
const observe = (value: unknown) =>
resultOk(
createAnalysisExecution(
value,
analysisProfile?.provider ?? fixtureProvider,
analysisProfile === undefined ? {} : { analysisProfile },
),
);
const execute: AnalysisClient["execute"] = (operation, parameters) => {
if (operation === "list_documents")
return Promise.resolve(observed(["AppTests", "App", "App"]));
return Promise.resolve(observe(["AppTests", "App", "App"]));
if (operation === "list_procedures") {
requests.push(parameters);
return Promise.resolve(
observed([
observe([
{ address: "0x1000", value: "duplicate" },
{ address: "0x2000", value: "unique" },
{ address: "0x3000", value: "duplicate" },
@@ -284,7 +304,11 @@ const client = (
]),
);
}
return Promise.resolve(observed(null));
},
close: () => Promise.resolve(resultOk(null)),
});
return Promise.resolve(observe(null));
};
return {
execute,
executeIfReady: execute,
close: () => Promise.resolve(resultOk(null)),
};
};
+287 -10
View File
@@ -11,7 +11,22 @@ import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
import {
createAnalysisExecution,
type AnalysisClient,
} from "../../../src/application/AnalysisProvider.js";
import type { JsonValue } from "../../../src/domain/jsonValue.js";
import type {
AnalysisProvider,
AnalysisProviderCandidate,
CapabilityDescriptor,
ProviderIdentity,
} from "../../../src/application/AnalysisProvider.js";
import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js";
import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
import { err, ok } from "../../../src/domain/result.js";
import {
createCacheProvider,
createTestBinarySession,
@@ -54,9 +69,11 @@ describe("guided prompts over MCP", () => {
completions: {},
prompts: { listChanged: true },
});
for (const [index, contract] of PROMPT_CONTRACTS.entries()) {
const advertised = prompts.prompts[index];
expect(advertised?.arguments).toEqual(
const advertisedByName = new Map(
prompts.prompts.map((prompt) => [prompt.name, prompt]),
);
for (const contract of PROMPT_CONTRACTS) {
expect(advertisedByName.get(contract.name)?.arguments).toEqual(
Object.entries(contract.arguments).map(
([name, { description, required }]) => ({
name,
@@ -271,15 +288,21 @@ describe("guided prompt completion registry", () => {
});
await connectPair(server, client);
resources.push(session);
expect((await client.listPrompts()).prompts[0]?.title).toBe(
"Investigate a feature",
const contract = PROMPT_CONTRACTS.find(
({ name }) => name === "investigate_feature",
);
if (contract === undefined)
throw new Error("Missing investigate_feature prompt contract");
const initialPrompt = (await client.listPrompts()).prompts.find(
({ name }) => name === contract.name,
);
expect(initialPrompt?.title).toBe(contract.title);
registry.update({
...PROMPT_CONTRACTS[0],
title: "Investigate a feature (updated)",
...contract,
title: `${contract.title} (updated)`,
arguments: {
...PROMPT_CONTRACTS[0].arguments,
...contract.arguments,
document: {
description: "Updated provider-backed selector",
required: false,
@@ -289,11 +312,74 @@ describe("guided prompt completion registry", () => {
});
await changed;
const prompts = await client.listPrompts();
expect(prompts.prompts[0]?.title).toBe("Investigate a feature (updated)");
expect(
prompts.prompts.find(({ name }) => name === contract.name)?.title,
).toBe(`${contract.title} (updated)`);
expect(await complete(client, "document", "fixture")).toEqual(["fixture"]);
});
});
it("guided prompt completion avoids cold startup and cancels warm lookup on close", async () => {
const directory = await createTestTempDirectory("rea-prompt-warm-only-");
temporaryDirectories.push(directory);
const target = join(directory, "target.hop");
await writeFile(target, "fixture target");
const fixture = await createWarmCompletionFixture(target);
const { client } = fixture;
const opened = await client.callTool({
name: "open_binary",
arguments: { path: target },
});
expect(opened.isError).not.toBe(true);
expect(fixture.childrenCreated()).toBe(0);
expect(await complete(client, "document", "")).toEqual([]);
expect(await complete(client, "procedure", "")).toEqual([]);
expect(fixture.childrenCreated()).toBe(0);
const startup = fixture.holdStartup();
const warming = client.callTool({ name: "list_documents", arguments: {} });
await startup.started;
expect(await complete(client, "document", "")).toEqual([]);
expect(await complete(client, "procedure", "")).toEqual([]);
expect(fixture.childrenCreated()).toBe(1);
startup.finish();
const warmed = await warming;
expect(warmed.isError, JSON.stringify(warmed)).not.toBe(true);
expect(fixture.childrenCreated()).toBe(1);
expect(await complete(client, "document", "fixture")).toEqual([
"fixture-document",
]);
const cancellation = fixture.holdCompletion();
const controller = new AbortController();
const cancelled = client.complete(
{
ref: { type: "ref/prompt", name: "investigate_feature" },
argument: { name: "document", value: "" },
},
{ signal: controller.signal },
);
await cancellation.started;
controller.abort();
await expect(cancelled).rejects.toThrow();
await cancellation.aborted;
const lifecycle = fixture.holdCompletion();
const pending = client.complete({
ref: { type: "ref/prompt", name: "investigate_feature" },
argument: { name: "document", value: "" },
});
await lifecycle.started;
const closed = await client.callTool({
name: "close_binary",
arguments: {},
});
expect(closed.isError).not.toBe(true);
await lifecycle.aborted;
expect((await pending).completion.values).toEqual([]);
}, 10_000);
describe("guided prompt completion lifecycle", () => {
it("survives a cancelled completion and ignores its late result", async () => {
let calls = 0;
@@ -400,6 +486,181 @@ describe("guided prompt completion lifecycle", () => {
}, 10_000);
});
const createWarmCompletionFixture = async (target: string) => {
const identity = {
id: "deep-fixture",
name: "Deep fixture provider",
version: "1",
};
const analysisProfile = createAnalysisProfile(identity, { fixture: true });
const observeCompletion = (result: JsonValue) =>
resultOk(createAnalysisExecution(result, identity, { analysisProfile }));
let childrenCreated = 0;
let ready = false;
let startupGate:
| {
readonly started: () => void;
readonly release: Promise<void>;
}
| undefined;
let completionGate:
| {
readonly started: () => void;
readonly aborted: () => void;
}
| undefined;
const deep = deepProvider(identity, {
createClient() {
childrenCreated += 1;
return {
execute: async (operation) => {
if (operation !== "health") {
const gate = startupGate;
if (gate !== undefined) {
startupGate = undefined;
gate.started();
await gate.release;
}
ready = true;
}
return observeCompletion(
operation === "list_documents"
? ["fixture-document"]
: operation === "list_procedures"
? [{ address: "0x1000", value: "fixture-procedure" }]
: null,
);
},
executeIfReady(operation, _parameters, options) {
if (
!ready ||
(operation !== "list_documents" && operation !== "list_procedures")
)
return Promise.resolve(undefined);
const gate = completionGate;
if (gate === undefined)
return Promise.resolve(
observeCompletion(
operation === "list_documents"
? ["fixture-document"]
: [{ address: "0x1000", value: "fixture-procedure" }],
),
);
completionGate = undefined;
gate.started();
return new Promise((resolve) => {
const signal = options?.signal;
const cancel = (): void => {
gate.aborted();
resolve(err(new AnalysisCancelledError(operation)));
};
if (signal?.aborted === true) cancel();
else signal?.addEventListener("abort", cancel, { once: true });
});
},
close: () => Promise.resolve(resultOk(null)),
};
},
});
const auxiliaryIdentity: ProviderIdentity = {
id: "aux-fixture",
name: "Aux fixture",
version: "1",
};
const auxiliary: AnalysisProvider = {
identity: () => auxiliaryIdentity,
capabilities: () => [
promptCapability(auxiliaryIdentity, "inspect_artifact"),
],
createClient: () => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(resultOk(null)),
}),
};
const session = composeBinarySession(new AnalysisProviderRegistry([deep]), [
auxiliary,
]);
const client = await connect(createServer({ kind: "session", session }));
resources.push(session);
return {
client,
childrenCreated: () => childrenCreated,
holdStartup: () => {
let started = (): void => undefined;
let finish = (): void => undefined;
const observedStart = new Promise<void>((resolve) => {
started = resolve;
});
const release = new Promise<void>((resolve) => {
finish = resolve;
});
startupGate = { started, release };
return { started: observedStart, finish };
},
holdCompletion: () => {
let started = (): void => undefined;
let aborted = (): void => undefined;
const observedStart = new Promise<void>((resolve) => {
started = resolve;
});
const observedAbort = new Promise<void>((resolve) => {
aborted = resolve;
});
completionGate = { started, aborted };
return { started: observedStart, aborted: observedAbort };
},
};
};
const deepProvider = (
identity: Parameters<typeof createAnalysisProfile>[0],
options: {
readonly createClient: AnalysisProviderCandidate["createClient"];
},
): AnalysisProviderCandidate => ({
identity: () => identity,
capabilities: () => [
promptCapability(identity, "list_documents"),
promptCapability(identity, "list_procedures"),
],
inspectAvailability: () => ({
status: "available",
code: null,
reason: null,
diagnostics: {},
}),
inspectTargetSupport: () => ({
status: "supported",
code: null,
reason: null,
diagnostics: {},
}),
resolveAnalysisProfile: async () =>
ok({ profile: createAnalysisProfile(identity, { fixture: true }) }),
createClient: options.createClient,
});
const promptCapability = (
provider: ProviderIdentity,
operation: CapabilityDescriptor["operation"],
): CapabilityDescriptor => ({
provider,
operation,
available: true,
reason: null,
cachePolicy: "live",
effects: {
mutatesArtifact: false,
launchesProcess: false,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
},
limitations: [],
});
const fixtureProvider = { id: "fixture", name: "Fixture", version: "1" };
const fixtureSession = (
@@ -451,6 +712,22 @@ const lifecycleClient = (
}
return Promise.resolve(observed(null));
},
executeIfReady(operation, parameters) {
if (operation === "list_documents")
return Promise.resolve(observed([`${target}-document`]));
if (operation === "list_procedures") {
requests.push(parameters);
return Promise.resolve(
observed([
{
address: target === "first" ? "0x1000" : "0x2000",
value: `${target}-procedure`,
},
]),
);
}
return Promise.resolve(undefined);
},
close: () => Promise.resolve(resultOk(null)),
});
+219
View File
@@ -0,0 +1,219 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished } from "vitest";
import { z } from "zod";
import { createServer } from "../../../src/server/createServer.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import type { AnalysisProvider } from "../../../src/application/AnalysisProvider.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { ok } from "../../../src/domain/result.js";
import { observed } from "../../fixtures/analysisExecution.js";
import {
createCacheProvider,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { silentLogger } from "../../../src/logger.js";
import type { CallToolResult } from "@modelcontextprotocol/server";
const connect = async (
provider: AnalysisProvider = createCacheProvider([]),
) => {
const session = createTestBinarySession(provider);
const server = createServer(
{ kind: "session", session },
{ logger: silentLogger },
);
const client = new Client({ name: "raw-binary-mcp", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
return { client, session };
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
)
throw new Error("missing structured result");
return z.record(z.string(), z.unknown()).parse(result.structuredContent);
};
it("opens a headerless image when architecture and entry are supplied", async () => {
const root = await createTestTempDirectory("rea-raw-mcp-");
const path = join(root, "ecu.bin");
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
const { client } = await connect();
const opened = await client.callTool({
name: "open_binary",
arguments: {
path,
format: "raw-binary",
architecture: "arm",
entry_point: "0x08000000",
},
});
expect(opened.isError).not.toBe(true);
expect(structured(opened).result).toMatchObject({
path,
format: "raw-binary",
kind: "executable",
architecture: "arm",
entry_point: "0x8000000",
});
});
it("rejects an unaligned AArch64 entry before selecting or starting a provider", async () => {
const root = await createTestTempDirectory("rea-raw-mcp-alignment-");
const path = join(root, "image.bin");
await writeFile(path, Buffer.from("c0035fd6", "hex"));
const { client, session } = await connect({
...createCacheProvider([]),
resolveAnalysisProfile: () => {
throw new Error("unaligned input must not select a provider");
},
createClient: () => {
throw new Error("unaligned input must not launch a provider");
},
});
const opened = await client.callTool({
name: "open_binary",
arguments: {
path,
format: "raw-binary",
architecture: "arm64",
entry_point: "0x8000001",
},
});
expect(opened.isError).toBe(true);
expect(JSON.stringify(opened.content)).toContain("must be 4-byte aligned");
expect(session.activeTarget()).toBeUndefined();
});
it("rejects raw-binary open requests that omit architecture", async () => {
const root = await createTestTempDirectory("rea-raw-mcp-missing-");
const path = join(root, "ecu.bin");
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
const { client } = await connect();
const opened = await client.callTool({
name: "open_binary",
arguments: { path, format: "raw-binary" },
});
expect(opened.isError).toBe(true);
});
it("reuses a canonical raw entry and replaces the session when the entry changes", async () => {
const root = await createTestTempDirectory("rea-raw-mcp-reopen-");
const path = join(root, "ecu.bin");
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
const fixture = createCacheProvider([]);
const resolved: string[] = [];
const created: string[] = [];
const closed: string[] = [];
const { client, session } = await connect({
...fixture,
resolveAnalysisProfile: (target) => {
if (target.format !== "raw-binary")
throw new Error("expected raw binary");
resolved.push(target.entryPoint);
return Promise.resolve(
ok({
profile: createAnalysisProfile(
{ ...fixture.identity(), version: "1" },
{
entry_point: target.entryPoint,
},
),
}),
);
},
createClient: (target) => {
if (target.format !== "raw-binary")
throw new Error("expected raw binary");
created.push(target.entryPoint);
return {
execute: (operation) => {
if (operation !== "health" && operation !== "address_name")
throw new Error(`unexpected fixture operation: ${operation}`);
return Promise.resolve(observed(target.entryPoint));
},
close: () => {
closed.push(target.entryPoint);
return Promise.resolve(ok(null));
},
};
},
});
const tools = (await client.listTools()).tools;
const validateLifecycle = (
name: "open_binary" | "binary_session",
response: CallToolResult,
) => {
const tool = tools.find((candidate) => candidate.name === name);
if (tool?.outputSchema === undefined)
throw new Error(`missing ${name} output schema`);
const schema = z.record(z.string(), z.unknown()).parse(tool.outputSchema);
const validate = new Ajv2020({
strict: false,
validateFormats: false,
}).compile(schema);
expect(
validate(response.structuredContent),
JSON.stringify(validate.errors),
).toBe(true);
const parsed = toolContract(name).outputSchema.parse(
response.structuredContent,
);
const target = z.record(z.string(), z.unknown()).parse(parsed.result);
const { entry_point: _entry, ...missingEntry } = target;
expect(validate({ ...structured(response), result: missingEntry })).toBe(
false,
);
return target;
};
for (const entryPoint of ["0x08000000", "0x8000000", "0x09000000"]) {
const opened = await client.callTool({
name: "open_binary",
arguments: {
path,
format: "raw-binary",
architecture: "arm",
entry_point: entryPoint,
},
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const canonical = `0x${BigInt(entryPoint).toString(16)}`;
expect(validateLifecycle("open_binary", opened).entry_point).toBe(
canonical,
);
const status = await client.callTool({
name: "binary_session",
arguments: {},
});
expect(status.isError, JSON.stringify(status)).not.toBe(true);
expect(validateLifecycle("binary_session", status).entry_point).toBe(
canonical,
);
const result = await client.callTool({
name: "address_name",
arguments: { address: entryPoint },
});
expect(result.isError, JSON.stringify(result)).not.toBe(true);
expect(structured(result).normalized_result).toBe(canonical);
}
expect(session.analysisProfile()?.parameters.entry_point).toBe("0x9000000");
expect(resolved).toEqual(["0x8000000", "0x9000000"]);
expect(created).toEqual(["0x8000000", "0x9000000"]);
expect(closed).toEqual(["0x8000000"]);
});
@@ -40,10 +40,6 @@ describe("reconstruction obligation ledger MCP parity", () => {
summary: { total: 0 },
},
});
expect(result.structuredContent).toHaveProperty(
"normalized_result.schema",
"ReconstructionObligationLedger",
);
} finally {
await client.close();
await server.close();
+57 -24
View File
@@ -15,6 +15,10 @@ import { CLI_COMMAND_NAMES } from "../../../src/cliCommandNames.js";
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 {
expandToolAvailability,
sessionProvider,
} from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { PROMPT_CONTRACTS } from "../../../src/contracts/promptContracts.js";
import { createServer } from "../../../src/server/createServer.js";
import { createServerIdentity } from "../../../src/serverIdentity.js";
@@ -70,20 +74,18 @@ const statusCapability = (
readonly reason: string;
} = { available: true },
) => ({
operation,
effects: {
mutates_artifact: false,
launches_process: false,
may_show_ui: false,
may_access_network: false,
may_write_filesystem: false,
changes_permissions: false,
requires_root: false,
},
limitations: [],
...(availability.available
? { available: true as const, reason: null, availability_code: null }
: availability),
provider: { id: "status-fixture", name: "Status fixture", version: null },
shared_limitations: [],
groups: [
{
operations: [operation],
effects: [],
limitations: [],
...(availability.available
? { available: true as const, reason: null, availability_code: null }
: availability),
},
],
});
describe("server and catalog identity", () => {
@@ -326,15 +328,10 @@ const activeTargetReasons = async (
name: "binary_session",
arguments: {},
});
const availability = z
.object({
result: z.object({
tool_availability: z.array(
z.object({ name: z.string(), reason: z.string() }).loose(),
),
}),
})
.parse(status.structuredContent).result.tool_availability;
const availability = expandToolAvailability(
z.object({ result: sessionProvider }).parse(status.structuredContent).result
.tool_availability,
);
return Object.fromEntries(
["inspect_macho", "inspect_artifact", "inspect_managed_artifact"].map(
(name) => [name, availability.find((tool) => tool.name === name)?.reason],
@@ -347,6 +344,32 @@ const assertLiveIdentity = async (client: Client): Promise<void> => {
name: "binary_session",
arguments: {},
});
const status = z
.object({ result: sessionProvider })
.parse(identity.structuredContent).result;
expect(Object.keys(status.server_identity.catalog).sort()).toEqual([
"counts",
"digests",
]);
const availability = expandToolAvailability(status.tool_availability);
expect(availability.map(({ name }) => name).sort()).toEqual(
TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
for (const contract of TOOL_CONTRACTS) {
expect(availability).toContainEqual(
expect.objectContaining({
name: contract.name,
surface: contract.kind,
effects: contract.effects,
annotations: {
read_only: contract.annotations.readOnlyHint ?? false,
destructive: contract.annotations.destructiveHint ?? false,
idempotent: contract.annotations.idempotentHint ?? false,
open_world: contract.annotations.openWorldHint ?? true,
},
}),
);
}
expect(identity.structuredContent).toMatchObject({
result: {
server_identity: {
@@ -370,7 +393,17 @@ const assertSessionIdentity = async (client: Client): Promise<void> => {
name: "binary_session",
arguments: { expected_package_version: "1.2.0" },
});
expect(status.structuredContent).toMatchObject({
const parsed = z
.object({ result: sessionProvider })
.parse(status.structuredContent);
expect({
result: {
...parsed.result,
tool_availability: expandToolAvailability(
parsed.result.tool_availability,
),
},
}).toMatchObject({
result: {
server_identity: {
catalog: {
+10 -9
View File
@@ -3,7 +3,6 @@ import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, expect, it } from "vitest";
import { z } from "zod";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import type {
@@ -12,8 +11,11 @@ import type {
} from "../../../src/application/AnalysisProvider.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import { createServer } from "../../../src/server/createServer.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { toolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import {
TOOL_CONTRACTS,
toolContract,
} from "../../../src/contracts/toolContracts.js";
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
const resources: Array<{ close(): Promise<void> }> = [];
@@ -65,7 +67,7 @@ it("executes a realistic workflow: list methods, decompile selected, get xrefs",
case "xrefs":
return Promise.resolve(ok(["0x1000"]));
default:
return Promise.resolve(ok(null));
throw new Error(`Unexpected analysis operation: ${name}`);
}
},
});
@@ -126,11 +128,10 @@ it("advertises the complete currently available inventory with a session", async
arguments: {},
}),
);
const inventory = z
.object({
result: z.object({ tool_availability: z.array(toolAvailability) }),
})
.parse(status).result.tool_availability;
const inventory = expandToolAvailability(
toolContract("binary_session").outputSchema.parse(status).result
.tool_availability,
);
for (const availability of inventory) {
if (availability.available) continue;
expect(availability.reason).not.toBe("available");
+8 -9
View File
@@ -26,6 +26,8 @@ import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { MAX_JSON_DEPTH } from "../../../src/domain/jsonValue.js";
import { parseAnalysisSnapshot } from "../../../src/domain/analysisSnapshot.js";
import { INVESTIGATION_EXAMPLES } from "../../../src/contracts/investigationExamples.js";
import { expandProviderCapabilities } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import {
createSessionMcpHarness,
@@ -279,7 +281,7 @@ describe("target-free MCP workflow", () => {
);
expect(
beforeTools.find(({ name }) => name === "inspect_artifact")?.description,
).toContain("Returns the complete content-addressed artifact graph");
).toMatch(/\breturns the complete content-addressed artifact graph\b/iu);
expect(beforeNames).toContain("open_binary");
expect(beforeNames).toContain("binary_session");
expect(beforeNames).toContain("current_document");
@@ -294,15 +296,12 @@ describe("target-free MCP workflow", () => {
expect(openedStatus).toMatchObject({
result: { path: await realpath(first) },
});
const sessionStatus =
toolContract("binary_session").outputSchema.parse(openedStatus);
expect(
z
.object({
result: z.object({
capabilities: z.array(z.object({ operation: z.string() })),
}),
})
.parse(openedStatus)
.result.capabilities.map(({ operation }) => operation),
expandProviderCapabilities(sessionStatus.result.capabilities).map(
({ operation }) => operation,
),
).not.toContain("inventory_artifact");
expect(
text(await mcp.callTool({ name: "current_document", arguments: {} })),
+18 -14
View File
@@ -50,6 +50,8 @@ const contract: ToolContract = {
accessesNetwork: false,
changesUiState: false,
mayDiscardData: false,
executesForeignCode: false,
mutatesDevice: false,
idempotent: true,
},
annotations: {
@@ -336,20 +338,22 @@ describe("tool result projection", () => {
const result = delivery.toCallToolResult(
err(
new HopperProcessError(80, {
component: "hopper_private_display",
operation: "launch",
status: "error",
failure_code: "x11_socket_directory_unusable",
reason: "socket_directory_read_only",
socket_directory: "/tmp/.X11-unix",
socket_directory_mode: "0777",
mount_read_only: true,
effective_socket_directory_mode: "1777",
effective_mount_read_only: false,
wsl: true,
strategy: "user-mount-namespace",
fallback_reason: null,
xvfb_stderr_bytes: 512,
diagnostic: {
component: "hopper_private_display",
operation: "launch",
status: "error",
failure_code: "x11_socket_directory_unusable",
reason: "socket_directory_read_only",
socket_directory: "/tmp/.X11-unix",
socket_directory_mode: "0777",
mount_read_only: true,
effective_socket_directory_mode: "1777",
effective_mount_read_only: false,
wsl: true,
strategy: "user-mount-namespace",
fallback_reason: null,
xvfb_stderr_bytes: 512,
},
}),
),
contract,
+190 -5
View File
@@ -4,6 +4,7 @@ import { Ajv2020 } from "ajv/dist/2020.js";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { advertisedInputExamples } from "../../../src/contracts/advertisedInputExamples.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { emptyArraySchema } from "../../../src/domain/emptyArraySchema.js";
import { processScenarioSchema } from "../../../src/domain/process/processScenario.js";
@@ -18,13 +19,30 @@ interface ToolSchemas {
}
function schemaErrors(tools: readonly ToolSchemas[]): string[] {
const ajv = new Ajv2020({ strict: false, validateFormats: false });
// Reuse Ajv's meta-schema validators, then clear each root's reference
// namespace, including nested IDs, before validating the next schema.
const ajv = new Ajv2020({
strict: false,
validateFormats: false,
addUsedSchema: false,
});
return tools.flatMap((tool) =>
["inputSchema", "outputSchema"].flatMap((kind) => {
const schema =
kind === "inputSchema" ? tool.inputSchema : tool.outputSchema;
if (schema === undefined || ajv.validateSchema(schema)) return [];
return [`${tool.name}.${kind}: ${ajv.errorsText(ajv.errors)}`];
if (schema === undefined) return [];
try {
if (!ajv.validateSchema(schema))
return [`${tool.name}.${kind}: ${ajv.errorsText(ajv.errors)}`];
ajv.compile(schema);
return [];
} catch (cause: unknown) {
return [
`${tool.name}.${kind}: ${cause instanceof Error ? cause.message : String(cause)}`,
];
} finally {
ajv.removeSchema();
}
}),
);
}
@@ -72,7 +90,7 @@ function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
},
annotate_native_function: {
readOnlyHint: false,
destructiveHint: false,
destructiveHint: true,
idempotentHint: true,
openWorldHint: true,
},
@@ -101,8 +119,22 @@ function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
openWorldHint: false,
},
capture_process_scenario: {
readOnlyHint: false,
destructiveHint: true,
openWorldHint: true,
},
observe_native_calls: {
readOnlyHint: false,
destructiveHint: true,
},
uninstall_adb_package: {
readOnlyHint: false,
destructiveHint: true,
},
start_adb_app: {
readOnlyHint: false,
destructiveHint: true,
},
export_evidence_bundle: {
readOnlyHint: false,
destructiveHint: true,
@@ -353,8 +385,9 @@ describe("MCP JSON Schema validity", () => {
const tool = byName.get(contract.name);
expect(tool?.title?.trim(), contract.name).toBeTruthy();
expect(tool?.description?.trim(), contract.name).toBeTruthy();
const examples = advertisedInputExamples(contract);
expect(tool?.inputSchema.examples, contract.name).toEqual(
contract.examples.map(({ input }) => input),
examples.length === 0 ? undefined : examples,
);
for (const example of contract.examples)
expect(
@@ -458,6 +491,95 @@ it(
advertiseAndEnforceProcessEnvironmentKeyConstraint,
);
const advertiseAndEnforceItemSelectorCollectionConstraints =
async (): Promise<void> => {
const contract = TOOL_CONTRACTS.find(
({ name }) => name === "inspect_analysis_view",
);
if (contract === undefined)
throw new Error("inspect_analysis_view contract was not registered");
const server = new McpServer({
name: "item-selector-schema",
version: "0",
});
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async () => ({
content: [],
}),
);
const client = new Client({ name: "item-selector-schema", version: "0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = (await client.listTools()).tools.find(
({ name }) => name === contract.name,
);
if (advertised === undefined)
throw new Error("inspect_analysis_view tool was not advertised");
const validate = new Ajv2020({
strict: false,
validateFormats: false,
}).compile(advertised.inputSchema);
const source = {
kind: "retained-evidence",
evidence_id: `ev_${"a".repeat(64)}`,
};
const itemInput = (collection: string, selector: unknown) => ({
source,
view: { kind: "item", collection, selector },
});
const nodeId = `jag_node_${"b".repeat(64)}`;
// Collection-specific selector constraints must survive JSON Schema
// conversion: the advertised schema rejects exactly what runtime
// input validation rejects.
const invalid: ReadonlyArray<readonly [string, unknown]> = [
["modules", { index: 0 }],
["modules", { name: "entry" }],
["sections", { path: "/src/entry.js" }],
["symbols", { node_id: nodeId }],
];
const valid: ReadonlyArray<readonly [string, unknown]> = [
["modules", { path: "/src/entry.js" }],
["modules", { node_id: nodeId }],
["sections", { index: 0 }],
["sections", { name: ".text" }],
["symbols", { index: 0 }],
["symbols", { name: "main" }],
];
for (const [collection, selector] of invalid) {
const input = itemInput(collection, selector);
const label = `${collection}/${Object.keys(selector as object)[0]}`;
expect(contract.inputSchema.safeParse(input).success, label).toBe(
false,
);
expect(validate(input), `advertised schema rejects ${label}`).toBe(
false,
);
}
for (const [collection, selector] of valid) {
const input = itemInput(collection, selector);
const label = `${collection}/${Object.keys(selector as object)[0]}`;
expect(contract.inputSchema.safeParse(input).success, label).toBe(true);
expect(validate(input), `advertised schema accepts ${label}`).toBe(
true,
);
}
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
};
it(
"advertises and enforces the item selector collection constraints",
advertiseAndEnforceItemSelectorCollectionConstraints,
);
describe("MCP process input JSON Schema", () => {
it("advertises process strings without weakening terminal input", async () => {
const server = new McpServer({
@@ -523,6 +645,69 @@ it("ships nonrecursive input and output schemas in the generated catalog", () =>
expect(recursiveReferences(GENERATED_MCP_TOOL_CATALOG)).toEqual([]);
});
it("rejects unresolved output-schema references even for uncalled tools", () => {
const errors = schemaErrors([
{
name: "dangling",
inputSchema: { type: "object" },
outputSchema: { $ref: "#/$defs/missing" },
},
]);
expect(errors).toHaveLength(1);
expect(errors[0]).toContain("dangling.outputSchema");
});
it("validates each tool independently when output schema IDs repeat", () => {
const outputSchema = { $id: "urn:rea:test:shared-output", type: "string" };
const errors = schemaErrors([
{ name: "first", inputSchema: { type: "object" }, outputSchema },
{
name: "second",
inputSchema: { type: "object" },
outputSchema: { ...outputSchema },
},
{
name: "broken",
inputSchema: { type: "object" },
outputSchema: { $id: outputSchema.$id, $ref: "#/$defs/missing" },
},
]);
expect(errors).toHaveLength(1);
expect(errors[0]).toContain("broken.outputSchema");
expect(errors[0]).toContain("missing");
});
it.each([false, true])(
"rejects references to another tool's nested IDs (earlier compilation fails: %s)",
(invalidPrevious) => {
const nestedId = "urn:rea:test:nested-output";
const errors = schemaErrors([
{
name: "first",
inputSchema: { type: "object" },
outputSchema: {
$defs: { shared: { $id: nestedId, type: "string" } },
...(invalidPrevious ? { pattern: "[" } : {}),
},
},
{
name: "broken",
inputSchema: { type: "object" },
outputSchema: {
$ref: nestedId,
$defs: { shared: { type: "number" } },
},
},
]);
expect(errors).toHaveLength(invalidPrevious ? 2 : 1);
const brokenErrors = errors.filter((error) =>
error.startsWith("broken.outputSchema:"),
);
expect(brokenErrors).toHaveLength(1);
expect(brokenErrors[0]).toContain(nestedId);
},
);
it("distinguishes recursive references from shared definitions", () => {
const diamond = {
type: "object",
+499
View File
@@ -0,0 +1,499 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished, vi } from "vitest";
import { readFile, realpath, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { WasmArtifactService } from "../../../src/application/wasm/WasmArtifactService.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { wasmArtifactSummaryViewResultSchema } from "../../../src/domain/analysisView/analysisView.js";
import { createHash } from "node:crypto";
import { z } from "zod";
import { createServer } from "../../../src/server/createServer.js";
import { ok } from "../../../src/domain/result.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import {
wasmArtifactFixture,
wasmArtifactExecution,
} from "../../fixtures/wasm/artifact.js";
const wasmToolSchemas = async (client: Client) => {
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_wasm_artifact",
);
if (advertised?.outputSchema === undefined)
throw new Error("WASM recovery must name an advertised static tool");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
return { name: advertised.name, ajv, inputSchema, outputSchema };
};
const assertFirstSummaryDelivery = async (
harness: Awaited<ReturnType<typeof createApplicationMcpHarness>>,
value: ReturnType<typeof wasmArtifactFixture>,
inspect: WasmArtifactService["provider"]["inspect"],
) => {
const {
ajv: wasmAjv,
inputSchema,
outputSchema,
} = await wasmToolSchemas(harness.client);
const summaryInput = { path: value.artifact.path, detail: "summary" };
expect(wasmAjv.validate(inputSchema, summaryInput)).toBe(true);
expect(
wasmAjv.validate(inputSchema, { ...summaryInput, detail: "brief" }),
).toBe(false);
const directSummary = await harness.client.callTool({
name: "inspect_wasm_artifact",
arguments: summaryInput,
});
expect(directSummary.isError).not.toBe(true);
expect(
wasmAjv.validate(outputSchema, directSummary.structuredContent),
JSON.stringify(wasmAjv.errors),
).toBe(true);
const summaryEvidence = parseEvidence(directSummary.structuredContent);
const summary = wasmArtifactSummaryViewResultSchema.parse(
summaryEvidence.normalized_result,
);
expect(summaryEvidence.confidence).toBe("derived");
expect(summaryEvidence.evidence_links).toEqual([summary.parent_evidence_id]);
expect(summary.summary.wat).toMatchObject({
sha256: value.wat.sha256,
code_units: value.wat.text.length,
});
expect(summary.summary.wat).not.toHaveProperty("text");
const retained = harness.session.evidenceById(summary.parent_evidence_id);
if (retained === undefined) throw new Error("Summary lost original Evidence");
expect(retained.normalized_result).toEqual(value);
expect(retained.parameters).toEqual({
path: value.artifact.path,
glue_paths: [],
candidate_paths: [],
});
expect(inspect).toHaveBeenCalledTimes(1);
expect(inspect).toHaveBeenLastCalledWith(
retained.parameters,
expect.objectContaining({ signal: expect.any(AbortSignal) }),
);
expect(
wasmAjv.validate(outputSchema, {
...summaryEvidence,
normalized_result: { ...summary, parent_operation: "inventory_artifact" },
}),
).toBe(false);
return { summary, retained };
};
it("directs rejected native WASM opening to the advertised static tool while preserving missing-WABT diagnostics", async () => {
const directory = await createTestTempDirectory("rea-wasm-recovery-");
const path = join(
await realpath(directory),
process.platform === "win32" ? "module space.bin" : 'module "quoted".bin',
);
await writeFile(path, Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]));
const createClient = vi.fn(() => {
throw new Error("native provider must not start for WASM");
});
const session = createTestBinarySession(createClient);
const harness = await createApplicationMcpHarness({
session,
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const { client } = harness;
const { name, ajv, inputSchema } = await wasmToolSchemas(client);
const input = { path };
expect(
toolContract("inspect_wasm_artifact").inputSchema.safeParse(input).success,
).toBe(true);
const opening = await client.callTool({
name: "open_binary",
arguments: input,
});
expect(opening.isError).toBe(true);
const failure = parseMcpToolError(opening);
expect(failure).toMatchObject({
error: {
code: "target_unavailable",
category: "unsupported_target",
details: { constraint: "wasm_requires_static_inspection" },
},
});
expect(failure.error.remediation.action).toContain(JSON.stringify({ path }));
expect(ajv.validate(inputSchema, input)).toBe(true);
const inspection = await client.callTool({
name,
arguments: input,
});
expect(inspection.isError).toBe(true);
expect(parseMcpToolError(inspection)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: "inspect_wasm_artifact",
reason: expect.stringContaining("REA_WABT_BIN_DIRECTORY"),
},
},
});
const summary = await client.callTool({
name,
arguments: { ...input, detail: "summary" },
});
expect(parseMcpToolError(summary)).toMatchObject({
error: {
code: "capability_unavailable",
details: { reason: expect.stringContaining("REA_WABT_BIN_DIRECTORY") },
},
});
await client.ping();
expect(createClient).not.toHaveBeenCalled();
expect(await readFile(path)).toEqual(
Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]),
);
});
it("advertises exact valid schemas and records inline WASM interface evidence without a binary target", async () => {
const value = wasmArtifactFixture();
const close = vi.fn(() => Promise.resolve());
const service = new WasmArtifactService({
close,
inspect: () => Promise.resolve(ok(wasmArtifactExecution(value))),
});
const session = createTestBinarySession(() => {
throw new Error("deep provider must not start");
});
const harness = await createApplicationMcpHarness({
session,
serverOptions: { wasmArtifact: service },
});
onTestFinished(harness.close);
const { client } = harness;
const { ajv, inputSchema, outputSchema } = await wasmToolSchemas(client);
expect(ajv.validate(inputSchema, { path: value.artifact.path })).toBe(true);
expect(
ajv.validate(inputSchema, {
path: value.artifact.path,
approval: true,
}),
).toBe(false);
const response = await client.callTool({
name: "inspect_wasm_artifact",
arguments: { path: value.artifact.path },
});
expect(response.isError).not.toBe(true);
expect(
ajv.validate(outputSchema, response.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const parsed = toolContract("inspect_wasm_artifact").outputSchema.parse(
response.structuredContent,
);
const evidence = parseEvidence(parsed);
expect(evidence.confidence).toBe("observed");
expect(evidence.subject?.digest.sha256).toBe(value.artifact.sha256);
expect(parsed.normalized_result).toEqual(value);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
expect(
(
await client.callTool({
name: "inspect_wasm_artifact",
arguments: { path: "relative.hex" },
})
).isError,
).toBe(true);
await harness.close();
expect(close).toHaveBeenCalled();
});
it("reads an oversized completed WASM result through its reported retained reference", async () => {
const text = "(module)\n" + ";;😀\n" + " ".repeat(6 * 1024 * 1024);
const value = {
...wasmArtifactFixture(),
imports: ['(import "env" "memory.with punctuation" (memory 1))'],
exports: ['(export "first" (func 0))', '(export "second" (func 1))'],
wat: {
text,
sha256: createHash("sha256").update(text, "utf8").digest("hex"),
representation: "decoded-wat" as const,
},
};
const inspect = vi.fn(() =>
Promise.resolve(ok(wasmArtifactExecution(value))),
);
const service = new WasmArtifactService({
close: () => Promise.resolve(),
inspect,
});
const harness = await createApplicationMcpHarness({
serverOptions: { wasmArtifact: service },
});
onTestFinished(harness.close);
const { summary, retained } = await assertFirstSummaryDelivery(
harness,
value,
inspect,
);
const reply = await harness.client.callTool({
name: "inspect_wasm_artifact",
arguments: { path: value.artifact.path },
});
const reference = z
.object({
details: z.object({
reported_limits: z.object({
evidence_reference: z.object({
kind: z.literal("retained-evidence"),
evidence_id: z.string(),
}),
}),
}),
})
.parse(parseMcpToolError(reply).error).details
.reported_limits.evidence_reference;
expect(reference.evidence_id).toBe(summary.parent_evidence_id);
const explicitComplete = await harness.client.callTool({
name: "inspect_wasm_artifact",
arguments: { path: value.artifact.path, detail: "complete" },
});
expect(parseMcpToolError(explicitComplete)).toMatchObject({
error: {
code: "resource_constraint",
details: { reported_limits: { evidence_reference: reference } },
},
});
const catalog = await harness.client.listTools();
const advertised = catalog.tools.find(
(tool) => tool.name === "inspect_analysis_view",
);
if (advertised?.outputSchema === undefined)
throw new Error("Missing WASM view schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const input: Record<string, unknown> = advertised.inputSchema;
const output: Record<string, unknown> = advertised.outputSchema;
for (const [view, expected] of [
[
{ kind: "summary" },
{
summary: {
validation: "valid",
available_counts: { imports: 1, exports: 2 },
runtime_execution: "not-performed",
network_fetch: "not-performed",
wat: { sha256: value.wat.sha256, code_units: text.length },
},
},
],
[
{ kind: "wasm", facet: "exports", offset: 1, limit: 1 },
{
item: [value.exports[1]],
coverage: { total: 2, next_offset: null, exhausted: true },
},
],
[{ kind: "wasm", facet: "imports" }, { item: value.imports }],
[
{ kind: "wasm", facet: "wat", offset: 0, limit: 16 },
{
item: { text: text.slice(0, 16), unit: "utf16-code-units" },
coverage: { total: text.length, next_offset: 16, exhausted: false },
},
],
] as const) {
const args = { source: reference, view };
expect(ajv.validate(input, args), JSON.stringify(ajv.errors)).toBe(true);
const selected = await harness.client.callTool({
name: "inspect_analysis_view",
arguments: args,
});
expect(
selected.isError,
JSON.stringify(selected.structuredContent),
).not.toBe(true);
expect(
ajv.validate(output, selected.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const evidence = parseEvidence(selected.structuredContent);
expect(evidence.confidence).toBe("derived");
expect(evidence.evidence_links).toEqual([reference.evidence_id]);
expect(evidence.normalized_result).toMatchObject({
parent_evidence_id: reference.evidence_id,
...expected,
});
}
const original = harness.session.evidenceById(reference.evidence_id);
expect(original?.normalized_result).toEqual(value);
expect(original).toEqual(retained);
expect(inspect).toHaveBeenCalledTimes(3);
await harness.client.ping();
});
it("rejects inconsistent decoded-WAT digests in portable Evidence without a provider run", async () => {
const value = wasmArtifactFixture();
const harness = await createApplicationMcpHarness({
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const inconsistent = createEvidence(
{
path: value.artifact.path,
sha256: value.artifact.sha256,
format: "file",
},
{ id: "historical-wabt", name: "Historical WABT", version: "1" },
{
operation: "inspect_wasm_artifact",
parameters: {},
result: { ...value, wat: { ...value.wat, sha256: "f".repeat(64) } },
},
);
const invalid = await harness.client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "inline", evidence: inconsistent },
view: { kind: "summary" },
},
});
expect(parseMcpToolError(invalid)).toMatchObject({
error: {
code: "invalid_request",
details: {
issues: [
{
path: ["source", "normalized_result", "wat", "sha256"],
reason: "invalid_value",
},
],
},
},
});
await harness.client.ping();
});
it("rejects absent or inconsistent WASM source identity before deriving portable views", async () => {
const value = wasmArtifactFixture();
const harness = await createApplicationMcpHarness({
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
for (const target of [
undefined,
{
path: `${value.artifact.path}.other`,
sha256: value.artifact.sha256,
format: "file" as const,
},
{
path: value.artifact.path,
sha256: "f".repeat(64),
format: "file" as const,
},
]) {
const source = createEvidence(
target,
{ id: "historical-wabt", name: "Historical WABT", version: "1" },
{ operation: "inspect_wasm_artifact", parameters: {}, result: value },
);
for (const view of [
{ kind: "summary" },
{ kind: "wasm", facet: "exports", offset: 0, limit: 1 },
]) {
const reply = await harness.client.callTool({
name: "inspect_analysis_view",
arguments: { source: { kind: "inline", evidence: source }, view },
});
expect(parseMcpToolError(reply)).toMatchObject({
error: {
code: "invalid_request",
details: {
issues: [{ path: ["source", "subject"], reason: "invalid_value" }],
},
},
});
}
}
await harness.client.ping();
});
it("requires retention for WASM summary delivery while keeping fixed-server complete delivery", async () => {
const value = wasmArtifactFixture();
const service = new WasmArtifactService({
close: () => Promise.resolve(),
inspect: () => Promise.resolve(ok(wasmArtifactExecution(value))),
});
const session = createTestBinarySession(() => {
throw new Error("No deep provider");
});
const server = createServer(
{ kind: "fixed", analysis: session },
{ wasmArtifact: service },
);
const client = new Client({ name: "wasm-fixed-delivery", version: "1" });
const [a, b] = InMemoryTransport.createLinkedPair();
try {
await server.connect(b);
await client.connect(a);
const summary = await client.callTool({
name: "inspect_wasm_artifact",
arguments: { path: value.artifact.path, detail: "summary" },
});
expect(parseMcpToolError(summary)).toMatchObject({
error: {
code: "capability_unavailable",
message: expect.stringContaining("does not retain Evidence"),
},
});
const complete = await client.callTool({
name: "inspect_wasm_artifact",
arguments: { path: value.artifact.path },
});
expect(complete.isError).not.toBe(true);
expect(parseEvidence(complete.structuredContent).normalized_result).toEqual(
value,
);
await client.ping();
} finally {
await client.close();
await server.close();
await session.close();
}
});
it("retries cleanup of the injected WASM module after server shutdown fails", async () => {
const close = vi
.fn()
.mockRejectedValueOnce(new Error("retained WASM workspace"))
.mockResolvedValue(undefined);
const service = new WasmArtifactService({
close,
inspect: () => Promise.resolve(ok(wasmArtifactExecution())),
});
const session = createTestBinarySession(() => {
throw new Error("No deep provider");
});
const server = createServer(
{ kind: "session", session },
{ wasmArtifact: service },
);
const client = new Client({ name: "wasm-cleanup-retry", version: "1" });
const [a, b] = InMemoryTransport.createLinkedPair();
try {
await server.connect(b);
await client.connect(a);
await expect(server.close()).rejects.toThrow("REA session cleanup failed");
await server.close();
expect(close).toHaveBeenCalledTimes(2);
} finally {
await client.close();
await server.close();
await session.close();
}
});
@@ -81,3 +81,32 @@ it("publishes valid SDK schemas and records the named module trace without a bin
});
expect(invalid.isError).toBe(true);
});
it("retains the module resolver cleanup owner across failed server shutdown", async () => {
let closes = 0;
const service = new WebModuleTraceService(
{ load: () => Promise.resolve(ok(webModuleArtifactsFixture())) },
{
...webModuleResolverFixture,
close: async () => {
closes += 1;
if (closes === 1) throw new Error("fixture browser close failed");
},
},
);
const session = createTestBinarySession(() => {
throw new Error("binary provider must not start");
});
const server = createServer(
{ kind: "session", session },
{ webModuleTrace: service },
);
onTestFinished(async () => {
await server.close();
await session.close();
});
await expect(server.close()).rejects.toBeInstanceOf(AggregateError);
await server.close();
await server.close();
expect(closes).toBe(2);
});
@@ -7,6 +7,7 @@ import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
import { expect, it, onTestFinished } from "vitest";
import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
import { silentLogger } from "../../../src/logger.js";
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
import { registerWebScriptTool } from "../../../src/server/registerWebScriptTool.js";
@@ -29,14 +30,17 @@ it.skipIf(process.platform === "win32")(
undefined,
new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE),
);
const artifactResources = new ArtifactResourceScope();
registerWebScriptTool(server, {
logger: silentLogger,
recordEvidence: undefined,
artifactResources: artifactResources,
});
const client = new Client({ name: "script-selection-test", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await artifactResources.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
@@ -1,6 +1,6 @@
import { parseConfig } from "../../../src/config/parseConfig.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { dirname, join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, describe, expect, it } from "vitest";
@@ -136,6 +136,20 @@ describe("MCP composed workflow snapshot replay", () => {
})
.passthrough()
.parse(output);
const primitiveResult = await mcp.callTool({
name: "list_strings",
arguments: { document: "fixture" },
});
expect(
primitiveResult.isError,
JSON.stringify(primitiveResult.content),
).not.toBe(true);
const primitiveEvidence = toolContract("list_strings").outputSchema.parse(
primitiveResult.structuredContent,
);
expect(primitiveEvidence).toMatchObject({
subject: { local_path: targetPath },
});
const afterAnalysisCalls = [...calls];
const afterAnalysisStarts = [...starts];
@@ -163,6 +177,47 @@ describe("MCP composed workflow snapshot replay", () => {
}),
);
const relocatedPath = join(dirname(targetPath), "relocated.hop");
await writeFile(relocatedPath, "fixture.hop");
const reopened = await mcp.callTool({
name: "open_binary",
arguments: { path: relocatedPath, snapshot_path: snapshotPath },
});
expect(reopened.isError, JSON.stringify(reopened.content)).not.toBe(true);
const cachedPrimitive = await mcp.callTool({
name: "list_strings",
arguments: { document: "fixture" },
});
expect(
cachedPrimitive.isError,
JSON.stringify(cachedPrimitive.content),
).not.toBe(true);
const cachedEvidence = toolContract("list_strings").outputSchema.parse(
cachedPrimitive.structuredContent,
);
expect(cachedEvidence).toMatchObject({
subject: { local_path: relocatedPath },
});
expect(cachedEvidence.normalized_result).toEqual(
primitiveEvidence.normalized_result,
);
expect(cachedEvidence.raw_result).toEqual(primitiveEvidence.raw_result);
const retained = await mcp.callTool({
name: "get_evidence_bundle",
arguments: {},
});
expect(retained.isError, JSON.stringify(retained.content)).not.toBe(true);
const retainedBundle = toolContract(
"get_evidence_bundle",
).outputSchema.parse(retained.structuredContent).result;
expect(
retainedBundle.records.find(
({ evidence_id }) => evidence_id === primitiveEvidence.evidence_id,
)?.subject?.local_path,
).toBe(targetPath);
expect(calls).toEqual(afterAnalysisCalls);
expect(starts).toEqual(afterAnalysisStarts);
const dependencies: DirectAnalysisDependencies = {
readConfiguration: () => parseConfig({}),
createBinarySession: () => createWorkflowSession(provider),
@@ -180,7 +235,9 @@ describe("MCP composed workflow snapshot replay", () => {
expect(calls).toEqual(afterAnalysisCalls);
expect(starts).toEqual(afterAnalysisStarts);
});
});
describe("MCP live workflow snapshot policy", () => {
it("does not bind a workflow when an upstream operation is live", async () => {
const { targetPaths, snapshotPath } = await createWorkflowFiles(
"rea-mcp-live-workflow-snapshot-",
@@ -282,26 +339,27 @@ describe("MCP investigation history snapshot replay", () => {
const foreignEvidence = toolContract("list_strings").outputSchema.parse(
unrelated.structuredContent,
);
const updateInput = {
unknown_id: unknown.unknown_id,
expected_revision: unknown.revision,
status: "resolved",
severity: input.severity,
supporting_evidence_ids: resolutionEvidenceIds,
contradicting_evidence_ids: input.contradicting_evidence_ids,
required_authority: input.required_authority,
required_confidence: input.required_confidence,
required_environment: input.required_environment,
recommended_probes: input.recommended_probes,
relationships: input.relationships,
resolution: {
disposition,
rationale: "Disposition recorded after further investigation.",
evidence_ids: resolutionEvidenceIds,
},
};
const updated = await mcp.callTool({
name: "update_unknown",
arguments: {
unknown_id: unknown.unknown_id,
expected_revision: unknown.revision,
status: "resolved",
severity: input.severity,
supporting_evidence_ids: resolutionEvidenceIds,
contradicting_evidence_ids: input.contradicting_evidence_ids,
required_authority: input.required_authority,
required_confidence: input.required_confidence,
required_environment: input.required_environment,
recommended_probes: input.recommended_probes,
relationships: input.relationships,
resolution: {
disposition,
rationale: "Disposition recorded after further investigation.",
evidence_ids: resolutionEvidenceIds,
},
},
arguments: updateInput,
});
expect(updated.isError, JSON.stringify(updated.content)).not.toBe(true);
const resolved = toolContract("update_unknown").outputSchema.parse(
@@ -327,6 +385,7 @@ describe("MCP investigation history snapshot replay", () => {
expect(snapshot.value.evidence_bundle.records).toContainEqual(
expect.objectContaining({
operation: "update_unknown",
parameters: updateInput,
subject: expect.objectContaining({ local_path: secondPath }),
}),
);