test: overhaul deterministic suite architecture

This commit is contained in:
morluto
2026-07-29 22:00:38 +00:00
parent 7f2348619a
commit 513d9b1555
371 changed files with 30879 additions and 24389 deletions
+467
View File
@@ -0,0 +1,467 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { createPackageWithOptions } from "@electron/asar";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { expect, it } from "vitest";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
composeBinarySessionFromFactory,
composeBinarySessionFromProvider,
} from "../../../src/application/BinarySessionComposition.js";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import { ARTIFACT_COMPARISON_EXAMPLE } from "../../../src/contracts/artifactComparisonExample.js";
import { evidenceBundleSchema } from "../../../src/domain/evidenceBundle.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
it.each([
{ unpacked: false, label: "embedded" },
{ unpacked: true, label: "unpacked" },
])(
"returns actionable local details for an $label ASAR integrity error",
async ({ unpacked }) => {
const root = await createTestTempDirectory("rea-asar-integrity-mcp-");
const source = join(root, "source");
const original = "console.log('ok');\n";
const changed = "console.log('no');\n";
await mkdir(source);
await writeFile(join(source, "main.js"), original);
const archive = join(root, "fixture.asar");
await createPackageWithOptions(
source,
archive,
unpacked ? { unpack: "*.js" } : {},
);
if (unpacked) {
await writeFile(join(`${archive}.unpacked`, "main.js"), changed);
} else {
const bytes = await readFile(archive);
const contentOffset = bytes.indexOf(original);
expect(contentOffset).toBeGreaterThanOrEqual(0);
bytes.write(changed, contentOffset, "utf8");
await writeFile(archive, bytes);
}
const session = composeBinarySessionFromProvider(new ArtifactProvider());
const server = createServer(session, session);
const client = new Client({ name: "asar-integrity-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const opened = await client.callTool({
name: "open_binary",
arguments: { path: archive },
});
expect(opened.isError).not.toBe(true);
const result = await client.callTool({
name: "inventory_artifact",
arguments: {},
});
expect(result.isError).toBe(true);
expect(result.structuredContent).toEqual({
error: {
code: "artifact_integrity_mismatch",
category: "integrity_mismatch",
message:
"Artifact is invalid or has changed. Get a fresh copy and try again.",
details: {
logical_path: "main.js",
declared_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
calculated_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
unpacked,
},
retryable: false,
remediation: {
action:
"Artifact is invalid or has changed. Get a fresh copy and try again.",
restart_required: false,
},
},
});
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
},
20_000,
);
const artifactInventoryResultSchema = z.object({
occurrences: z.object({
items: z.array(
z.object({ logical_path: z.string(), hash_status: z.string() }),
),
}),
integrity_contradictions: z.array(
z.object({
logical_path: z.string(),
declared_sha256: z.string(),
observed_sha256: z.string(),
trust: z.literal("observed-untrusted"),
}),
),
});
it("records an approved mismatch, preserves verified siblings, and never reports equivalence", async () => {
const root = await createTestTempDirectory("rea-asar-continue-mcp-");
const source = join(root, "source");
await mkdir(source);
const original = "console.log('ok');\n",
changed = "console.log('no');\n",
secondOriginal = "console.log('up');\n",
secondChanged = "console.log('dn');\n";
await writeFile(join(source, "main.js"), original);
await writeFile(join(source, "second.js"), secondOriginal);
await writeFile(join(source, "sibling.js"), "console.log('sibling');\n");
const archive = join(root, "fixture.asar");
await createPackageWithOptions(source, archive, {});
const bytes = await readFile(archive);
const contentOffset = bytes.indexOf(original);
const secondOffset = bytes.indexOf(secondOriginal);
expect(contentOffset).toBeGreaterThanOrEqual(0);
expect(secondOffset).toBeGreaterThanOrEqual(0);
bytes.write(changed, contentOffset, "utf8");
bytes.write(secondChanged, secondOffset, "utf8");
await writeFile(archive, bytes);
const session = composeBinarySessionFromProvider(
new ArtifactProvider(false, true),
);
const server = createServer(session, session);
const client = new Client({ name: "asar-continue-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
await client.callTool({
name: "open_binary",
arguments: { path: archive },
});
const limited = await client.callTool({
name: "inventory_artifact",
arguments: {
integrity_policy: "record-and-continue",
integrity_continue_approved: true,
max_integrity_mismatches: 1,
},
});
expect(limited).toMatchObject({
isError: true,
structuredContent: { error: { code: "truncated" } },
});
const result = await client.callTool({
name: "inventory_artifact",
arguments: {
integrity_policy: "record-and-continue",
integrity_continue_approved: true,
},
});
expect(result.isError).not.toBe(true);
const compact = compactResult(result.structuredContent);
const evidence = session.evidenceById(compact.evidence_id);
if (evidence === undefined) throw new Error("missing inventory Evidence");
const inventory = artifactInventoryResultSchema.parse(compact.result);
expect(inventory.integrity_contradictions).toEqual(
expect.arrayContaining([
expect.objectContaining({
logical_path: "main.js",
trust: "observed-untrusted",
declared_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
observed_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
}),
expect.objectContaining({ logical_path: "second.js" }),
]),
);
expect(inventory.integrity_contradictions).toHaveLength(2);
expect(inventory.occurrences.items).toEqual(
expect.arrayContaining([
expect.objectContaining({
logical_path: "main.js",
hash_status: "mismatched",
}),
expect.objectContaining({
logical_path: "sibling.js",
hash_status: "verified",
}),
expect.objectContaining({
logical_path: "second.js",
hash_status: "mismatched",
}),
]),
);
const inspected = await client.callTool({
name: "inspect_artifact",
arguments: {
integrity_policy: "record-and-continue",
integrity_continue_approved: true,
},
});
expect(inspected.isError).not.toBe(true);
expect(compactResult(inspected.structuredContent).result).toMatchObject({
contradictions: [
expect.objectContaining({ occurrence_id: expect.any(String) }),
expect.objectContaining({ occurrence_id: expect.any(String) }),
],
substeps: [
expect.objectContaining({
operation: "inventory_artifact",
status: "completed",
}),
],
});
const compared = await client.callTool({
name: "compare_artifacts",
arguments: {
left_evidence_ids: [evidence.evidence_id],
right_evidence_ids: [evidence.evidence_id],
},
});
expect(compared.isError).not.toBe(true);
expect(compactResult(compared.structuredContent).result).toMatchObject({
status: "contradiction",
summary: { contradiction: 2 },
changes: {
items: expect.arrayContaining([
expect.objectContaining({
logical_path: "main.js",
classification: "contradiction",
dimensions: ["integrity"],
}),
expect.objectContaining({
logical_path: "second.js",
classification: "contradiction",
}),
]),
},
});
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
});
it("rejects altered payloads that reuse session Evidence IDs", async () => {
const session = composeBinarySessionFromFactory(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
session.recordEvidence(ARTIFACT_COMPARISON_EXAMPLE.left);
session.recordEvidence(ARTIFACT_COMPARISON_EXAMPLE.right);
const server = createServer(session, session);
const client = new Client({
name: "artifact-authority-test",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "compare_artifacts",
arguments: {
...ARTIFACT_COMPARISON_EXAMPLE,
left: {
...ARTIFACT_COMPARISON_EXAMPLE.left,
limitations: ["caller altered this record"],
},
},
});
expect(result.isError).toBe(true);
expect(session.exportEvidenceBundle().records).toHaveLength(2);
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
});
it("rejects comparison Evidence that is not owned by the session", async () => {
const session = composeBinarySessionFromFactory(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session);
const client = new Client({
name: "artifact-ownership-test",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "compare_artifacts",
arguments: ARTIFACT_COMPARISON_EXAMPLE,
});
expect(result.isError).toBe(true);
expect(session.exportEvidenceBundle().records).toEqual([]);
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
});
it("opens archives without Hopper, compares them, and exports linked evidence", async () => {
const directory = await createTestTempDirectory("rea-artifact-mcp-");
const archive = join(directory, "fixture.ipa");
const changedArchive = join(directory, "changed.ipa");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("Payload/Fixture.app/main.js", new TextReader("main();"));
await writeFile(archive, await writer.close());
const changedWriter = new ZipWriter(new Uint8ArrayWriter());
await changedWriter.add(
"Payload/Fixture.app/main.js",
new TextReader("changed();"),
);
await writeFile(changedArchive, await changedWriter.close());
const session = composeBinarySessionFromProvider(new ArtifactProvider());
const server = createServer(session, session);
const client = new Client({ name: "artifact-mcp-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const opened = await client.callTool({
name: "open_binary",
arguments: { path: archive },
});
expect(opened.isError).not.toBe(true);
const inspected = await client.callTool({
name: "inspect_artifact",
arguments: { max_observations: 1, max_relationships: 1 },
});
expect(inspected.isError).not.toBe(true);
const inspectionResult = compactResult(inspected.structuredContent);
const inspectionEvidence = session.evidenceById(
inspectionResult.evidence_id,
);
if (inspectionEvidence === undefined)
throw new Error("missing inspection Evidence");
const inspection = z
.object({
substeps: z.array(
z.object({
evidence_id: z.string(),
status: z.literal("completed"),
}),
),
coverage: z.object({
status: z.literal("truncated"),
substeps_completed: z.literal(1),
}),
unexplored_branches: z.array(z.object({ reason: z.string() })),
})
.parse(inspectionResult.result);
expect(inspection.substeps).toHaveLength(1);
expect(
session.evidenceById(inspection.substeps[0]?.evidence_id ?? ""),
).toMatchObject({ operation: "inventory_artifact" });
expect(inspectionEvidence.evidence_links).toEqual([
inspection.substeps[0]?.evidence_id,
]);
expect(inspection.unexplored_branches).toEqual(
expect.arrayContaining([
expect.objectContaining({ reason: "page-limit" }),
]),
);
const inventory = await client.callTool({
name: "inventory_artifact",
arguments: {},
});
expect(inventory.isError).not.toBe(true);
const inventoryResult = compactResult(inventory.structuredContent);
const evidence = session.evidenceById(inventoryResult.evidence_id);
if (evidence === undefined) throw new Error("missing inventory Evidence");
expect(evidence).toMatchObject({
provider: { id: "rea-artifact-graph" },
subject: { format: "ipa" },
});
expect(inventoryResult.result).toMatchObject({
manifest: { root_format: "ipa" },
});
const openedChanged = await client.callTool({
name: "open_binary",
arguments: { path: changedArchive },
});
expect(openedChanged.isError).not.toBe(true);
const changedInventory = await client.callTool({
name: "inventory_artifact",
arguments: {},
});
const changedResult = compactResult(changedInventory.structuredContent);
const changedEvidence = session.evidenceById(changedResult.evidence_id);
if (changedEvidence === undefined)
throw new Error("missing changed Evidence");
const compared = await client.callTool({
name: "compare_artifacts",
arguments: {
left_evidence_ids: [evidence.evidence_id],
right_evidence_ids: [changedEvidence.evidence_id],
unknown_registry_approved: true,
},
});
expect(compared.isError).not.toBe(true);
expect(compactResult(compared.structuredContent)).toMatchObject({
result: { status: "changed" },
evidence_id: expect.stringMatching(/^ev_/u),
});
const unknowns = await client.callTool({
name: "list_unknowns",
arguments: { domain: "artifact-comparison" },
});
expect(unknowns.structuredContent).toMatchObject({
result: {
items: [
expect.objectContaining({
unknown: expect.objectContaining({
domain: "artifact-comparison",
}),
}),
],
},
});
const snapshotted = await client.callTool({
name: "snapshot_evidence_bundle",
arguments: {},
});
const bundleUri = z
.object({ result: z.object({ bundle_uri: z.string() }) })
.parse(snapshotted.structuredContent).result.bundle_uri;
const bundleResource = await client.readResource({ uri: bundleUri });
const bundle = evidenceBundleSchema.parse(
JSON.parse(
z.object({ text: z.string() }).parse(bundleResource.contents[0]).text,
),
);
expect(bundle.records).toHaveLength(6);
expect(bundle.artifacts).toContainEqual({
digest: { sha256: evidence.subject?.digest.sha256 },
format: "ipa",
architecture: null,
});
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
});
const compactResult = (value: unknown) =>
z
.object({
result: z.unknown(),
evidence_id: z.string(),
evidence_uri: z.string(),
})
.parse(value);
+330
View File
@@ -0,0 +1,330 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, expect, it } from "vitest";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import { loadConfiguredPermissionAuthority } from "../../../src/application/PermissionConfiguration.js";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { parseConfig } from "../../../src/config.js";
import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "../../../src/contracts/javascriptRuntimeReconciliationExample.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
import {
startFakeCdpBrowser,
type FakeCdpBrowser,
} from "../../fixtures/fakeCdpBrowser.js";
const resources: Array<{ close(): Promise<unknown> }> = [];
const browsers: FakeCdpBrowser[] = [];
const INTEGRATION_TEST_TIMEOUT_MS = 20_000;
afterEach(async () => {
await Promise.all(
resources.splice(0).map(async (resource) => resource.close()),
);
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
});
it(
"exposes CLI-equivalent Evidence v2 and session resources",
async () => {
const browser = await startFakeCdpBrowser({
sessionTimeline: "same_origin",
webMcpTools: true,
sensitiveShapes: true,
});
browsers.push(browser);
const connected = await connectBrowser(browser);
const tools = await connected.client.listTools();
expect(tools.tools.length).toBeLessThan(TOOL_CONTRACTS.length);
expect(tools.tools.map(({ name }) => name)).toEqual(
expect.arrayContaining([
"list_browser_targets",
"inspect_web_page",
"analyze_web_bundle",
"observe_web_session",
"discover_webmcp_tools",
"compare_web_captures",
"capture_web_screenshot",
"compare_web_screenshots",
]),
);
const status = await connected.client.callTool({
name: "binary_session",
arguments: { detail: "full" },
});
expect(status.structuredContent).toMatchObject({
result: {
tool_availability: expect.arrayContaining([
expect.objectContaining({
name: "inspect_web_page",
available: true,
reason: "available",
}),
]),
},
});
const listed = await connected.client.callTool({
name: "list_browser_targets",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
approved: true,
},
});
expect(listed.isError).not.toBe(true);
expect(listed.structuredContent).toMatchObject({
result: {
targets: { items: [{ target_id: "allowed-page" }] },
},
});
const inspected = await connected.client.callTool({
name: "inspect_web_page",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
include_console_text: true,
console_text_approved: true,
include_json_body_shapes: true,
json_body_schema_approved: true,
include_websocket_shapes: true,
websocket_shape_approved: true,
include_script_sources: true,
},
});
expect(inspected.isError).not.toBe(true);
expect(inspected.structuredContent).toMatchObject({
result: {
target: { target_id: "allowed-page" },
console: { prior_activity_available: false },
network: {
prior_activity_available: false,
requests: [
expect.objectContaining({
body_shapes: expect.objectContaining({ status: "included" }),
}),
],
},
},
});
const reconciled = await connected.client.callTool({
name: "reconcile_javascript_runtime",
arguments: {
static_layers: JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE.static_layers,
runtime_observations: [
evidenceFor(connected.session, inspected.structuredContent),
],
},
});
expect(reconciled.isError).not.toBe(true);
expect(reconciled.structuredContent).toMatchObject({
result: { summary: { runtime_scripts: 1 } },
});
expect(JSON.stringify(reconciled.structuredContent)).not.toContain(
"source-secret",
);
const analyzed = await connected.client.callTool({
name: "analyze_web_bundle",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
source_capture_approved: true,
observation_ms: 0,
},
});
expect(analyzed.isError).not.toBe(true);
expect(analyzed.structuredContent).toMatchObject({
result: {
capture: { scripts_analyzed: 1 },
observations: { source_maps: { status: "not_requested" } },
},
});
await verifySessionAndComparisonTools(connected, browser, inspected);
},
INTEGRATION_TEST_TIMEOUT_MS,
);
const verifySessionAndComparisonTools = async (
connected: Awaited<ReturnType<typeof connectBrowser>>,
browser: FakeCdpBrowser,
inspected: Awaited<ReturnType<Client["callTool"]>>,
): Promise<void> => {
const observedSession = await connected.client.callTool({
name: "observe_web_session",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 5,
},
});
expect(observedSession.isError).not.toBe(true);
expect(observedSession.structuredContent).toMatchObject({
result: {
window: { end_reason: "window_elapsed" },
timeline: expect.arrayContaining([
expect.objectContaining({ type: "same_origin_reload" }),
]),
},
});
const webMcp = await connected.client.callTool({
name: "discover_webmcp_tools",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
},
});
expect(webMcp.isError).not.toBe(true);
expect(webMcp.structuredContent).toMatchObject({
result: {
tools: {
items: [expect.objectContaining({ name: "search_orders" })],
},
},
});
const capture = normalizedResultOf(inspected.structuredContent);
const compared = await connected.client.callTool({
name: "compare_web_captures",
arguments: {
before: { inspection: capture },
after: { inspection: capture },
},
});
expect(compared.isError).not.toBe(true);
expect(compared.structuredContent).toMatchObject({
result: { overall_status: "unknown" },
});
const screenshot = await connected.client.callTool({
name: "capture_web_screenshot",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
screenshot_approved: true,
},
});
expect(screenshot.isError).not.toBe(true);
const screenshotArtifact = artifactOf(screenshot.structuredContent);
const visual = await connected.client.callTool({
name: "compare_web_screenshots",
arguments: {
before: screenshotArtifact,
after: screenshotArtifact,
},
});
expect(visual.isError).not.toBe(true);
expect(visual.structuredContent).toMatchObject({
result: { status: "identical", changed_pixels: 0 },
});
const evidenceId = evidenceIdOf(inspected.structuredContent);
const evidence = await connected.client.readResource({
uri: `rea://evidence/${evidenceId}`,
});
expect(evidence.contents[0]).toEqual(
expect.objectContaining({ text: expect.stringContaining(evidenceId) }),
);
};
it("denies origins outside the administrator ceiling before CDP attach", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const connected = await connectBrowser(browser);
const denied = await connected.client.callTool({
name: "inspect_web_page",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_origins: ["https://unapproved.example.test"],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
},
});
expect(denied.isError).toBe(true);
expect(denied.structuredContent).toMatchObject({
error: {
code: "permission_required",
details: {
missing: { origins: ["https://unapproved.example.test"] },
},
},
});
expect(browser.commands).toHaveLength(0);
});
const connectBrowser = async (browser: FakeCdpBrowser) => {
const config = parseConfig({
REA_BROWSER_OBSERVE_ENABLED: "true",
REA_BROWSER_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
REA_BROWSER_ALLOWED_ORIGINS_JSON: JSON.stringify([browser.allowedOrigin]),
});
if (!config.ok) throw config.error;
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok) throw authority.error;
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
browserObservation: new CdpBrowserProvider(),
permissionAuthority: authority.value,
availabilityPolicy: () => ({
processCaptureEnabled: false,
evidenceFileRoots: 0,
investigationInputRoots: 0,
browserObservationEnabled: true,
}),
});
const client = new Client({ name: "browser-mcp-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server, session);
await server.connect(serverTransport);
await client.connect(clientTransport);
return { client, session };
};
const evidenceIdOf = (value: unknown): string => {
if (
typeof value !== "object" ||
value === null ||
!("evidence_id" in value) ||
typeof value.evidence_id !== "string"
)
throw new TypeError("Missing browser evidence ID");
return value.evidence_id;
};
const normalizedResultOf = (value: unknown): unknown => {
if (typeof value !== "object" || value === null || !("result" in value))
throw new TypeError("Missing normalized browser result");
return value.result;
};
const evidenceFor = (session: BinarySession, value: unknown) => {
const evidence = session.evidenceById(evidenceIdOf(value));
if (evidence === undefined) throw new TypeError("Missing session Evidence");
return evidence;
};
const artifactOf = (value: unknown): unknown => {
const normalized = normalizedResultOf(value);
if (
typeof normalized !== "object" ||
normalized === null ||
!("artifact" in normalized)
)
throw new TypeError("Missing screenshot artifact");
return normalized.artifact;
};
@@ -0,0 +1,278 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { dirname } from "node:path";
import { afterEach, describe, expect, test } from "vitest";
import type { BrowserScenarioCapturePort } from "../../../src/application/BrowserScenarioCapturePort.js";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import { loadConfiguredPermissionAuthority } from "../../../src/application/PermissionConfiguration.js";
import type {
ExecutionOptions,
ProviderIdentity,
} from "../../../src/application/AnalysisProvider.js";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { parseConfig } from "../../../src/config.js";
import { sanitizeBrowserUrl } from "../../../src/domain/browserObservation.js";
import type { BrowserScenario } from "../../../src/domain/browserScenario.js";
import {
browserScenarioCaptureSchema,
type BrowserScenarioCapture,
} from "../../../src/domain/browserScenarioCapture.js";
import type { AnalysisError } from "../../../src/domain/errors.js";
import { ok, type Result } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
const providerIdentity: ProviderIdentity = {
id: "test-browser-scenario",
name: "Test browser scenario provider",
version: "1",
};
class FakeBrowserScenarioProvider implements BrowserScenarioCapturePort {
readonly scenarios: BrowserScenario[] = [];
identity(): ProviderIdentity {
return providerIdentity;
}
captureScenario(
scenario: BrowserScenario,
_options?: ExecutionOptions,
): Promise<Result<BrowserScenarioCapture, AnalysisError>> {
this.scenarios.push(scenario);
return Promise.resolve(ok(captureFor(scenario)));
}
}
const artifacts = {
screenshot: { state: "not_requested" },
dom: { state: "not_requested" },
accessibility: { state: "not_requested" },
url: { state: "not_requested" },
history: { state: "not_requested" },
storage: { state: "not_requested" },
} as const;
const captureFor = (scenario: BrowserScenario): BrowserScenarioCapture => {
const start = scenario.start_url.url;
const step = (stepIndex: number, stepId: string, action: string) => ({
step_index: stepIndex,
step_id: stepId,
action,
status: "completed",
elapsed_ms: 1,
before_url: sanitizeBrowserUrl(start),
after_url: sanitizeBrowserUrl(start),
error: null,
event_sequence_start: 1,
event_sequence_end: 0,
artifacts,
completeness: {
status: "complete",
equality_eligible: true,
missing_sections: [],
truncated_sections: [],
},
});
return browserScenarioCaptureSchema.parse({
schema_version: 1,
browser: {
mode: scenario.browser.mode,
process_ownership: "provider-owned",
cleanup: "terminated-owned-process",
product: "Test Browser",
version: "1",
},
scenario: {
start_origin: new URL(start).origin,
allowed_origins: scenario.allowed_origins,
action_count: scenario.actions.length,
secret_references: scenario.secrets.map(({ secret_id: id }) => id),
},
duration_ms: 2,
steps: [
step(0, "scenario_start", "goto_start"),
...scenario.actions.map((action, index) =>
step(index + 1, action.step_id, action.action),
),
],
events: { retained: 0, dropped: 0, items: [] },
completeness: {
status: "complete",
equality_eligible: true,
missing_sections: [],
truncated_sections: [],
},
limitations: [],
});
};
const scenario = (origin = "https://app.example.test") => ({
schema_version: 1,
browser: {
mode: "launch",
executable_path: process.execPath,
headless: true,
user_data: "temporary-owned",
cleanup: "close-and-delete-profile",
},
start_url: { url: `${origin}/`, query: [] },
allowed_origins: [origin],
environment: {
viewport: { width: 1_280, height: 720 },
locale: "en-US",
timezone: "UTC",
color_scheme: "light",
reduced_motion: "reduce",
service_workers: "block",
},
actions: [
{
step_id: "login-input",
action: "fill",
locator: { kind: "test_id", value: "password" },
value: { source: "secret", secret_id: "login_input" },
},
],
storage: {},
request_replay: { mode: "disabled" },
secrets: [
{
secret_id: "login_input",
environment_variable: "REA_TEST_PASSWORD",
purpose: "input",
redaction: "replace-with-secret-reference",
},
],
redaction: {
secret_values: "replace-with-secret-reference",
query_parameter_names: [],
},
capture: { after_each_step: [], at_end: [], events: [] },
limits: {
max_duration_ms: 10_000,
action_timeout_ms: 1_000,
navigation_timeout_ms: 1_000,
max_events: 100,
max_frames: 10,
max_workers: 5,
max_popups: 2,
max_websockets: 10,
max_dom_nodes: 1_000,
max_accessibility_nodes: 1_000,
max_screenshots: 2,
max_screenshot_bytes: 1_048_576,
max_storage_entries: 100,
max_total_metadata_bytes: 1_048_576,
},
approved: true,
});
describe("browser scenario MCP tool", () => {
const resources: Array<{ close(): Promise<unknown> }> = [];
afterEach(async () => {
await Promise.all(resources.splice(0).map((item) => item.close()));
});
test("authorizes exact scope, records Evidence, and retains no secret value", async () => {
const configured = parseConfig({
REA_BROWSER_SCENARIO_ENABLED: "true",
REA_BROWSER_SCENARIO_AUTO_GRANT: "true",
REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON: JSON.stringify([
dirname(process.execPath),
]),
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON: '["https://app.example.test"]',
REA_BROWSER_SCENARIO_ALLOWED_ENV_JSON: '["REA_TEST_PASSWORD"]',
});
if (!configured.ok) throw configured.error;
const authority = await loadConfiguredPermissionAuthority(configured.value);
if (!authority.ok) throw authority.error;
const provider = new FakeBrowserScenarioProvider();
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
browserObservation: new CdpBrowserProvider(),
browserScenarioCapture: provider,
permissionAuthority: authority.value,
availabilityPolicy: () => ({
processCaptureEnabled: false,
evidenceFileRoots: 0,
investigationInputRoots: 0,
browserObservationEnabled: true,
browserScenarioEnabled: true,
}),
});
const client = new Client({ name: "browser-scenario-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server, session);
await server.connect(serverTransport);
await client.connect(clientTransport);
const captured = await client.callTool({
name: "capture_browser_scenario",
arguments: scenario(),
});
expect(captured.isError, JSON.stringify(captured)).not.toBe(true);
expect(captured.structuredContent).toMatchObject({
result: {
scenario: {
secret_references: ["login_input"],
},
},
});
expect(provider.scenarios).toHaveLength(1);
expect(JSON.stringify(captured.structuredContent)).not.toContain(
"correct horse battery staple",
);
const evidenceId = Reflect.get(
captured.structuredContent ?? {},
"evidence_id",
);
expect(session.evidenceById(String(evidenceId))).toMatchObject({
predicate_type: "rea.browser-scenario-capture/v1",
});
const captureResult = Reflect.get(
captured.structuredContent ?? {},
"result",
);
const compared = await client.callTool({
name: "compare_web_captures",
arguments: {
before_scenario: captureResult,
after_scenario: captureResult,
normalization: { rules: [] },
},
});
expect(compared.isError, JSON.stringify(compared)).not.toBe(true);
expect(compared.structuredContent).toMatchObject({
result: {
comparison_kind: "browser_scenario",
overall_status: "unchanged",
alignment: { status: "aligned", aligned_steps: 2 },
},
});
const denied = await client.callTool({
name: "capture_browser_scenario",
arguments: scenario("https://other.example.test"),
});
expect(denied.isError).toBe(true);
expect(provider.scenarios).toHaveLength(1);
const unapprovedEnvironment = scenario();
const secretDeclaration = unapprovedEnvironment.secrets.at(0);
if (secretDeclaration === undefined)
throw new Error("Scenario secret fixture disappeared");
secretDeclaration.environment_variable = "REA_UNAPPROVED_SECRET";
const deniedSecret = await client.callTool({
name: "capture_browser_scenario",
arguments: unapprovedEnvironment,
});
expect(deniedSecret.isError).toBe(true);
expect(provider.scenarios).toHaveLength(1);
});
});
@@ -0,0 +1,169 @@
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import {
createEvidenceBundle,
serializeEvidenceBundle,
} from "../../../src/domain/evidenceBundle.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
const roots: string[] = [];
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
const sourceEvidence = (label: string) =>
createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: "observe",
parameters: { label },
result: { label },
confidence: "observed",
authority: "shipped-artifact",
},
);
describe("bundle comparison MCP integration", () => {
it("reads two approved bounded bundle files and records a compact result", async () => {
const root = await createTestTempDirectory("rea-bundle-mcp-");
roots.push(root);
const leftPath = join(root, "left.json");
const rightPath = join(root, "right.json");
const leftRecord = sourceEvidence("left");
const rightRecord = sourceEvidence("right");
await Promise.all([
writeFile(
leftPath,
serializeEvidenceBundle(createEvidenceBundle([leftRecord])),
),
writeFile(
rightPath,
serializeEvidenceBundle(createEvidenceBundle([rightRecord])),
),
]);
const connected = await connect(root);
try {
const result = await connected.client.callTool({
name: "compare_bundles",
arguments: {
left_bundle_path: leftPath,
right_bundle_path: rightPath,
record_pairs: [
{
left_evidence_id: leftRecord.evidence_id,
right_evidence_id: rightRecord.evidence_id,
},
],
},
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
result: { status: "changed" },
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
evidence_uri: expect.stringMatching(/^rea:\/\/evidence\/ev_/u),
});
} finally {
await connected.close();
}
});
it("rejects a bundle path outside the approved root", async () => {
const root = await createTestTempDirectory("rea-bundle-root-");
const outside = await createTestTempDirectory("rea-bundle-outside-");
roots.push(root, outside);
const leftPath = join(root, "left.json");
const rightPath = join(outside, "right.json");
const encoded = serializeEvidenceBundle(createEvidenceBundle([]));
await Promise.all([
writeFile(leftPath, encoded),
writeFile(rightPath, encoded),
]);
const connected = await connect(root);
try {
const result = await connected.client.callTool({
name: "compare_bundles",
arguments: {
left_bundle_path: leftPath,
right_bundle_path: rightPath,
},
});
expect(result).toMatchObject({
isError: true,
structuredContent: { error: { code: "outside_approved_root" } },
});
} finally {
await connected.close();
}
});
it("rejects an oversized approved bundle", async () => {
const root = await createTestTempDirectory("rea-bundle-size-");
roots.push(root);
const leftPath = join(root, "left.json");
const rightPath = join(root, "right.json");
await Promise.all([
writeFile(leftPath, " ".repeat(2_000)),
writeFile(rightPath, serializeEvidenceBundle(createEvidenceBundle([]))),
]);
const connected = await connect(root, 1_024);
try {
const result = await connected.client.callTool({
name: "compare_bundles",
arguments: {
left_bundle_path: leftPath,
right_bundle_path: rightPath,
},
});
expect(result).toMatchObject({
isError: true,
structuredContent: { error: { code: "truncated" } },
});
} finally {
await connected.close();
}
});
});
const connect = async (root: string, maxBytes = 1024 * 1024) => {
const session = composeBinarySessionFromFactory(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
evidenceFilePolicy: {
roots: [root],
maxBytes,
maxDepth: 68,
maxStringLength: 1024 * 1024,
maxNodes: 100_000,
},
});
const client = new Client({ name: "bundle-comparison-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
return {
client,
close: async () => {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
},
};
};
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import { mcpTest } from "../../support/mcp/mcpFixture.js";
import { createServer } from "../../../src/server/createServer.js";
const analysis = {
execute: () => Promise.resolve(ok(null)),
};
describe("MCP server composition", () => {
it("constructs independent MCP server instances", () => {
expect(createServer(analysis)).not.toBe(createServer(analysis));
});
mcpTest("does not advertise unavailable session tools", async ({ mcp }) => {
const server = createServer(analysis);
const client = await mcp.connect(server, {
name: "composition-test",
version: "1.0.0",
});
expect(client.getInstructions()).not.toContain("open_binary");
const names = (await client.listTools()).tools.map(({ name }) => name);
expect(names).not.toContain("compare_managed_members");
expect(names).not.toContain("plan_managed_runtime_correlation");
});
});
@@ -0,0 +1,90 @@
import { describe, expect, it } from "vitest";
import { runDerivedOperation } from "../../../src/server/runDerivedOperation.js";
const context = (
controller: AbortController,
notifications: unknown[] = [],
) => ({
mcpReq: {
signal: controller.signal,
_meta: { progressToken: "derived-test" },
notify: (notification: unknown) => {
notifications.push(notification);
return Promise.resolve();
},
},
});
describe("derived MCP operation boundary", () => {
it("cancels before computation and never evaluates the operation", async () => {
const controller = new AbortController();
controller.abort();
let computed = false;
const result = await runDerivedOperation(
context(controller),
"compare",
() => {
computed = true;
return "impossible";
},
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
expect(computed).toBe(false);
});
it("lets cancellation win immediately before result publication", async () => {
const controller = new AbortController();
const result = await runDerivedOperation(
context(controller),
"compare",
() => {
controller.abort();
return "must-not-publish";
},
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
});
it("emits bounded monotonic progress with one terminal state", async () => {
const controller = new AbortController();
const notifications: Array<{
params?: { progress?: number; total?: number };
}> = [];
const result = await runDerivedOperation(
context(controller, notifications),
"compare",
() => "complete",
);
expect(result).toEqual({ ok: true, value: "complete" });
expect(notifications.map(({ params }) => params?.progress)).toEqual([0, 2]);
expect(notifications.every(({ params }) => params?.total === 2)).toBe(true);
});
it("projects synchronous computation failures into a typed result", async () => {
const result = await runDerivedOperation(
context(new AbortController()),
"compare_artifacts",
() => {
throw new TypeError("malformed comparison evidence");
},
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisInputError",
operation: "compare_artifacts",
},
});
});
});
+351
View File
@@ -0,0 +1,351 @@
import { mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, expect, it } from "vitest";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import { loadConfiguredPermissionAuthority } from "../../../src/application/PermissionConfiguration.js";
import { CdpElectronProvider } from "../../../src/browser/CdpElectronProvider.js";
import { parseConfig } from "../../../src/config.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
import {
startFakeCdpBrowser,
type FakeCdpBrowser,
} from "../../fixtures/fakeCdpBrowser.js";
import { writeElectronBoundaryFixture } from "../../fixtures/electronBoundaryApplication.js";
const browsers: FakeCdpBrowser[] = [];
const resources: Array<{ close(): Promise<unknown> }> = [];
const temporary: string[] = [];
afterEach(async () => {
await Promise.all(resources.splice(0).map(async (item) => item.close()));
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
await Promise.all(
temporary
.splice(0)
.map(async (path) => rm(path, { recursive: true, force: true })),
);
});
it("exposes root-confined Electron discovery and inspection as Evidence v2", async () => {
const root = await createTestTempDirectory("rea-electron-mcp-");
temporary.push(root);
await writeFile(join(root, "index.html"), "<script src='app.js'></script>");
await writeFile(
join(root, "app.js"),
"export const observed = 'source-secret';",
);
await writeFile(
join(root, "package.json"),
JSON.stringify({ name: "runtime-fixture", renderer: "index.html" }),
);
await writeFile(join(root, "worker.js"), "self.onmessage = () => {};\n");
const browser = await startFakeCdpBrowser({
electronFileUrl: pathToFileURL(join(root, "index.html")).href,
});
browsers.push(browser);
const config = parseConfig({
REA_ELECTRON_OBSERVE_ENABLED: "true",
REA_ELECTRON_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
REA_ELECTRON_FILE_ROOTS_JSON: JSON.stringify([root]),
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
});
if (!config.ok) throw config.error;
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok) throw authority.error;
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
electronObservation: new CdpElectronProvider(),
permissionAuthority: authority.value,
availabilityPolicy: () => ({
processCaptureEnabled: false,
evidenceFileRoots: 0,
investigationInputRoots: 1,
electronObservationEnabled: true,
}),
});
const client = new Client({ name: "electron-mcp-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server, session);
await server.connect(serverTransport);
await client.connect(clientTransport);
const listed = await client.callTool({
name: "list_electron_targets",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
approved: true,
},
});
expect(listed.isError).not.toBe(true);
expect(listed.structuredContent).toMatchObject({
result: {
targets: { items: [{ target_id: "electron-page" }] },
},
});
const inspected = await client.callTool({
name: "inspect_electron_page",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_file_roots: [root],
target_id: "electron-page",
approved: true,
observation_ms: 0,
include_script_sources: true,
source_capture_approved: true,
},
});
const analyzed = await client.callTool({
name: "analyze_javascript_application",
arguments: { input_path: root, approved: true, detail: "full" },
});
expect(analyzed.isError).not.toBe(true);
expect(analyzed.structuredContent).toMatchObject({
result: { graph: { nodes: expect.any(Array), edges: expect.any(Array) } },
});
const analysisText = analyzed.content.find(({ type }) => type === "text");
expect(analysisText).toBeDefined();
if (analysisText?.type !== "text")
throw new TypeError("Missing JavaScript analysis text projection");
expect(analysisText.text).not.toContain('"nodes":[');
const reconciled = await client.callTool({
name: "reconcile_javascript_runtime",
arguments: {
static_layers: [
{
role: "application",
analysis: evidenceFor(session, analyzed.structuredContent),
},
],
runtime_observations: [evidenceFor(session, inspected.structuredContent)],
},
});
expect(reconciled.isError).not.toBe(true);
expect(reconciled.structuredContent).toMatchObject({
result: {
summary: { runtime_scripts: 1, matched: expect.any(Number) },
source_map_authority: { used_for_primary_matching: false },
},
});
expect(inspected.isError).not.toBe(true);
expect(inspected.structuredContent).toMatchObject({
result: {
target: { file_path: expect.stringMatching(/\/index\.html$/u) },
scripts: {
items: [
expect.objectContaining({
frame_id: "frame-main",
file_path: expect.stringMatching(/\/app\.js$/u),
}),
],
},
workers: [
expect.objectContaining({
target_id: "electron-worker",
opener_target_id: "electron-page",
file_path: expect.stringMatching(/\/worker\.js$/u),
}),
],
},
});
const outside = join(root, "..", `outside-${Date.now().toString(16)}`);
await mkdir(outside);
temporary.push(outside);
const commandsBeforeDenial = browser.commands.length;
const denied = await client.callTool({
name: "list_electron_targets",
arguments: {
cdp_endpoint: browser.endpoint,
allowed_file_roots: [outside],
approved: true,
},
});
expect(denied.isError).toBe(true);
expect(denied.structuredContent).toMatchObject({
error: {
code: "permission_required",
details: { missing: { roots: [expect.stringMatching(/outside-/u)] } },
},
});
expect(browser.commands).toHaveLength(commandsBeforeDenial);
}, 20_000);
it("exposes the target-free static JavaScript application workflow", async () => {
const root = await createTestTempDirectory("rea-electron-static-mcp-");
temporary.push(root);
await writeElectronBoundaryFixture(root);
const config = parseConfig({
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
});
if (!config.ok) throw config.error;
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok) throw authority.error;
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
permissionAuthority: authority.value,
availabilityPolicy: () => ({
processCaptureEnabled: false,
evidenceFileRoots: 0,
investigationInputRoots: 1,
}),
});
const client = new Client({
name: "electron-static-mcp-test",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server, session);
await server.connect(serverTransport);
await client.connect(clientTransport);
const analyzed = await client.callTool({
name: "analyze_javascript_application",
arguments: { input_path: root, approved: true },
});
expect(analyzed.isError).not.toBe(true);
const projected = z
.object({
evidence_id: z.string(),
result: z.object({
schema_version: z.literal(2),
input_path: z.string(),
unknowns: z.array(z.string()),
summary: z.object({
browser_windows: z.number(),
context_bridge_apis: z.number(),
ipc: z.object({ paired_renderer_transmissions: z.number() }),
}),
graph: z.object({
graph_id: z.string(),
node_count: z.number(),
edge_count: z.number(),
top_findings: z.array(z.unknown()),
pages: z.object({ nodes: z.string(), edges: z.string() }),
}),
semantic_graph: z.object({
graph_id: z.string(),
nodes: z.number(),
relations: z.number(),
unknown_frontiers: z.number(),
query_tool: z.literal("trace_javascript_semantics"),
}),
}),
})
.parse(analyzed.structuredContent);
expect(projected.result).toMatchObject({
input_path: expect.stringMatching(/rea-electron-static-mcp-/u),
summary: {
browser_windows: 3,
context_bridge_apis: 2,
ipc: { paired_renderer_transmissions: 4 },
},
});
expect(projected.result.graph.node_count).toBeGreaterThan(0);
expect(projected.result.semantic_graph.nodes).toBeGreaterThan(0);
expect(JSON.stringify(analyzed.structuredContent)).not.toContain('"nodes":[');
const nodePage = await client.readResource({
uri: projected.result.graph.pages.nodes,
});
const nodeContent = nodePage.contents[0];
if (nodeContent === undefined || !("text" in nodeContent))
throw new TypeError("Missing JavaScript application graph node page");
expect(JSON.parse(nodeContent.text)).toMatchObject({
evidence_id: projected.evidence_id,
graph_id: projected.result.graph.graph_id,
collection: "nodes",
items: expect.any(Array),
offset: 0,
limit: 100,
});
});
it("reports an unconfigured investigation ceiling before static analysis", async () => {
const root = await createTestTempDirectory("rea-electron-denied-mcp-");
temporary.push(root);
await writeElectronBoundaryFixture(root);
const config = parseConfig({});
if (!config.ok) throw config.error;
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok) throw authority.error;
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
permissionAuthority: authority.value,
});
const client = new Client({
name: "electron-denied-mcp-test",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server, session);
await server.connect(serverTransport);
await client.connect(clientTransport);
const status = await client.callTool({
name: "binary_session",
arguments: {
detail: "capabilities",
capability_family: "electron-provider",
limit: 100,
},
});
expect(status.structuredContent).toMatchObject({
result: {
capabilities: {
items: expect.arrayContaining([
expect.objectContaining({
name: "analyze_javascript_application",
available: false,
reason: "policy_disabled",
}),
expect.objectContaining({
name: "reconcile_javascript_runtime",
available: true,
reason: "available",
}),
]),
},
},
});
expect(
(await client.listTools()).tools.some(
({ name }) => name === "analyze_javascript_application",
),
).toBe(false);
});
const evidenceFor = (session: BinarySession, value: unknown) => {
if (
typeof value !== "object" ||
value === null ||
!("evidence_id" in value) ||
typeof value.evidence_id !== "string"
)
throw new TypeError("Missing compact Evidence ID");
const evidence = session.evidenceById(value.evidence_id);
if (evidence === undefined) throw new TypeError("Missing session Evidence");
return evidence;
};
@@ -0,0 +1,315 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../../../src/contracts/managedWorkflowToolContracts.js";
import {
ENHANCED_TOOL_CONTRACTS,
SESSION_TOOL_CONTRACTS,
TOOL_CONTRACTS,
} from "../../../src/contracts/toolContracts.js";
import {
jsonValueSchema,
type JsonValue,
} from "../../../src/domain/jsonValue.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
const PROCEDURES = {
"0x1": "_TtC7Fixture5Class",
"0x2": "_TtV7Fixture6Struct",
"0x3": "_TtP7Fixture8Protocol",
"0x4": "_TtO7Fixture4Enum",
"0x5": "_TtE7Fixture9Extension",
"0x6": "prefix_TtOther",
};
const page = (values: Readonly<Record<string, string>>) => ({
items: Object.entries(values).map(([address, value]) => ({ address, value })),
offset: 0,
limit: 100,
total: Object.keys(values).length,
next_offset: null,
has_more: false,
});
const fixturePort = (): AnalysisOperationPort => ({
execute: (name, arguments_) => {
switch (name) {
case "list_procedures":
return Promise.resolve(ok(page(PROCEDURES)));
case "list_names":
return Promise.resolve(
ok(
page({
"0x10": "_OBJC_CLASS_$_Fixture",
"0x11": "_OBJC_CLASS_$_Fixture",
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
"0x13": "entry",
}),
),
);
case "procedure_pseudo_code": {
const procedure = arguments_.procedure;
return Promise.resolve(
ok(typeof procedure === "string" ? `pseudo:${procedure}` : "invalid"),
);
}
case "procedure_callees": {
const procedure = arguments_.procedure;
return Promise.resolve(
ok(
procedure === "0x1"
? ["0x2", "0x3"]
: procedure === "0x2"
? ["0x1"]
: [],
),
);
}
case "procedure_callers":
return Promise.resolve(ok(["0x9"]));
case "address_name":
return Promise.resolve(ok(arguments_.address ?? null));
case "xrefs":
return Promise.resolve(ok(["0x20", "0x21"]));
case "resolve_containing_procedure":
return Promise.resolve(
ok({
query_address:
typeof arguments_.address === "string"
? arguments_.address
: "0x0",
found: false,
procedure: null,
reason: "not_in_procedure",
}),
);
case "list_segments":
return Promise.resolve(
ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
);
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(ok(page({ "0x30": "hello" })));
case "analyze_function":
return Promise.resolve(
ok({
procedure: {
address: "0x1",
name: "entry",
signature: null,
locals: [],
},
pseudocode: {
text: "return 0;",
total_chars: 9,
returned_chars: 9,
truncated: false,
next_offset: null,
},
assembly: {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
},
comments: emptyBounded(),
callers: emptyBounded(),
callees: emptyBounded(),
incoming_references: emptyBounded(),
outgoing_references: emptyBounded(),
referenced_strings: emptyBounded(),
referenced_names: emptyBounded(),
basic_blocks: emptyBounded(),
instruction_scan: { scanned: 0, truncated: false },
}),
);
default:
return Promise.resolve(ok(null));
}
},
});
const emptyBounded = () => ({
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
});
const resources: Array<{ close(): Promise<void> }> = [];
afterEach(async () => {
await Promise.all(
resources.splice(0).map(async (resource) => resource.close()),
);
});
const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
const server = createServer(analysis);
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
return client;
};
const jsonResult = (result: CallToolResult): JsonValue => {
if (result.structuredContent === undefined)
throw new Error("Tool result omitted structured content");
const structured = jsonValueSchema.safeParse(result.structuredContent);
if (!structured.success)
throw new Error("Tool structured result was not JSON");
if (
typeof structured.data === "object" &&
structured.data !== null &&
!Array.isArray(structured.data) &&
"normalized_result" in structured.data
) {
return structured.data.normalized_result ?? null;
}
if (
typeof structured.data === "object" &&
structured.data !== null &&
!Array.isArray(structured.data) &&
"evidence_id" in structured.data &&
"result" in structured.data
)
return structured.data.result ?? null;
const text = result.content.find((item) => item.type === "text");
if (text?.type !== "text")
throw new Error("Tool result omitted text content");
const decoded: unknown = JSON.parse(text.text);
const parsed = jsonValueSchema.safeParse(decoded);
if (!parsed.success) throw new Error("Tool result was not JSON");
return parsed.data;
};
describe("enhanced MCP tools", () => {
it("lists the complete target-open analysis surface", async () => {
const client = await connect();
const listed = await client.listTools();
expect(listed.tools).toHaveLength(
TOOL_CONTRACTS.length -
SESSION_TOOL_CONTRACTS.length -
MANAGED_WORKFLOW_TOOL_CONTRACTS.length,
);
expect(
listed.tools
.map(({ name }) => name)
.filter((name) =>
ENHANCED_TOOL_CONTRACTS.some((tool) => tool.name === name),
)
.sort(),
).toEqual(ENHANCED_TOOL_CONTRACTS.map(({ name }) => name).sort());
});
it("executes all thirteen tools through production registration", async () => {
const client = await connect();
const calls = [
["swift_classes", { pattern: "Fixture" }],
["get_objc_classes", { pattern: "Fixture" }],
["get_objc_protocols", {}],
["batch_decompile", { addresses: ["0x1", "0x2"] }],
["get_call_graph", { address: "0x1", direction: "forward", depth: 2 }],
["analyze_swift_types", {}],
["find_xrefs_to_name", { name: "entry" }],
["binary_overview", {}],
["analyze_function", { procedure: "0x1" }],
["inspect_native_api", { procedure: "0x1" }],
["trace_feature", { query: "hello", max_operations: 10 }],
["find_code_for_string", { query: "hello", max_operations: 10 }],
["trace_call_path", { start: "0x1", goal: "0x2", max_operations: 10 }],
] as const;
const results = await Promise.all(
calls.map(async ([name, arguments_]) =>
jsonResult(await client.callTool({ name, arguments: arguments_ })),
),
);
expect(results[0]).toMatchObject({ count: 1 });
expect(results[1]).toMatchObject({ count: 1 });
expect(results[2]).toMatchObject({ count: 1 });
expect(results[3]).toEqual({
items: [
{ address: "0x1", status: "ok", pseudocode: "pseudo:0x1" },
{ address: "0x2", status: "ok", pseudocode: "pseudo:0x2" },
],
total: 2,
succeeded: 2,
failed: 0,
});
expect(results[4]).toEqual({
"0": [{ address: "0x1", status: "ok", calls: ["0x2", "0x3"] }],
"1": [
{ address: "0x2", status: "ok", calls: ["0x1"] },
{ address: "0x3", status: "ok", calls: [] },
],
});
expect(results[5]).toMatchObject({ total: 6 });
expect(results[6]).toEqual({
status: "resolved",
name: "entry",
address: "0x13",
xrefs: ["0x20", "0x21"],
});
expect(results[7]).toMatchObject({
document: "fixture",
segment_count: 1,
procedure_count: 6,
string_count: 1,
});
expect(results[8]).toMatchObject({
procedure: { address: "0x1", name: "entry" },
pseudocode: { text: "return 0;" },
});
expect(results[9]).toMatchObject({
procedure: { address: "0x1", name: "entry" },
boundary: { available: false },
unsupported_branches: [
"structured-boundary-types",
"jump-table-data-mapping",
],
residual_unknowns: expect.arrayContaining([
expect.stringContaining("boundary types"),
]),
substeps: [
{ operation: "analyze_function", status: "completed" },
{ operation: "project_native_api_boundary", status: "unsupported" },
{ operation: "preserve_residual_unknowns", status: "completed" },
],
});
expect(results[10]).toMatchObject({
query: "hello",
search_mode: "literal",
truncated: false,
references: [
{ target_address: "0x30", source_address: "0x20" },
{ target_address: "0x30", source_address: "0x21" },
],
});
expect(results[11]).toMatchObject({
query: "hello",
matches: [{ type: "string", address: "0x30", value: "hello" }],
truncated: false,
});
expect(results[12]).toMatchObject({
start: "0x1",
goal: "0x2",
direction: "forward",
goal_status: "reached",
traversal_path: ["0x1", "0x2"],
nodes: [
{ address: "0x1", depth: 0 },
{ address: "0x2", depth: 1 },
],
truncated: false,
});
});
});
@@ -0,0 +1,262 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
import { AnalysisOutputError } from "../../../src/domain/errors.js";
import { err } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
const PROCEDURES = {
"0x1": "_TtC7Fixture5Class",
"0x2": "_TtV7Fixture6Struct",
"0x3": "_TtP7Fixture8Protocol",
"0x4": "_TtO7Fixture4Enum",
"0x5": "_TtE7Fixture9Extension",
"0x6": "prefix_TtOther",
};
const page = (values: Readonly<Record<string, string>>) => ({
items: Object.entries(values).map(([address, value]) => ({ address, value })),
offset: 0,
limit: 100,
total: Object.keys(values).length,
next_offset: null,
has_more: false,
});
const fixturePort = (): AnalysisOperationPort => ({
execute: (name, arguments_) => {
switch (name) {
case "list_procedures":
return Promise.resolve(ok(page(PROCEDURES)));
case "list_names":
return Promise.resolve(
ok(
page({
"0x10": "_OBJC_CLASS_$_Fixture",
"0x11": "_OBJC_CLASS_$_Fixture",
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
"0x13": "entry",
}),
),
);
case "procedure_pseudo_code": {
const procedure = arguments_.procedure;
return Promise.resolve(
ok(typeof procedure === "string" ? `pseudo:${procedure}` : "invalid"),
);
}
case "procedure_callees": {
const procedure = arguments_.procedure;
return Promise.resolve(
ok(
procedure === "0x1"
? ["0x2", "0x3"]
: procedure === "0x2"
? ["0x1"]
: [],
),
);
}
case "procedure_callers":
return Promise.resolve(ok(["0x9"]));
case "address_name":
return Promise.resolve(ok(arguments_.address ?? null));
case "xrefs":
return Promise.resolve(ok(["0x20", "0x21"]));
case "resolve_containing_procedure":
return Promise.resolve(
ok({
query_address:
typeof arguments_.address === "string"
? arguments_.address
: "0x0",
found: false,
procedure: null,
reason: "not_in_procedure",
}),
);
case "list_segments":
return Promise.resolve(
ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
);
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(ok(page({ "0x30": "hello" })));
case "analyze_function":
return Promise.resolve(
ok({
procedure: {
address: "0x1",
name: "entry",
signature: null,
locals: [],
},
pseudocode: {
text: "return 0;",
total_chars: 9,
returned_chars: 9,
truncated: false,
next_offset: null,
},
assembly: {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
},
comments: emptyBounded(),
callers: emptyBounded(),
callees: emptyBounded(),
incoming_references: emptyBounded(),
outgoing_references: emptyBounded(),
referenced_strings: emptyBounded(),
referenced_names: emptyBounded(),
basic_blocks: emptyBounded(),
instruction_scan: { scanned: 0, truncated: false },
}),
);
default:
return Promise.resolve(ok(null));
}
},
});
const emptyBounded = () => ({
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
});
const resources: Array<{ close(): Promise<void> }> = [];
afterEach(async () => {
await Promise.all(
resources.splice(0).map(async (resource) => resource.close()),
);
});
const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
const server = createServer(analysis);
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
return client;
};
describe("enhanced MCP tools", () => {
it("returns Evidence IDs and explicit call-path frontiers at limits", async () => {
const client = await connect();
const result = await client.callTool({
name: "trace_call_path",
arguments: {
start: "0x1",
goal: "0x3",
max_nodes: 1,
max_operations: 10,
},
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
result: {
goal_status: "not_reached",
nodes: [{ address: "0x1", depth: 0 }],
frontier: ["0x2"],
truncated: true,
residual_unknowns: expect.arrayContaining([
expect.stringContaining("reached the node limit"),
expect.stringContaining("reached the edge limit"),
]),
limits: {
max_nodes: 1,
nodes_visited: 1,
operations_used: 1,
},
},
});
});
it("bounds batch concurrency at the parsed maximum of 20", async () => {
let active = 0;
let maximum = 0;
const analysis: AnalysisOperationPort = {
execute: async (name) => {
if (name !== "procedure_pseudo_code") return ok(null);
active += 1;
maximum = Math.max(maximum, active);
await new Promise((resolve) => setTimeout(resolve, 2));
active -= 1;
return ok("pseudo");
},
};
const client = await connect(analysis);
const result = await client.callTool({
name: "batch_decompile",
arguments: {
addresses: Array.from(
{ length: 20 },
(_, index) => `0x${String(index)}`,
),
},
});
expect(result.isError).not.toBe(true);
expect(maximum).toBe(20);
});
it("returns ordered typed batch failures and zero counts for empty input", async () => {
const tools = new EnhancedTools({
execute: (_name, arguments_) =>
arguments_.procedure === "0x2"
? Promise.resolve(err(new AnalysisOutputError("decompile", "failed")))
: Promise.resolve(ok("pseudo")),
});
const result = await tools.execute("batch_decompile", {
addresses: ["0x1", "0x2"],
});
const empty = await tools.execute("batch_decompile", { addresses: [] });
expect(result).toEqual({
ok: true,
value: {
items: [
{ address: "0x1", status: "ok", pseudocode: "pseudo" },
{
address: "0x2",
status: "error",
error: {
code: "unreadable_output",
category: "execution_failure",
message:
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
retryable: false,
remediation: {
action:
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
restart_required: false,
},
},
},
],
total: 2,
succeeded: 1,
failed: 1,
},
});
expect(empty).toEqual({
ok: true,
value: { items: [], total: 0, succeeded: 0, failed: 0 },
});
});
});
@@ -0,0 +1,297 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
import { AnalysisOutputError } from "../../../src/domain/errors.js";
import {
jsonValueSchema,
type JsonValue,
} from "../../../src/domain/jsonValue.js";
import { err } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
const PROCEDURES = {
"0x1": "_TtC7Fixture5Class",
"0x2": "_TtV7Fixture6Struct",
"0x3": "_TtP7Fixture8Protocol",
"0x4": "_TtO7Fixture4Enum",
"0x5": "_TtE7Fixture9Extension",
"0x6": "prefix_TtOther",
};
const page = (values: Readonly<Record<string, string>>) => ({
items: Object.entries(values).map(([address, value]) => ({ address, value })),
offset: 0,
limit: 100,
total: Object.keys(values).length,
next_offset: null,
has_more: false,
});
const fixturePort = (): AnalysisOperationPort => ({
execute: (name, arguments_) => {
switch (name) {
case "list_procedures":
return Promise.resolve(ok(page(PROCEDURES)));
case "list_names":
return Promise.resolve(
ok(
page({
"0x10": "_OBJC_CLASS_$_Fixture",
"0x11": "_OBJC_CLASS_$_Fixture",
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
"0x13": "entry",
}),
),
);
case "procedure_pseudo_code": {
const procedure = arguments_.procedure;
return Promise.resolve(
ok(typeof procedure === "string" ? `pseudo:${procedure}` : "invalid"),
);
}
case "procedure_callees": {
const procedure = arguments_.procedure;
return Promise.resolve(
ok(
procedure === "0x1"
? ["0x2", "0x3"]
: procedure === "0x2"
? ["0x1"]
: [],
),
);
}
case "procedure_callers":
return Promise.resolve(ok(["0x9"]));
case "address_name":
return Promise.resolve(ok(arguments_.address ?? null));
case "xrefs":
return Promise.resolve(ok(["0x20", "0x21"]));
case "resolve_containing_procedure":
return Promise.resolve(
ok({
query_address:
typeof arguments_.address === "string"
? arguments_.address
: "0x0",
found: false,
procedure: null,
reason: "not_in_procedure",
}),
);
case "list_segments":
return Promise.resolve(
ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
);
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(ok(page({ "0x30": "hello" })));
case "analyze_function":
return Promise.resolve(
ok({
procedure: {
address: "0x1",
name: "entry",
signature: null,
locals: [],
},
pseudocode: {
text: "return 0;",
total_chars: 9,
returned_chars: 9,
truncated: false,
next_offset: null,
},
assembly: {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
},
comments: emptyBounded(),
callers: emptyBounded(),
callees: emptyBounded(),
incoming_references: emptyBounded(),
outgoing_references: emptyBounded(),
referenced_strings: emptyBounded(),
referenced_names: emptyBounded(),
basic_blocks: emptyBounded(),
instruction_scan: { scanned: 0, truncated: false },
}),
);
default:
return Promise.resolve(ok(null));
}
},
});
const emptyBounded = () => ({
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
});
const resources: Array<{ close(): Promise<void> }> = [];
afterEach(async () => {
await Promise.all(
resources.splice(0).map(async (resource) => resource.close()),
);
});
const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
const server = createServer(analysis);
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
return client;
};
const jsonResult = (result: CallToolResult): JsonValue => {
if (result.structuredContent === undefined)
throw new Error("Tool result omitted structured content");
const structured = jsonValueSchema.safeParse(result.structuredContent);
if (!structured.success)
throw new Error("Tool structured result was not JSON");
if (
typeof structured.data === "object" &&
structured.data !== null &&
!Array.isArray(structured.data) &&
"normalized_result" in structured.data
) {
return structured.data.normalized_result ?? null;
}
if (
typeof structured.data === "object" &&
structured.data !== null &&
!Array.isArray(structured.data) &&
"evidence_id" in structured.data &&
"result" in structured.data
)
return structured.data.result ?? null;
const text = result.content.find((item) => item.type === "text");
if (text?.type !== "text")
throw new Error("Tool result omitted text content");
const decoded: unknown = JSON.parse(text.text);
const parsed = jsonValueSchema.safeParse(decoded);
if (!parsed.success) throw new Error("Tool result was not JSON");
return parsed.data;
};
describe("enhanced MCP tools", () => {
it("returns typed graph failures and stable unresolved-name results", async () => {
const tools = new EnhancedTools({
execute: (name) =>
name === "procedure_callees"
? Promise.resolve(err(new AnalysisOutputError(name, "failed")))
: Promise.resolve(ok(page({}))),
});
const graph = await tools.execute("get_call_graph", {
address: "0x1",
direction: "forward",
depth: 1,
});
const unresolved = await tools.execute("find_xrefs_to_name", {
name: "missing",
});
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`.",
},
},
],
},
});
expect(unresolved).toEqual({
ok: true,
value: {
status: "unresolved",
name: "missing",
reason: "name_not_found",
},
});
});
it("follows procedure pagination for whole-binary workflows", async () => {
const offsets: number[] = [];
const client = await connect({
execute: (_name, arguments_) => {
const offset = arguments_.offset;
offsets.push(typeof offset === "number" ? offset : 0);
return Promise.resolve(
ok({
items: [
{
address: offset === 500 ? "0x2" : "0x1",
value: offset === 500 ? "_TtC4Last" : "_TtC5First",
},
],
offset: typeof offset === "number" ? offset : 0,
limit: 500,
total: 2,
next_offset: offset === 500 ? null : 500,
has_more: offset !== 500,
}),
);
},
});
const result = jsonResult(
await client.callTool({ name: "swift_classes", arguments: {} }),
);
expect(offsets).toEqual([0, 500]);
expect(result).toMatchObject({ count: 2 });
});
it("does not start another page after cancellation", async () => {
const controller = new AbortController();
let calls = 0;
const analysis: AnalysisOperationPort = {
execute: () => {
calls += 1;
controller.abort();
return Promise.resolve(
ok({
items: [{ address: "0x1", value: "_TtC5First" }],
offset: 0,
limit: 500,
total: 2,
next_offset: 500,
has_more: true,
}),
);
},
};
const result = await new EnhancedTools(analysis).execute(
"swift_classes",
{},
controller.signal,
);
expect(calls).toBe(1);
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected cancellation");
expect(result.error._tag).toBe("AnalysisCancelledError");
});
});
@@ -0,0 +1,316 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import {
jsonValueSchema,
type JsonValue,
} from "../../../src/domain/jsonValue.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
const PROCEDURES = {
"0x1": "_TtC7Fixture5Class",
"0x2": "_TtV7Fixture6Struct",
"0x3": "_TtP7Fixture8Protocol",
"0x4": "_TtO7Fixture4Enum",
"0x5": "_TtE7Fixture9Extension",
"0x6": "prefix_TtOther",
};
const page = (values: Readonly<Record<string, string>>) => ({
items: Object.entries(values).map(([address, value]) => ({ address, value })),
offset: 0,
limit: 100,
total: Object.keys(values).length,
next_offset: null,
has_more: false,
});
const fixturePort = (): AnalysisOperationPort => ({
execute: (name, arguments_) => {
switch (name) {
case "list_procedures":
return Promise.resolve(ok(page(PROCEDURES)));
case "list_names":
return Promise.resolve(
ok(
page({
"0x10": "_OBJC_CLASS_$_Fixture",
"0x11": "_OBJC_CLASS_$_Fixture",
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
"0x13": "entry",
}),
),
);
case "procedure_pseudo_code": {
const procedure = arguments_.procedure;
return Promise.resolve(
ok(typeof procedure === "string" ? `pseudo:${procedure}` : "invalid"),
);
}
case "procedure_callees": {
const procedure = arguments_.procedure;
return Promise.resolve(
ok(
procedure === "0x1"
? ["0x2", "0x3"]
: procedure === "0x2"
? ["0x1"]
: [],
),
);
}
case "procedure_callers":
return Promise.resolve(ok(["0x9"]));
case "address_name":
return Promise.resolve(ok(arguments_.address ?? null));
case "xrefs":
return Promise.resolve(ok(["0x20", "0x21"]));
case "resolve_containing_procedure":
return Promise.resolve(
ok({
query_address:
typeof arguments_.address === "string"
? arguments_.address
: "0x0",
found: false,
procedure: null,
reason: "not_in_procedure",
}),
);
case "list_segments":
return Promise.resolve(
ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
);
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(ok(page({ "0x30": "hello" })));
case "analyze_function":
return Promise.resolve(
ok({
procedure: {
address: "0x1",
name: "entry",
signature: null,
locals: [],
},
pseudocode: {
text: "return 0;",
total_chars: 9,
returned_chars: 9,
truncated: false,
next_offset: null,
},
assembly: {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
},
comments: emptyBounded(),
callers: emptyBounded(),
callees: emptyBounded(),
incoming_references: emptyBounded(),
outgoing_references: emptyBounded(),
referenced_strings: emptyBounded(),
referenced_names: emptyBounded(),
basic_blocks: emptyBounded(),
instruction_scan: { scanned: 0, truncated: false },
}),
);
default:
return Promise.resolve(ok(null));
}
},
});
const emptyBounded = () => ({
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
});
const resources: Array<{ close(): Promise<void> }> = [];
afterEach(async () => {
await Promise.all(
resources.splice(0).map(async (resource) => resource.close()),
);
});
const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
const server = createServer(analysis);
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
return client;
};
const jsonResult = (result: CallToolResult): JsonValue => {
if (result.structuredContent === undefined)
throw new Error("Tool result omitted structured content");
const structured = jsonValueSchema.safeParse(result.structuredContent);
if (!structured.success)
throw new Error("Tool structured result was not JSON");
if (
typeof structured.data === "object" &&
structured.data !== null &&
!Array.isArray(structured.data) &&
"normalized_result" in structured.data
) {
return structured.data.normalized_result ?? null;
}
if (
typeof structured.data === "object" &&
structured.data !== null &&
!Array.isArray(structured.data) &&
"evidence_id" in structured.data &&
"result" in structured.data
)
return structured.data.result ?? null;
const text = result.content.find((item) => item.type === "text");
if (text?.type !== "text")
throw new Error("Tool result omitted text content");
const decoded: unknown = JSON.parse(text.text);
const parsed = jsonValueSchema.safeParse(decoded);
if (!parsed.success) throw new Error("Tool result was not JSON");
return parsed.data;
};
describe("enhanced MCP tools", () => {
it("follows name pagination for exhaustive Objective-C discovery", async () => {
const offsets: number[] = [];
const client = await connect({
execute: (name, arguments_) => {
expect(name).toBe("list_names");
const offset =
typeof arguments_.offset === "number" ? arguments_.offset : 0;
offsets.push(offset);
return Promise.resolve(
ok({
items: [
{
address: offset === 500 ? "0x2" : "0x1",
value:
offset === 500 ? "_OBJC_CLASS_$_Last" : "_OBJC_CLASS_$_First",
},
],
offset,
limit: 500,
total: 2,
next_offset: offset === 500 ? null : 500,
has_more: offset !== 500,
}),
);
},
});
const result = jsonResult(
await client.callTool({ name: "get_objc_classes", arguments: {} }),
);
expect(offsets).toEqual([0, 500]);
expect(result).toMatchObject({ count: 2 });
});
it("honors overview detail and limit while reporting exhaustive totals", async () => {
const procedureOffsets: number[] = [];
const client = await connect({
execute: (name, arguments_) => {
switch (name) {
case "list_segments":
return Promise.resolve(
ok([
{ name: "__TEXT", start: "0x1000", end: "0x1800" },
{ name: "__DATA", start: "0x1800", end: "0x2000" },
]),
);
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(
ok({
items: [{ address: "0x30", value: "first page only" }],
offset: 0,
limit: 100,
total: 700,
next_offset: 100,
has_more: true,
}),
);
case "list_procedures": {
const offset =
typeof arguments_.offset === "number" ? arguments_.offset : 0;
procedureOffsets.push(offset);
return Promise.resolve(
ok({
items: [
{
address: offset === 500 ? "0x2" : "0x1",
value: offset === 500 ? "last" : "first",
},
],
offset,
limit: 500,
total: 2,
next_offset: offset === 500 ? null : 500,
has_more: offset !== 500,
}),
);
}
default:
return Promise.resolve(ok(null));
}
},
});
const result = jsonResult(
await client.callTool({
name: "binary_overview",
arguments: { detail: "detailed", limit: 1 },
}),
);
expect(procedureOffsets).toEqual([0]);
expect(result).toEqual({
document: "fixture",
detail: "detailed",
segments: [
{ name: "__TEXT", start: "0x1000", end: "0x1800", length: 2048 },
],
segment_count: 2,
procedure_count: 2,
string_count: 700,
});
});
it("rejects non-advancing pagination metadata", async () => {
const client = await connect({
execute: () =>
Promise.resolve(
ok({
items: [{ address: "0x1", value: "_TtC5First" }],
offset: 0,
limit: 500,
total: 2,
next_offset: 0,
has_more: true,
}),
),
});
const result = await client.callTool({
name: "swift_classes",
arguments: {},
});
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
expect(text?.type === "text" ? text.text : "").toBe(
JSON.stringify(result.structuredContent),
);
});
});
@@ -0,0 +1,304 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import {
jsonValueSchema,
type JsonValue,
} from "../../../src/domain/jsonValue.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
const PROCEDURES = {
"0x1": "_TtC7Fixture5Class",
"0x2": "_TtV7Fixture6Struct",
"0x3": "_TtP7Fixture8Protocol",
"0x4": "_TtO7Fixture4Enum",
"0x5": "_TtE7Fixture9Extension",
"0x6": "prefix_TtOther",
};
const page = (values: Readonly<Record<string, string>>) => ({
items: Object.entries(values).map(([address, value]) => ({ address, value })),
offset: 0,
limit: 100,
total: Object.keys(values).length,
next_offset: null,
has_more: false,
});
const fixturePort = (): AnalysisOperationPort => ({
execute: (name, arguments_) => {
switch (name) {
case "list_procedures":
return Promise.resolve(ok(page(PROCEDURES)));
case "list_names":
return Promise.resolve(
ok(
page({
"0x10": "_OBJC_CLASS_$_Fixture",
"0x11": "_OBJC_CLASS_$_Fixture",
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
"0x13": "entry",
}),
),
);
case "procedure_pseudo_code": {
const procedure = arguments_.procedure;
return Promise.resolve(
ok(typeof procedure === "string" ? `pseudo:${procedure}` : "invalid"),
);
}
case "procedure_callees": {
const procedure = arguments_.procedure;
return Promise.resolve(
ok(
procedure === "0x1"
? ["0x2", "0x3"]
: procedure === "0x2"
? ["0x1"]
: [],
),
);
}
case "procedure_callers":
return Promise.resolve(ok(["0x9"]));
case "address_name":
return Promise.resolve(ok(arguments_.address ?? null));
case "xrefs":
return Promise.resolve(ok(["0x20", "0x21"]));
case "resolve_containing_procedure":
return Promise.resolve(
ok({
query_address:
typeof arguments_.address === "string"
? arguments_.address
: "0x0",
found: false,
procedure: null,
reason: "not_in_procedure",
}),
);
case "list_segments":
return Promise.resolve(
ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
);
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(ok(page({ "0x30": "hello" })));
case "analyze_function":
return Promise.resolve(
ok({
procedure: {
address: "0x1",
name: "entry",
signature: null,
locals: [],
},
pseudocode: {
text: "return 0;",
total_chars: 9,
returned_chars: 9,
truncated: false,
next_offset: null,
},
assembly: {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
},
comments: emptyBounded(),
callers: emptyBounded(),
callees: emptyBounded(),
incoming_references: emptyBounded(),
outgoing_references: emptyBounded(),
referenced_strings: emptyBounded(),
referenced_names: emptyBounded(),
basic_blocks: emptyBounded(),
instruction_scan: { scanned: 0, truncated: false },
}),
);
default:
return Promise.resolve(ok(null));
}
},
});
const emptyBounded = () => ({
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
});
const resources: Array<{ close(): Promise<void> }> = [];
afterEach(async () => {
await Promise.all(
resources.splice(0).map(async (resource) => resource.close()),
);
});
const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
const server = createServer(analysis);
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
return client;
};
const jsonResult = (result: CallToolResult): JsonValue => {
if (result.structuredContent === undefined)
throw new Error("Tool result omitted structured content");
const structured = jsonValueSchema.safeParse(result.structuredContent);
if (!structured.success)
throw new Error("Tool structured result was not JSON");
if (
typeof structured.data === "object" &&
structured.data !== null &&
!Array.isArray(structured.data) &&
"normalized_result" in structured.data
) {
return structured.data.normalized_result ?? null;
}
if (
typeof structured.data === "object" &&
structured.data !== null &&
!Array.isArray(structured.data) &&
"evidence_id" in structured.data &&
"result" in structured.data
)
return structured.data.result ?? null;
const text = result.content.find((item) => item.type === "text");
if (text?.type !== "text")
throw new Error("Tool result omitted text content");
const decoded: unknown = JSON.parse(text.text);
const parsed = jsonValueSchema.safeParse(decoded);
if (!parsed.success) throw new Error("Tool result was not JSON");
return parsed.data;
};
describe("enhanced MCP tools", () => {
it("stops trace_feature at its explicit operation budget", async () => {
let operations = 0;
const client = await connect({
execute: () => {
operations += 1;
return Promise.resolve(
ok({
items: [{ address: "0x1", value: "needle" }],
offset: 0,
limit: 500,
total: 2,
next_offset: 1,
has_more: true,
}),
);
},
});
const result = jsonResult(
await client.callTool({
name: "trace_feature",
arguments: { query: "needle", max_operations: 1 },
}),
);
expect(operations).toBe(1);
expect(result).toMatchObject({
operations_used: 1,
operation_budget: 1,
truncated: true,
});
expect(JSON.stringify(result)).toContain("operation budget");
});
it("returns correction-only structured validation issues", async () => {
const client = await connect();
const valid = await client.callTool({
name: "trace_feature",
arguments: { query: "needle", max_operations: 1 },
});
expect(valid.isError).not.toBe(true);
const misspelled = await client.callTool({
name: "trace_feature",
arguments: { query: "needle", max_operatons: 1 },
});
expect(misspelled).toMatchObject({
isError: true,
structuredContent: {
error: {
code: "invalid_request",
retryable: true,
details: {
issues: [{ path: ["max_operatons"], reason: "unknown_argument" }],
},
},
},
});
const nestedMisspelled = await client.callTool({
name: "analyze_function",
arguments: {
procedure: "0x1",
collection_offset: { commentz: 1 },
},
});
expect(nestedMisspelled).toMatchObject({
isError: true,
structuredContent: {
error: {
details: {
issues: [
{
path: ["collection_offset", "commentz"],
reason: "unknown_argument",
},
],
},
},
},
});
const bounded = await client.callTool({
name: "trace_feature",
arguments: { query: "needle", max_operations: 101 },
});
expect(bounded.structuredContent).toMatchObject({
error: {
details: {
issues: [
{
path: ["max_operations"],
reason: "out_of_range",
maximum: 100,
},
],
},
},
});
expect(bounded.content[0]).toEqual({
type: "text",
text: JSON.stringify(bounded.structuredContent),
});
});
it("returns a typed tool error for malformed Hopper boundary values", async () => {
const client = await connect({
execute: () => Promise.resolve(ok(["not", "a", "procedure", "map"])),
});
const result = await client.callTool({
name: "swift_classes",
arguments: {},
});
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
expect(text?.type === "text" ? text.text : "").toBe(
JSON.stringify(result.structuredContent),
);
});
});
@@ -0,0 +1,242 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
const PROCEDURES = {
"0x1": "_TtC7Fixture5Class",
"0x2": "_TtV7Fixture6Struct",
"0x3": "_TtP7Fixture8Protocol",
"0x4": "_TtO7Fixture4Enum",
"0x5": "_TtE7Fixture9Extension",
"0x6": "prefix_TtOther",
};
const page = (values: Readonly<Record<string, string>>) => ({
items: Object.entries(values).map(([address, value]) => ({ address, value })),
offset: 0,
limit: 100,
total: Object.keys(values).length,
next_offset: null,
has_more: false,
});
const fixturePort = (): AnalysisOperationPort => ({
execute: (name, arguments_) => {
switch (name) {
case "list_procedures":
return Promise.resolve(ok(page(PROCEDURES)));
case "list_names":
return Promise.resolve(
ok(
page({
"0x10": "_OBJC_CLASS_$_Fixture",
"0x11": "_OBJC_CLASS_$_Fixture",
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
"0x13": "entry",
}),
),
);
case "procedure_pseudo_code": {
const procedure = arguments_.procedure;
return Promise.resolve(
ok(typeof procedure === "string" ? `pseudo:${procedure}` : "invalid"),
);
}
case "procedure_callees": {
const procedure = arguments_.procedure;
return Promise.resolve(
ok(
procedure === "0x1"
? ["0x2", "0x3"]
: procedure === "0x2"
? ["0x1"]
: [],
),
);
}
case "procedure_callers":
return Promise.resolve(ok(["0x9"]));
case "address_name":
return Promise.resolve(ok(arguments_.address ?? null));
case "xrefs":
return Promise.resolve(ok(["0x20", "0x21"]));
case "resolve_containing_procedure":
return Promise.resolve(
ok({
query_address:
typeof arguments_.address === "string"
? arguments_.address
: "0x0",
found: false,
procedure: null,
reason: "not_in_procedure",
}),
);
case "list_segments":
return Promise.resolve(
ok([{ name: "__TEXT", start: "0x1000", end: "0x2000" }]),
);
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(ok(page({ "0x30": "hello" })));
case "analyze_function":
return Promise.resolve(
ok({
procedure: {
address: "0x1",
name: "entry",
signature: null,
locals: [],
},
pseudocode: {
text: "return 0;",
total_chars: 9,
returned_chars: 9,
truncated: false,
next_offset: null,
},
assembly: {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
},
comments: emptyBounded(),
callers: emptyBounded(),
callees: emptyBounded(),
incoming_references: emptyBounded(),
outgoing_references: emptyBounded(),
referenced_strings: emptyBounded(),
referenced_names: emptyBounded(),
basic_blocks: emptyBounded(),
instruction_scan: { scanned: 0, truncated: false },
}),
);
default:
return Promise.resolve(ok(null));
}
},
});
const emptyBounded = () => ({
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
});
const resources: Array<{ close(): Promise<void> }> = [];
afterEach(async () => {
await Promise.all(
resources.splice(0).map(async (resource) => resource.close()),
);
});
const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
const server = createServer(analysis);
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
return client;
};
describe("enhanced MCP tools", () => {
it("rejects incomplete function dossiers at the application boundary", async () => {
const client = await connect({
execute: () =>
Promise.resolve(
ok({
procedure: { address: "0x1", name: "entry" },
pseudocode: { text: "plausible but incomplete" },
}),
),
});
const result = await client.callTool({
name: "analyze_function",
arguments: { procedure: "0x1" },
});
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
expect(text?.type === "text" ? text.text : "").toBe(
JSON.stringify(result.structuredContent),
);
});
it("rejects deceptive function dossier collection metadata", async () => {
const malformedPort = fixturePort();
const client = await connect({
execute: async (name, arguments_, options) => {
const result = await malformedPort.execute(name, arguments_, options);
if (!result.ok || name !== "analyze_function") return result;
const dossier = result.value.result;
if (
typeof dossier !== "object" ||
dossier === null ||
Array.isArray(dossier)
)
return result;
return ok({
...dossier,
comments: {
items: [],
total: 0,
returned: 1,
truncated: false,
next_offset: null,
},
});
},
});
const result = await client.callTool({
name: "analyze_function",
arguments: { procedure: "0x1" },
});
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
expect(text?.type === "text" ? text.text : "").toBe(
JSON.stringify(result.structuredContent),
);
});
it("accepts a final dossier page whose total exceeds returned", async () => {
const malformedPort = fixturePort();
const client = await connect({
execute: async (name, arguments_, options) => {
const result = await malformedPort.execute(name, arguments_, options);
if (!result.ok || name !== "analyze_function") return result;
const dossier = result.value.result;
if (
typeof dossier !== "object" ||
dossier === null ||
Array.isArray(dossier)
)
return result;
return ok({
...dossier,
callers: {
items: [],
total: 1,
returned: 0,
truncated: false,
next_offset: null,
},
});
},
});
const result = await client.callTool({
name: "analyze_function",
arguments: { procedure: "0x1" },
});
expect(result.isError).not.toBe(true);
});
});
@@ -0,0 +1,269 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { createServer } from "../../../src/server/createServer.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { createInvestigationWorkspace } from "../../../src/domain/investigationWorkspace.js";
const provider = { id: "fixture", name: "Fixture", version: "1" };
interface ResourceFixture {
readonly evidence: ReturnType<typeof createEvidence>;
readonly capture: ReturnType<typeof createEvidence>;
readonly workspace: ReturnType<typeof createInvestigationWorkspace>;
readonly unknown: ReturnType<BinarySession["recordUnknown"]>;
}
function seedResourceFixture(session: BinarySession): ResourceFixture {
const evidence = createEvidence(undefined, provider, {
operation: "resource_probe",
parameters: {},
result: { observed: true },
});
session.recordEvidence(evidence);
const capture = createEvidence(undefined, provider, {
operation: "capture_process_scenario",
parameters: {},
result: {
frames: [{ sequence: 0, at_ms: 0, data: "ready" }],
protocol_events: [],
replay_transitions: [],
},
});
session.recordEvidence(capture);
const workspace = createInvestigationWorkspace(
"resource test",
createEvidenceBundle([]),
[],
);
session.retainInvestigationWorkspace(workspace);
const unknown = session.recordUnknown({
approved: true,
question: "Was every branch observed?",
severity: "medium",
domain: "control-flow",
supporting_evidence_ids: [evidence.evidence_id],
contradicting_evidence_ids: [],
required_authority: "controlled-replay",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
});
expect(unknown.ok).toBe(true);
return { evidence, capture, workspace, unknown };
}
async function verifyResourceProtocol(
client: Client,
fixture: ResourceFixture,
): Promise<void> {
const { evidence, capture, workspace, unknown } = fixture;
const templates = await client.listResourceTemplates();
expect(templates.resourceTemplates).toContainEqual(
expect.objectContaining({ uriTemplate: "rea://evidence/{evidenceId}" }),
);
expect(
templates.resourceTemplates.map(({ uriTemplate }) => uriTemplate),
).toEqual(
expect.arrayContaining([
"rea://artifact/{manifestId}/{collection}",
"rea://function/{targetSha256}/{address}",
"rea://evidence-bundle/{bundleDigest}",
"rea://workspace/{workspaceId}/revision/{revision}",
]),
);
expect(templates.resourceTemplates).toContainEqual(
expect.objectContaining({
uriTemplate: "rea://evidence/{evidenceId}/section/{section}",
}),
);
const listed = await client.listResources();
expect(listed.resources).toContainEqual(
expect.objectContaining({ uri: "rea://snapshot/current" }),
);
expect(listed.resources).not.toContainEqual(
expect.objectContaining({
uri: `rea://evidence/${evidence.evidence_id}`,
}),
);
const read = await client.readResource({
uri: `rea://evidence/${evidence.evidence_id}`,
});
expect(read.contents).toEqual([
expect.objectContaining({
uri: `rea://evidence/${evidence.evidence_id}`,
mimeType: "application/json",
text: expect.stringContaining(evidence.evidence_id),
}),
]);
const firstSnapshot = await client.callTool({
name: "snapshot_evidence_bundle",
arguments: {},
});
const secondSnapshot = await client.callTool({
name: "snapshot_evidence_bundle",
arguments: {},
});
expect(secondSnapshot.structuredContent).toEqual(
firstSnapshot.structuredContent,
);
expect(firstSnapshot.content).toContainEqual(
expect.objectContaining({
type: "text",
text: expect.stringContaining("Copy the opaque URI exactly"),
}),
);
const bundleUri = z
.object({ result: z.object({ bundle_uri: z.string() }) })
.parse(firstSnapshot.structuredContent).result.bundle_uri;
const retainedBundle = await client.readResource({ uri: bundleUri });
expect(retainedBundle.contents[0]).toEqual(
expect.objectContaining({
uri: bundleUri,
text: expect.stringContaining(evidence.evidence_id),
}),
);
const terminal = await client.readResource({
uri: `rea://evidence/${capture.evidence_id}/section/terminal`,
});
const workspaceResource = await client.readResource({
uri: `rea://workspace/${workspace.workspace_id}/revision/${String(workspace.revision)}`,
});
expect(workspaceResource.contents[0]).toEqual(
expect.objectContaining({
text: expect.stringContaining(workspace.revision_digest),
}),
);
expect(terminal.contents[0]).toEqual(
expect.objectContaining({ text: expect.stringContaining("ready") }),
);
if (unknown.ok) {
const unknownResource = await client.readResource({
uri: `rea://unknown/${unknown.value.unknown_id}`,
});
expect(unknownResource.contents[0]).toEqual(
expect.objectContaining({
text: expect.stringContaining(unknown.value.revision_digest),
}),
);
}
await expect(
client.readResource({ uri: `rea://evidence/ev_${"0".repeat(64)}` }),
).rejects.toThrow(/not found/iu);
}
describe("evidence MCP resources", () => {
it("publishes mutable snapshot changes for every Evidence mutation", () => {
const session = composeBinarySessionFromFactory(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
let updates = 0;
session.onAnalysisSnapshotChanged(() => {
updates += 1;
});
const first = createEvidence(undefined, provider, {
operation: "notification_probe",
parameters: {},
result: 1,
});
expect(session.recordEvidence(first)).toEqual({ ok: true, value: "added" });
expect(session.recordEvidence(first)).toEqual({
ok: true,
value: "duplicate",
});
const imported = createEvidence(undefined, provider, {
operation: "import_notification_probe",
parameters: {},
result: 2,
});
expect(
session.importEvidenceBundle(createEvidenceBundle([imported])),
).toEqual({ ok: true, value: 1 });
expect(
session.recordUnknown({
approved: true,
question: "Does mutation publish a snapshot update?",
severity: "low",
domain: "notifications",
supporting_evidence_ids: [first.evidence_id],
contradicting_evidence_ids: [],
required_authority: "controlled-replay",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
}).ok,
).toBe(true);
expect(updates).toBe(3);
});
it("retains bundles without eviction and rejects a seventeenth digest", () => {
const session = composeBinarySessionFromFactory(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const first = session.snapshotEvidenceBundle();
expect(first.ok).toBe(true);
for (let index = 0; index < 15; index += 1) {
session.recordEvidence(
createEvidence(undefined, provider, {
operation: `retention_probe_${String(index)}`,
parameters: {},
result: index,
}),
);
expect(session.snapshotEvidenceBundle().ok).toBe(true);
}
session.recordEvidence(
createEvidence(undefined, provider, {
operation: "retention_probe_overflow",
parameters: {},
result: true,
}),
);
expect(session.snapshotEvidenceBundle()).toMatchObject({
ok: false,
error: { _tag: "EvidenceLimitError", limit: "records", maximum: 16 },
});
if (first.ok)
expect(session.retainedEvidenceBundle(first.value.bundleDigest)).toEqual(
expect.any(String),
);
});
it("lists and reads only evidence owned by the current session", async () => {
const session = composeBinarySessionFromFactory(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const fixture = seedResourceFixture(session);
const server = createServer(session, session);
const client = new Client({
name: "evidence-resource-test",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
await verifyResourceProtocol(client, fixture);
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
}, 10_000);
});
@@ -0,0 +1,152 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
describe("function comparison MCP integration", () => {
it("records linked comparison Evidence and an approved residual unknown", async () => {
const session = composeBinarySessionFromFactory(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
expect(session.recordEvidence(FUNCTION_COMPARISON_EXAMPLE.left).ok).toBe(
true,
);
expect(session.recordEvidence(FUNCTION_COMPARISON_EXAMPLE.right).ok).toBe(
true,
);
const server = createServer(session, session);
const client = new Client({
name: "function-comparison-test",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "compare_functions",
arguments: {
left_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.left.evidence_id],
right_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.right.evidence_id],
unknown_registry_approved: true,
},
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
result: { status: expect.any(String) },
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
evidence_uri: expect.stringMatching(/^rea:\/\/evidence\/ev_/u),
});
const unknowns = await client.callTool({
name: "list_unknowns",
arguments: { domain: "function-comparison" },
});
expect(unknowns.structuredContent).toMatchObject({
result: {
items: [
expect.objectContaining({
unknown: expect.objectContaining({
domain: "function-comparison",
recommended_probes: [
expect.objectContaining({
rationale:
"Capture complete dossiers for both functions under the same target context and analysis limits.",
}),
],
}),
}),
],
},
});
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
});
it("rejects dangling Evidence links before recording output", async () => {
const session = composeBinarySessionFromFactory(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session);
const client = new Client({ name: "function-link-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "compare_functions",
arguments: {
left_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.left.evidence_id],
right_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.right.evidence_id],
},
});
expect(result.isError).toBe(true);
expect(session.exportEvidenceBundle().records).toEqual([]);
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
});
it("rejects Evidence IDs with the wrong operation", async () => {
const session = composeBinarySessionFromFactory(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const wrong = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: "inventory_artifact",
parameters: {},
result: {},
},
);
session.recordEvidence(wrong);
session.recordEvidence(FUNCTION_COMPARISON_EXAMPLE.right);
const server = createServer(session, session);
const client = new Client({
name: "function-authority-test",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "compare_functions",
arguments: {
left_evidence_ids: [wrong.evidence_id],
right_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.right.evidence_id],
},
});
expect(result.isError).toBe(true);
expect(session.exportEvidenceBundle().records).toHaveLength(2);
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
});
});
@@ -0,0 +1,150 @@
import { describe, expect, it } from "vitest";
import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js";
describe("Ghidra MCP evidence parity", () => {
it("preserves provider evidence, composed parity, and capability routing", async () => {
const harness = await connectGhidraMcp("ghidra-parity");
const { mcp, session } = harness;
try {
const listed = sessionEvidence(
session,
(
await mcp.callTool({
name: "list_procedures",
arguments: {},
})
).structuredContent,
);
expect(listed).toMatchObject({
operation: "list_procedures",
provider: { id: "ghidra", name: "Ghidra", version: "12.1.2" },
analysis_profile: {
provider: { id: "ghidra", version: "12.1.2" },
parameters: {
import_mode: "ephemeral-read-only",
analyzer_preset: "ghidra-default",
},
},
normalized_result: {
items: [
{
address: "0x401000",
value: "fixture_main",
procedure: {
external: false,
thunk: false,
thunk_target: null,
},
},
],
total: 1,
},
raw_result: {
items: [{ value_truncated: false }],
},
});
const mcpOverview = sessionEvidence(
session,
(
await mcp.callTool({
name: "binary_overview",
arguments: { detail: "detailed", limit: 5 },
})
).structuredContent,
);
const directOverview = await new EnhancedTools(session).execute(
"binary_overview",
{ detail: "detailed", limit: 5 },
);
expect(directOverview.ok).toBe(true);
if (!directOverview.ok) return;
expect(mcpOverview.normalized_result).toEqual(directOverview.value);
expect(mcpOverview).toMatchObject({
provider: { id: "rea-workflow" },
confidence: "derived",
normalized_result: {
document: "fixture",
segment_count: 1,
procedure_count: 1,
string_count: 2,
segments: [{ name: ".text", length: 256 }],
},
});
const pseudocode = sessionEvidence(
session,
(
await mcp.callTool({
name: "procedure_pseudo_code",
arguments: { procedure: "fixture_main" },
})
).structuredContent,
);
expect(pseudocode).toMatchObject({
operation: "procedure_pseudo_code",
provider: { id: "ghidra", version: "12.1.2" },
normalized_result: expect.stringContaining("return 42"),
limitations: expect.arrayContaining([
expect.stringContaining("not text-equivalent to Hopper"),
expect.stringContaining("30-second native deadline"),
]),
});
const analyzed = sessionEvidence(
session,
(
await mcp.callTool({
name: "analyze_function",
arguments: { procedure: "fixture_main", include_assembly: true },
})
).structuredContent,
);
expect(analyzed).toMatchObject({
operation: "analyze_function",
provider: { id: "rea-workflow", version: "1" },
normalized_result: {
procedure: {
address: "0x401000",
name: "fixture_main",
classification: {
external: false,
thunk: false,
provenance: "ghidra-function-manager",
},
},
pseudocode: { truncated: false },
outgoing_references: {
items: [
{
kind: {
available: true,
provenance: "ghidra-reference-manager",
},
},
],
},
limitations: expect.arrayContaining([
expect.stringContaining("indirect flows without target addresses"),
expect.stringContaining(
"not original source or Hopper-equivalent text",
),
]),
},
limitations: [
"Derived by an REA workflow from one or more provider observations.",
],
});
const directAnalyzed = await new EnhancedTools(session).execute(
"analyze_function",
{ procedure: "fixture_main", include_assembly: true },
);
expect(directAnalyzed.ok).toBe(true);
if (!directAnalyzed.ok) return;
expect(analyzed.normalized_result).toEqual(directAnalyzed.value);
} finally {
await harness.close();
}
}, 30_000);
});
+299
View File
@@ -0,0 +1,299 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { composeBinarySession } from "../../../src/application/BinarySessionComposition.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import { AnalysisProviderRegistry } from "../../../src/application/AnalysisProviderRegistry.js";
import { SessionProviderRouter } from "../../../src/application/SessionProviderRouter.js";
import { parseConfig } from "../../../src/config.js";
import type { JsonValue } from "../../../src/domain/jsonValue.js";
import { ok } from "../../../src/domain/result.js";
import type { GhidraInstallationHost } from "../../../src/ghidra/GhidraInstallation.js";
import type { GhidraOperation } from "../../../src/ghidra/GhidraClient.js";
import {
GhidraProvider,
type GhidraProviderClientFactory,
} from "../../../src/ghidra/GhidraProvider.js";
import { GHIDRA_SESSION_CAPABILITIES } from "../../../src/ghidra/GhidraSessionValues.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import {
ghidraBounded,
ghidraFunctionClassification,
ghidraFunctionDossier,
ghidraFunctionIdentity,
ghidraReferenceEdge,
} from "../../fixtures/ghidraFunction.js";
const INSTALL = "/opt/ghidra_12.1.2_PUBLIC";
export const connectGhidraMcp = async (name: string) => {
const calls: GhidraOperation[] = [];
const factory: GhidraProviderClientFactory = (options) => ({
start: () =>
Promise.resolve(
ok(sessionInfo(options.profileDigest, options.targetSha256)),
),
callTool: (operation, input) => {
calls.push(operation);
return Promise.resolve(ok(resultFor(operation, input)));
},
close: () => Promise.resolve(),
});
const config = parseConfig({ GHIDRA_INSTALL_DIR: INSTALL });
if (!config.ok) throw config.error;
const provider = new GhidraProvider(
config.value,
silentLogger,
installationHost(),
factory,
);
const session = composeBinarySession(
SessionProviderRouter.selectable(
new AnalysisProviderRegistry([provider]),
[],
),
);
const server = createServer(session, session, { logger: silentLogger });
const mcp = new Client({ name, version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const close = async () => {
await Promise.allSettled([mcp.close(), server.close()]);
await session.close();
};
try {
await server.connect(serverTransport);
await mcp.connect(clientTransport);
const opened = await mcp.callTool({
name: "open_binary",
arguments: { path: process.execPath },
});
if (opened.isError === true)
throw new Error("The Ghidra MCP harness could not open its target");
} catch (cause: unknown) {
await close();
throw cause;
}
return {
calls,
mcp,
session,
close,
};
};
export const sessionEvidence = (session: BinarySession, value: unknown) => {
if (
typeof value !== "object" ||
value === null ||
!("evidence_id" in value) ||
typeof value.evidence_id !== "string"
)
throw new TypeError(
`Missing compact Evidence ID: ${JSON.stringify(value)}`,
);
const evidence = session.evidenceById(value.evidence_id);
if (evidence === undefined) throw new TypeError("Missing session Evidence");
return evidence;
};
const installationHost = (): GhidraInstallationHost => ({
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.2\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
major: 21,
home: "/usr/lib/jvm/jdk-21",
bits: 64,
jdk: true,
}),
});
const sessionInfo = (profileDigest: string, targetSha256: string) => ({
name: "REA Ghidra bridge" as const,
bridge_version: 6 as const,
run_id: "11111111-1111-4111-8111-111111111111",
profile_digest: profileDigest,
provider: { id: "ghidra" as const, version: "12.1.2" },
read_only: true as const,
analysis_complete: true,
analysis_timed_out: false,
capabilities: [...GHIDRA_SESSION_CAPABILITIES],
target: {
name: "fixture",
language_id: "x86:LE:64:default",
compiler_spec_id: "gcc",
image_base: "0x400000",
default_address_space: "ram",
sha256: targetSha256,
},
});
type GhidraResultBuilder = (
input: Readonly<Record<string, JsonValue>>,
limit: number,
) => JsonValue;
const resultBuilders = new Map<GhidraOperation, GhidraResultBuilder>([
["list_documents", () => ["fixture"]],
[
"list_procedures",
(_input, limit) =>
page(
[
{
address: "0x401000",
value: "fixture_main",
value_truncated: false,
procedure: {
external: false,
thunk: false,
thunk_target: null,
},
},
],
limit,
),
],
[
"list_strings",
(_input, limit) =>
page(
[
stringItem("0x402000", "inventory fixture"),
stringItem("0x402020", "external fixture"),
],
limit,
),
],
[
"list_segments",
() => [
{
name: ".text",
start: "0x401000",
end: "0x401100",
readable: true,
writable: false,
executable: true,
permissions: { available: true, source: "ghidra-memory-block" },
provenance: "ghidra-memory-block",
address_space: "ram",
image_base: "0x400000",
initialized: true,
overlay: false,
sections: [],
},
],
],
[
"list_names",
(_input, limit) =>
page(
[
{
address: "0x401000",
value: "fixture_main",
value_truncated: false,
symbol: {
primary: true,
dynamic: false,
external: false,
type: "function",
source: "user_defined",
},
},
],
limit,
),
],
["search_procedures", (_input, limit) => page([], limit)],
["search_strings", (_input, limit) => page([], limit)],
["address_name", () => "fixture_main"],
["procedure_address", () => "0x401000"],
[
"resolve_containing_procedure",
() => ({
query_address: "0x401001",
found: true,
procedure: ghidraFunctionIdentity(),
}),
],
["procedure_assembly", () => "0x401000: CALL 0x401020\n0x401005: RET"],
["procedure_callees", () => []],
["procedure_callers", () => []],
[
"procedure_info",
() => ({
name: "fixture_main",
entrypoint: "0x401000",
basicblock_count: 1,
length: 6,
signature: "int fixture_main(void)",
locals: [],
classification: ghidraFunctionClassification(),
}),
],
["procedure_pseudo_code", () => "int fixture_main(void) { return 42; }"],
[
"read_function_instructions",
() => ({
procedure: ghidraFunctionIdentity(),
instructions: ghidraBounded(["0x401000: CALL 0x401020", "0x401005: RET"]),
instructions_scanned: 2,
instruction_scan_truncated: false,
limitations: ["Ghidra-specific instruction text."],
}),
],
[
"procedure_references",
(input, _limit) => ({
procedure: ghidraFunctionIdentity(),
direction: input.direction ?? "outgoing",
references: ghidraBounded([ghidraReferenceEdge()]),
instructions_scanned: 2,
instruction_scan_truncated: false,
}),
],
["xrefs", () => ["0x401001"]],
[
"analyze_function",
(input, _limit) =>
ghidraFunctionDossier(
input.include_assembly === true,
input.procedure === "fixture_truncated",
),
],
]);
const resultFor = (
operation: GhidraOperation,
input: Readonly<Record<string, JsonValue>>,
): JsonValue => {
const limit = typeof input.limit === "number" ? input.limit : 100;
const builder = resultBuilders.get(operation);
if (builder === undefined)
throw new TypeError(`Unexpected Ghidra operation: ${operation}`);
return builder(input, limit);
};
const page = (items: readonly JsonValue[], limit: number): JsonValue => ({
items: items.slice(0, limit),
offset: 0,
limit,
total: items.length,
next_offset: items.length > limit ? limit : null,
has_more: items.length > limit,
});
const stringItem = (address: string, value: string): JsonValue => ({
address,
value,
value_truncated: false,
string: {
encoding: "UTF-8",
termination: "present_or_not_required",
byte_length: value.length + 1,
},
});
@@ -0,0 +1,88 @@
import { describe, expect, it } from "vitest";
import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js";
describe("Ghidra MCP native API evidence", () => {
it("records approved native API truncation once and links its evidence", async () => {
const harness = await connectGhidraMcp("ghidra-native-api");
const { mcp, session } = harness;
try {
const unapprovedInspection = sessionEvidence(
session,
(
await mcp.callTool({
name: "inspect_native_api",
arguments: { procedure: "fixture_truncated" },
})
).structuredContent,
);
expect(unapprovedInspection.normalized_result).toMatchObject({
boundary: {
available: true,
jump_tables: [{ mappings_truncated: true }],
},
residual_unknowns: [
expect.stringContaining("additional data sources or targets"),
],
});
expect(
(
await mcp.callTool({
name: "list_unknowns",
arguments: {},
})
).structuredContent,
).toMatchObject({ result: { items: [] } });
const approvedInspection = sessionEvidence(
session,
(
await mcp.callTool({
name: "inspect_native_api",
arguments: {
procedure: "fixture_truncated",
unknown_registry_approved: true,
},
})
).structuredContent,
);
await mcp.callTool({
name: "inspect_native_api",
arguments: {
procedure: "fixture_truncated",
unknown_registry_approved: true,
},
});
expect(
(
await mcp.callTool({
name: "list_unknowns",
arguments: {},
})
).structuredContent,
).toMatchObject({
result: {
items: [
{
unknown: {
status: "open",
domain: "native-api",
question: expect.stringContaining(
"additional data sources or targets",
),
supporting_evidence_ids: [approvedInspection.evidence_id],
recommended_probes: [
{
operation: "inspect_native_api",
rationale: expect.stringContaining("ABI probe"),
},
],
},
},
],
},
});
} finally {
await harness.close();
}
}, 30_000);
});
@@ -0,0 +1,75 @@
import { describe, expect, it } from "vitest";
import { connectGhidraMcp } from "./ghidraMcpHarness.js";
describe("Ghidra MCP capability routing", () => {
it("routes composed and capability tools", async () => {
const harness = await connectGhidraMcp("ghidra-routing");
const { calls, mcp } = harness;
try {
const batch = await mcp.callTool({
name: "batch_decompile",
arguments: { addresses: ["fixture_main"] },
});
expect(batch.isError).not.toBe(true);
expect(batch.structuredContent).toMatchObject({
result: {
succeeded: 1,
failed: 0,
items: [{ status: "ok" }],
},
});
const availableNames = (await mcp.listTools()).tools.map(
({ name }) => name,
);
expect(availableNames).not.toContain("set_comment");
expect(calls).not.toContain("set_comment");
const status = await mcp.callTool({
name: "binary_session",
arguments: { detail: "full" },
});
expect(status.structuredContent).toMatchObject({
result: {
open: true,
analysis_provider_binding: {
provider: { id: "ghidra", version: "12.1.2" },
},
tool_availability: expect.arrayContaining([
expect.objectContaining({
name: "binary_overview",
available: true,
}),
expect.objectContaining({ name: "swift_classes", 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();
}
}, 30_000);
});
@@ -0,0 +1,348 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { z } from "zod";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
import { INVESTIGATION_EXAMPLES } from "../../../src/contracts/investigationExamples.js";
import {
FUNCTION_COMPARISON_EVIDENCE,
PROCESS_CAPTURE_RECONSTRUCTION,
PROCESS_CAPTURE_REFERENCE,
PROCESS_COMPARISON_EVIDENCE,
} from "../../../src/contracts/investigationExamples.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import {
jsonObjectSchema,
jsonValueSchema,
} from "../../../src/domain/jsonValue.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
import type { EvidenceFilePolicy } from "../../../src/domain/evidenceBundle.js";
import type { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
it("aggregates comparison Evidence and records an approved runtime gap", async () => {
const { session, server, client } = await connected();
const comparison =
INVESTIGATION_EXAMPLES.find_changed_behavior.comparisons[0];
if (comparison === undefined) throw new Error("missing comparison fixture");
for (const evidence of [
FUNCTION_COMPARISON_EXAMPLE.left,
FUNCTION_COMPARISON_EXAMPLE.right,
comparison,
])
expect(session.recordEvidence(evidence).ok).toBe(true);
try {
const response = await client.callTool({
name: "find_changed_behavior",
arguments: {
comparisons: [comparison],
unknown_registry_approved: true,
},
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const evidence = sessionEvidence(session, response.structuredContent);
expect(evidence).toMatchObject({
provider: { id: "rea-changed-behavior" },
normalized_result: { behavior_status: "unknown" },
});
expect(session.listUnknowns({ domain: "changed-behavior" })).toMatchObject([
{
question:
"Did both versions behave the same under a complete controlled replay?",
},
]);
} finally {
await close(session, server, client);
}
}, 10_000);
it("builds a zero-hop exact-address path with dossier citations", async () => {
const { session, server, client } = await connected();
expect(session.recordEvidence(FUNCTION_COMPARISON_EXAMPLE.left).ok).toBe(
true,
);
try {
const response = await client.callTool({
name: "build_call_path",
arguments: INVESTIGATION_EXAMPLES.build_call_path,
});
expect(response.isError).not.toBe(true);
const evidence = sessionEvidence(session, response.structuredContent);
expect(evidence).toMatchObject({
provider: { id: "rea-call-path" },
normalized_result: {
status: "found",
shortest_hops: 0,
paths: { total: 1 },
},
evidence_links: [FUNCTION_COMPARISON_EXAMPLE.left.evidence_id],
});
} finally {
await close(session, server, client);
}
});
it("records a safe unresolved call-path question", async () => {
const { session, server, client } = await connected();
const base = FUNCTION_COMPARISON_EXAMPLE.left;
if (base.subject === null) throw new Error("missing dossier subject");
const dossier = createEvidence(
{
path: base.subject.local_path,
sha256: base.subject.digest.sha256,
format: base.subject.format,
...(base.subject.architecture === null
? {}
: { architecture: base.subject.architecture }),
},
base.provider,
{
predicateType: base.predicate_type,
operation: base.operation,
parameters: base.parameters,
result: jsonValueSchema.parse({
...jsonObjectSchema.parse(base.normalized_result),
callees: {
items: [{ address: "0x2000", name: "next" }],
total: 1,
returned: 1,
truncated: false,
next_offset: null,
},
}),
rawResult: base.raw_result,
confidence: base.confidence,
authority: base.authority,
limitations: base.limitations,
locations: base.locations,
evidenceLinks: base.evidence_links,
},
);
expect(session.recordEvidence(dossier).ok).toBe(true);
try {
const response = await client.callTool({
name: "build_call_path",
arguments: {
...INVESTIGATION_EXAMPLES.build_call_path,
functions: [dossier],
start: { address: "0x1000" },
goal: { address: "0x3000" },
unknown_registry_approved: true,
},
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
expect(session.listUnknowns({ domain: "call-path" })).toMatchObject([
{
question:
"Can the requested call path be established from complete analysis?",
},
]);
} finally {
await close(session, server, client);
}
});
it("records an explicit non-causal static/runtime hypothesis", async () => {
const { session, server, client } = await connected();
for (const evidence of [
FUNCTION_COMPARISON_EXAMPLE.left,
FUNCTION_COMPARISON_EXAMPLE.right,
FUNCTION_COMPARISON_EVIDENCE,
PROCESS_CAPTURE_REFERENCE,
PROCESS_CAPTURE_RECONSTRUCTION,
PROCESS_COMPARISON_EVIDENCE,
])
expect(session.recordEvidence(evidence).ok).toBe(true);
try {
const response = await client.callTool({
name: "correlate_static_and_runtime",
arguments: INVESTIGATION_EXAMPLES.correlate_static_and_runtime,
});
expect(response.isError).not.toBe(true);
const evidence = sessionEvidence(session, response.structuredContent);
expect(evidence).toMatchObject({
provider: { id: "rea-static-runtime-correlation" },
confidence: "inferred",
normalized_result: {
status: "correlated",
summary: { hypotheses: 1 },
},
});
} finally {
await close(session, server, client);
}
});
it("records a safe unresolved static/runtime question", async () => {
const { session, server, client } = await connected();
for (const evidence of [
FUNCTION_COMPARISON_EXAMPLE.left,
FUNCTION_COMPARISON_EXAMPLE.right,
FUNCTION_COMPARISON_EVIDENCE,
PROCESS_CAPTURE_REFERENCE,
PROCESS_CAPTURE_RECONSTRUCTION,
PROCESS_COMPARISON_EVIDENCE,
])
expect(session.recordEvidence(evidence).ok).toBe(true);
const mapping =
INVESTIGATION_EXAMPLES.correlate_static_and_runtime.mappings[0];
if (mapping === undefined) throw new Error("missing correlation fixture");
try {
const response = await client.callTool({
name: "correlate_static_and_runtime",
arguments: {
...INVESTIGATION_EXAMPLES.correlate_static_and_runtime,
mappings: [
{
...mapping,
static: {
...mapping.static,
selector: { kind: "function", dimension: "assembly" },
},
},
],
unknown_registry_approved: true,
},
});
expect(response.isError).not.toBe(true);
expect(
session.listUnknowns({ domain: "static-runtime-correlation" }),
).toMatchObject([
{
question: "Does runtime behavior match the available static analysis?",
},
]);
} finally {
await close(session, server, client);
}
});
it("passes only the finite declared reconstruction specification", async () => {
const { session, server, client } = await connected();
for (const evidence of [
PROCESS_CAPTURE_REFERENCE,
PROCESS_CAPTURE_RECONSTRUCTION,
PROCESS_COMPARISON_EVIDENCE,
])
expect(session.recordEvidence(evidence).ok).toBe(true);
try {
const response = await client.callTool({
name: "verify_reconstruction",
arguments: {
...INVESTIGATION_EXAMPLES.verify_reconstruction,
unknown_registry_approved: true,
},
});
expect(response.isError).not.toBe(true);
const evidence = sessionEvidence(session, response.structuredContent);
expect(evidence).toMatchObject({
provider: { id: "rea-reconstruction-verifier" },
normalized_result: { status: "pass", summary: { passed: 1 } },
});
expect(evidence.limitations).toContain(
"Pass means every declared claim passed; it does not establish global implementation equivalence.",
);
} finally {
await close(session, server, client);
}
});
it("cannot omit a session-owned active unknown from reconstruction input", async () => {
const { session, server, client } = await connected();
for (const evidence of [
PROCESS_CAPTURE_REFERENCE,
PROCESS_CAPTURE_RECONSTRUCTION,
PROCESS_COMPARISON_EVIDENCE,
])
expect(session.recordEvidence(evidence).ok).toBe(true);
expect(
session.recordUnknown({
approved: true,
question: "Was terminal equivalence reproduced independently?",
severity: "high",
domain: "reconstruction-verification",
supporting_evidence_ids: [PROCESS_COMPARISON_EVIDENCE.evidence_id],
contradicting_evidence_ids: [],
required_authority: "controlled-replay",
required_confidence: "observed",
required_environment: null,
recommended_probes: [
{
operation: "capture_process_scenario",
rationale: "Repeat both sides under one controlled environment.",
},
],
relationships: [],
}).ok,
).toBe(true);
try {
const response = await client.callTool({
name: "verify_reconstruction",
arguments: {
...INVESTIGATION_EXAMPLES.verify_reconstruction,
unknown_registry_approved: true,
},
});
expect(response.isError).not.toBe(true);
const evidence = sessionEvidence(session, response.structuredContent);
expect(evidence.normalized_result).toMatchObject({
status: "unknown",
summary: { unknown: 1 },
});
expect(
session.listUnknowns({ domain: "reconstruction-verification" }),
).toContainEqual(
expect.objectContaining({
question: "Does the reconstruction satisfy every declared claim?",
}),
);
} finally {
await close(session, server, client);
}
});
const connected = async (
evidenceFilePolicy?: EvidenceFilePolicy,
investigationInputRoots: readonly string[] = evidenceFilePolicy?.roots ?? [],
permissionAuthority?: PermissionAuthority,
) => {
const session = composeBinarySessionFromFactory(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
...(evidenceFilePolicy === undefined
? {}
: {
evidenceFilePolicy,
investigationInputRoots,
}),
...(permissionAuthority === undefined ? {} : { permissionAuthority }),
});
const client = new Client({ name: "investigation-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
return { session, server, client };
};
const sessionEvidence = (session: BinarySession, value: unknown) => {
const parsed = z
.object({ evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u) })
.parse(value);
const evidence = session.evidenceById(parsed.evidence_id);
if (evidence === undefined) throw new TypeError("Missing session Evidence");
return evidence;
};
const close = async (
session: BinarySession,
server: Awaited<ReturnType<typeof createServer>>,
client: Client,
) => {
await Promise.allSettled([client.close(), server.close(), session.close()]);
};
@@ -0,0 +1,395 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
import { INVESTIGATION_EXAMPLES } from "../../../src/contracts/investigationExamples.js";
import {
FUNCTION_COMPARISON_EVIDENCE,
PROCESS_CAPTURE_RECONSTRUCTION,
PROCESS_CAPTURE_REFERENCE,
PROCESS_COMPARISON_EVIDENCE,
} from "../../../src/contracts/investigationExamples.js";
import { changedBehaviorResultSchema } from "../../../src/domain/changedBehavior.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { readInvestigationWorkspace } from "../../../src/application/InvestigationWorkspaceStore.js";
import type { EvidenceFilePolicy } from "../../../src/domain/evidenceBundle.js";
import type { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
it("never retains derived evidence after request cancellation", async () => {
const { session, server, client } = await connected();
const inputs = [
{
name: "find_changed_behavior",
arguments: INVESTIGATION_EXAMPLES.find_changed_behavior,
},
{
name: "build_call_path",
arguments: INVESTIGATION_EXAMPLES.build_call_path,
},
{
name: "correlate_static_and_runtime",
arguments: INVESTIGATION_EXAMPLES.correlate_static_and_runtime,
},
] as const;
for (const evidence of [
FUNCTION_COMPARISON_EXAMPLE.left,
FUNCTION_COMPARISON_EXAMPLE.right,
FUNCTION_COMPARISON_EVIDENCE,
PROCESS_CAPTURE_REFERENCE,
PROCESS_CAPTURE_RECONSTRUCTION,
PROCESS_COMPARISON_EVIDENCE,
])
expect(session.recordEvidence(evidence).ok).toBe(true);
const initialCount = session.exportEvidenceBundle().records.length;
try {
for (const input of inputs) {
const controller = new AbortController();
const request = client.callTool(input, {
signal: controller.signal,
onprogress: () => controller.abort(),
});
await expect(request).rejects.toThrow(/abort/iu);
}
await expect
.poll(() => session.exportEvidenceBundle().records.length)
.toBe(initialCount);
} finally {
await close(session, server, client);
}
}, 10_000);
it("runs and reuses a persistent cross-version workspace", async () => {
const directory = await createTestTempDirectory("rea-investigation-mcp-");
const left = join(directory, "left");
const right = join(directory, "right");
const workspace = join(directory, "workspace.json");
await Promise.all([mkdir(left), mkdir(right)]);
await Promise.all([
writeFile(join(left, "feature.txt"), "old\n"),
writeFile(join(right, "feature.txt"), "new\n"),
]);
const filePolicy = evidencePolicy(directory);
const { session, server, client } = await connected(filePolicy);
try {
const arguments_ = {
investigation_run: {
approved: true,
workspace_path: workspace,
workspace_name: "mcp-release-diff",
left_path: left,
right_path: right,
options: { page_size: 500, change_limit: 100 },
},
};
const first = await client.callTool({
name: "find_changed_behavior",
arguments: arguments_,
});
expect(first.isError).not.toBe(true);
const firstEvidence = sessionEvidence(session, first.structuredContent);
expect(firstEvidence.normalized_result).toMatchObject({
behavior_status: "unknown",
summary: { static_candidates: 2 },
investigation_run: { inventory_evidence_count: 2 },
});
expect(session.hasEvidence(firstEvidence.evidence_id)).toBe(true);
const loaded = await readInvestigationWorkspace(workspace, filePolicy);
expect(loaded).toMatchObject({
ok: true,
value: { revision: 3, runs: [{ status: "complete" }] },
});
expect(first.content).toContainEqual(
expect.objectContaining({
type: "resource_link",
uri: expect.stringMatching(
/^rea:\/\/workspace\/ws_[a-f0-9]{64}\/revision\/3$/u,
),
}),
);
const retainedWorkspace = session.investigationWorkspaces()[0];
expect(retainedWorkspace).toBeDefined();
if (retainedWorkspace !== undefined) {
const resource = await client.readResource({
uri: `rea://workspace/${retainedWorkspace.workspace_id}/revision/${String(retainedWorkspace.revision)}`,
});
expect(resource.contents[0]).toEqual(
expect.objectContaining({
text: expect.stringContaining(retainedWorkspace.revision_digest),
}),
);
}
const second = await client.callTool({
name: "find_changed_behavior",
arguments: arguments_,
});
expect(second.isError, JSON.stringify(second)).not.toBe(true);
const secondEvidence = sessionEvidence(session, second.structuredContent);
expect(secondEvidence.evidence_id).toBe(firstEvidence.evidence_id);
expect(
await readInvestigationWorkspace(workspace, filePolicy),
).toMatchObject({ ok: true, value: { revision: 3 } });
} finally {
await close(session, server, client);
await rm(directory, { recursive: true, force: true });
}
});
it("replays a complete workspace without write authority", async () => {
const directory = await createTestTempDirectory("rea-investigation-read-");
const left = join(directory, "left");
const right = join(directory, "right");
const workspace = join(directory, "workspace.json");
await Promise.all([mkdir(left), mkdir(right)]);
await Promise.all([
writeFile(join(left, "feature.txt"), "old\n"),
writeFile(join(right, "feature.txt"), "new\n"),
]);
const filePolicy = evidencePolicy(directory);
const arguments_ = {
investigation_run: {
approved: true,
workspace_path: workspace,
workspace_name: "read-only-replay",
left_path: left,
right_path: right,
options: { page_size: 500, change_limit: 100 },
},
};
const writer = await investigationAuthority(directory, true);
const initial = await connected(filePolicy, [directory], writer);
try {
const created = await initial.client.callTool({
name: "find_changed_behavior",
arguments: arguments_,
});
expect(created.isError, JSON.stringify(created)).not.toBe(true);
} finally {
await close(initial.session, initial.server, initial.client);
}
const reader = await investigationAuthority(directory, false);
const replay = await connected(filePolicy, [directory], reader);
try {
const cached = await replay.client.callTool({
name: "find_changed_behavior",
arguments: arguments_,
});
expect(cached.isError, JSON.stringify(cached)).not.toBe(true);
expect(
await readInvestigationWorkspace(workspace, filePolicy),
).toMatchObject({ ok: true, value: { revision: 3 } });
await writeFile(join(right, "feature.txt"), "changed again\n");
const denied = await replay.client.callTool({
name: "find_changed_behavior",
arguments: arguments_,
});
expect(denied).toMatchObject({
isError: true,
structuredContent: {
error: {
code: "permission_required",
details: { capability: "investigation_workspace_write" },
},
},
});
} finally {
await close(replay.session, replay.server, replay.client);
await rm(directory, { recursive: true, force: true });
}
});
it("defers input permission for an explicit replay with deleted inputs", async () => {
const directory = await createTestTempDirectory("rea-investigation-replay-");
const left = join(directory, "left");
const right = join(directory, "right");
const workspace = join(directory, "workspace.json");
await Promise.all([mkdir(left), mkdir(right)]);
await Promise.all([
writeFile(join(left, "feature.txt"), "old\n"),
writeFile(join(right, "feature.txt"), "new\n"),
]);
const filePolicy = evidencePolicy(directory);
const investigationRun = {
approved: true,
workspace_path: workspace,
workspace_name: "selected-replay",
left_path: left,
right_path: right,
options: { page_size: 500, change_limit: 100 },
};
const writer = await investigationAuthority(directory, true);
const initial = await connected(filePolicy, [directory], writer);
let runId: string | undefined;
try {
const created = await initial.client.callTool({
name: "find_changed_behavior",
arguments: { investigation_run: investigationRun },
});
expect(created.isError, JSON.stringify(created)).not.toBe(true);
const evidence = sessionEvidence(
initial.session,
created.structuredContent,
);
const result = changedBehaviorResultSchema.parse(
evidence.normalized_result,
);
runId = result.investigation_run?.run_id;
} finally {
await close(initial.session, initial.server, initial.client);
}
if (runId === undefined) throw new Error("missing completed run ID");
await Promise.all([
rm(left, { recursive: true, force: true }),
rm(right, { recursive: true, force: true }),
]);
const workspaceOnly = await permissionAuthorityForRoot(
directory,
[
"investigation_workspace_read",
"investigation_workspace_write",
"investigation_input",
],
["investigation_workspace_read"],
);
const replay = await connected(filePolicy, [], workspaceOnly);
try {
const cached = await replay.client.callTool({
name: "find_changed_behavior",
arguments: {
investigation_run: {
...investigationRun,
replay_run_id: runId,
},
},
});
expect(cached.isError, JSON.stringify(cached)).not.toBe(true);
expect(
await readInvestigationWorkspace(workspace, filePolicy),
).toMatchObject({ ok: true, value: { revision: 3 } });
} finally {
await close(replay.session, replay.server, replay.client);
await rm(directory, { recursive: true, force: true });
}
});
it("refuses automatic artifact reads outside operator-approved roots", async () => {
const directory = await createTestTempDirectory("rea-investigation-mcp-");
const approvedInputs = join(directory, "approved-inputs");
const outsideInputs = join(directory, "outside-inputs");
const evidenceRoot = join(directory, "evidence");
await Promise.all([
mkdir(approvedInputs),
mkdir(outsideInputs),
mkdir(evidenceRoot),
]);
const left = join(outsideInputs, "left");
const right = join(outsideInputs, "right");
await Promise.all([mkdir(left), mkdir(right)]);
const { session, server, client } = await connected(
evidencePolicy(evidenceRoot),
[approvedInputs],
);
try {
const response = await client.callTool({
name: "find_changed_behavior",
arguments: {
investigation_run: {
approved: true,
workspace_path: join(evidenceRoot, "workspace.json"),
left_path: left,
right_path: right,
},
},
});
expect(response.isError).toBe(true);
expect(response.content[0]).toEqual({
type: "text",
text: JSON.stringify(response.structuredContent),
});
} finally {
await close(session, server, client);
await rm(directory, { recursive: true, force: true });
}
});
const connected = async (
evidenceFilePolicy?: EvidenceFilePolicy,
investigationInputRoots: readonly string[] = evidenceFilePolicy?.roots ?? [],
permissionAuthority?: PermissionAuthority,
) => {
const session = composeBinarySessionFromFactory(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
...(evidenceFilePolicy === undefined
? {}
: {
evidenceFilePolicy,
investigationInputRoots,
}),
...(permissionAuthority === undefined ? {} : { permissionAuthority }),
});
const client = new Client({ name: "investigation-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
return { session, server, client };
};
const evidencePolicy = (root: string): EvidenceFilePolicy => ({
roots: [root],
maxBytes: 64 * 1024 * 1024,
maxDepth: 64,
maxStringLength: 1024 * 1024,
maxNodes: 1_000_000,
});
const sessionEvidence = (session: BinarySession, value: unknown) => {
const parsed = z
.object({ evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u) })
.parse(value);
const evidence = session.evidenceById(parsed.evidence_id);
if (evidence === undefined) throw new TypeError("Missing session Evidence");
return evidence;
};
const investigationAuthority = async (
root: string,
includeWrite: boolean,
): Promise<PermissionAuthority> =>
permissionAuthorityForRoot(
root,
[
"investigation_workspace_read",
"investigation_workspace_write",
"investigation_input",
],
[
"investigation_workspace_read",
"investigation_input",
...(includeWrite ? (["investigation_workspace_write"] as const) : []),
],
);
const close = async (
session: BinarySession,
server: Awaited<ReturnType<typeof createServer>>,
client: Client,
) => {
await Promise.allSettled([client.close(), server.close(), session.close()]);
};
@@ -0,0 +1,152 @@
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, describe, expect, test } from "vitest";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import { loadConfiguredPermissionAuthority } from "../../../src/application/PermissionConfiguration.js";
import { observeJavaScriptRuntime } from "../../../src/application/JavaScriptRuntimeObservationService.js";
import { V8InspectorProvider } from "../../../src/browser/V8InspectorProvider.js";
import { parseConfig } from "../../../src/config.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { startFakeV8Inspector } from "../../fixtures/fakeV8Inspector.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("JavaScript runtime observation MCP tools", () => {
const resources: Array<{ close(): Promise<unknown> }> = [];
const temporary: string[] = [];
afterEach(async () => {
await Promise.all(resources.splice(0).map((item) => item.close()));
await Promise.all(
temporary
.splice(0)
.map((path) => rm(path, { recursive: true, force: true })),
);
});
test("lists and observes one target as retained Evidence", async () => {
const root = await createTestTempDirectory("rea-v8-mcp-");
temporary.push(root);
const entry = join(root, "entry.js");
await writeFile(entry, "export const value = 1;\n");
const inspector = await startFakeV8Inspector({
targetUrl: pathToFileURL(entry).href,
});
resources.push(inspector);
const config = parseConfig({
REA_V8_INSPECTOR_OBSERVE_ENABLED: "true",
REA_V8_INSPECTOR_ENDPOINTS_JSON: JSON.stringify([inspector.endpoint]),
REA_V8_INSPECTOR_FILE_ROOTS_JSON: JSON.stringify([root]),
});
if (!config.ok) throw config.error;
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok) throw authority.error;
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
javascriptRuntimeObservation: new V8InspectorProvider(),
permissionAuthority: authority.value,
availabilityPolicy: () => ({
processCaptureEnabled: false,
evidenceFileRoots: 0,
investigationInputRoots: 0,
v8InspectorObservationEnabled: true,
}),
});
const client = new Client({ name: "v8-mcp-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server, session);
await server.connect(serverTransport);
await client.connect(clientTransport);
const listed = await client.callTool({
name: "list_javascript_runtime_targets",
arguments: {
inspector_endpoint: inspector.endpoint,
allowed_file_roots: [root],
allowed_origins: [],
approved: true,
},
});
expect(listed.isError).not.toBe(true);
expect(listed.structuredContent).toMatchObject({
result: {
targets: { items: [{ target_id: inspector.targetId }] },
},
});
const observedRuntime = await client.callTool({
name: "observe_javascript_runtime",
arguments: {
inspector_endpoint: inspector.endpoint,
allowed_file_roots: [root],
allowed_origins: [],
target_id: inspector.targetId,
runtime_kind: "node",
approved: true,
observation_ms: 10,
},
});
expect(observedRuntime.isError).not.toBe(true);
expect(observedRuntime.structuredContent).toMatchObject({
result: {
target: {
target_id: inspector.targetId,
runtime_kind: "node",
runtime_kind_authority: "caller-declared-unverified",
},
scripts: {
items: [
expect.objectContaining({
location: { kind: "file", file_path: entry },
}),
],
},
},
});
const evidenceId = evidenceIdFrom(observedRuntime.structuredContent);
expect(session.evidenceById(evidenceId)).toBeDefined();
expect(inspector.commands.map(({ method }) => method)).toEqual([
"Runtime.enable",
"Debugger.enable",
]);
const direct = await observeJavaScriptRuntime(
new V8InspectorProvider(),
authority.value,
{
inspector_endpoint: inspector.endpoint,
allowed_file_roots: [root],
allowed_origins: [],
target_id: inspector.targetId,
runtime_kind: "node",
approved: true,
observation_ms: 10,
limits: {
max_events: 10_000,
max_scripts: 2_000,
max_execution_contexts: 1_000,
max_location_bytes: 16_384,
max_total_metadata_bytes: 4_194_304,
},
},
);
expect(direct.ok).toBe(true);
if (direct.ok) expect(evidenceId).toBe(direct.value.evidence_id);
});
});
const evidenceIdFrom = (value: unknown): string => {
if (typeof value !== "object" || value === null)
throw new TypeError("Missing structured result");
const evidenceId = Reflect.get(value, "evidence_id");
if (typeof evidenceId !== "string")
throw new TypeError("Missing Evidence ID");
return evidenceId;
};
+159
View File
@@ -0,0 +1,159 @@
import type { ServeStdioOptions } from "@modelcontextprotocol/server/stdio";
import { describe, expect, it } from "vitest";
import { run, runEntrypoint } from "../../../src/main.js";
type RuntimeDependencies = NonNullable<Parameters<typeof run>[0]>;
const nextTurn = (): Promise<void> =>
new Promise((resolve) => setImmediate(resolve));
const dependencies = ({
serve,
output,
shutdown,
exitCodes,
shutdownUnregistrations = [],
}: {
readonly serve: RuntimeDependencies["serve"];
readonly output: string[];
readonly shutdown: Array<() => void>;
readonly exitCodes: number[];
readonly shutdownUnregistrations?: string[];
}): RuntimeDependencies => ({
env: {},
serve,
writeStderr: (text) => output.push(text),
setExitCode: (code) => exitCodes.push(code),
registerShutdown: (handler) => {
shutdown.push(handler);
return () => shutdownUnregistrations.push("shutdown");
},
});
describe("MCP runtime errors", () => {
it("reports connection loss without the transport cause", async () => {
const output: string[] = [];
const shutdown: Array<() => void> = [];
const shutdownUnregistrations: string[] = [];
let options: ServeStdioOptions | undefined;
let closeCalls = 0;
const close = (): Promise<void> => {
closeCalls += 1;
return Promise.resolve();
};
const exitCodes: number[] = [];
expect(
await run(
dependencies({
serve: (_factory, received) => {
options = received;
return { close };
},
output,
shutdown,
exitCodes,
shutdownUnregistrations,
}),
),
).toBe(0);
options?.onerror?.(new Error("SECRET transport stack"));
expect(output).toEqual([
"REA lost its MCP client connection. Restart REA from your MCP client.\n",
]);
shutdown[0]?.();
await nextTurn();
expect(closeCalls).toBe(1);
expect(shutdownUnregistrations).toEqual(["shutdown"]);
});
it("unregisters every process-lifetime handler during idempotent shutdown", async () => {
const shutdown: Array<() => void> = [];
const reload: Array<() => void> = [];
const unregistrations: string[] = [];
let closeCalls = 0;
const runtime: RuntimeDependencies = {
...dependencies({
serve: () => ({
close: async () => {
closeCalls += 1;
},
}),
output: [],
shutdown,
exitCodes: [],
shutdownUnregistrations: unregistrations,
}),
registerReload: (handler) => {
reload.push(handler);
return () => unregistrations.push("reload");
},
};
expect(await run(runtime)).toBe(0);
expect(shutdown).toHaveLength(1);
expect(reload).toHaveLength(1);
shutdown[0]?.();
shutdown[0]?.();
await nextTurn();
expect(closeCalls).toBe(1);
expect(unregistrations).toEqual(["reload", "shutdown"]);
});
it("reports transport startup failure without its cause", async () => {
const output: string[] = [];
expect(
await run(
dependencies({
serve: () => {
throw new Error("SECRET startup stack");
},
output,
shutdown: [],
exitCodes: [],
}),
),
).toBe(1);
expect(output).toEqual([
"REA could not start its MCP connection. Restart REA from your MCP client; run `rea doctor` if it fails again.\n",
]);
});
it("reports shutdown failure and sets a failing exit code", async () => {
const output: string[] = [];
const shutdown: Array<() => void> = [];
const exitCodes: number[] = [];
await run(
dependencies({
serve: () => ({
close: () => Promise.reject(new Error("SECRET close")),
}),
output,
shutdown,
exitCodes,
}),
);
shutdown[0]?.();
await nextTurn();
expect(exitCodes).toEqual([1]);
expect(output).toEqual([
"REA could not close cleanly. End the REA process before starting it again.\n",
]);
});
it("reports an unexpected entrypoint failure without its cause", async () => {
const output: string[] = [];
const exitCodes: number[] = [];
await runEntrypoint(
() => Promise.reject(new Error("SECRET entrypoint stack")),
(text) => output.push(text),
(code) => exitCodes.push(code),
);
expect(output).toEqual([
"REA could not start. Run `rea doctor`, then restart REA from your MCP client.\n",
]);
expect(exitCodes).toEqual([1]);
});
});
+277
View File
@@ -0,0 +1,277 @@
import { createHash } from "node:crypto";
import { mkdir, rm } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import type { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import type { ProjectPermissionStore } from "../../../src/application/ProjectPermissionStore.js";
import type { PermissionGrant } from "../../../src/domain/permissionPolicy.js";
import { ok } from "../../../src/domain/result.js";
import { run } from "../../../src/main.js";
import {
createServer,
type CreateServerOptions,
} from "../../../src/server/createServer.js";
type RuntimeDependencies = NonNullable<Parameters<typeof run>[0]>;
const directories: string[] = [];
afterEach(async () => {
await Promise.all(
directories
.splice(0)
.map((path) => rm(path, { recursive: true, force: true })),
);
});
describe("runtime permission reload", () => {
it("keeps live state unchanged after a late grant failure, then commits together", async () => {
const fixture = await reloadFixture();
const invalid = projectStore(fixture.projectRoot, [
projectGrant("invalid", fixture.outsideRoot),
]);
const valid = projectStore(fixture.projectRoot, [
projectGrant("valid", fixture.newRoot),
]);
const validReadStarted = deferred<void>();
const releaseValidRead = deferred<void>();
let reads = 0;
const runtime = await startRuntime(fixture.env, async () => {
reads += 1;
if (reads === 1) return ok(invalid);
validReadStarted.resolve();
await releaseValidRead.promise;
return ok(valid);
});
configure(fixture.env, fixture.newRoot, true);
runtime.reload();
runtime.reload();
await validReadStarted.promise;
expect(runtime.notifications()).toBe(0);
expect(runtime.options.processPolicy?.enabled).toBe(false);
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
fixture.oldRoot,
]);
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(false);
expect(await canRead(runtime.authority, fixture.oldRoot)).toBe(true);
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(false);
releaseValidRead.resolve();
await runtime.notificationCount(1);
expect(runtime.options.processPolicy?.enabled).toBe(true);
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
fixture.newRoot,
]);
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(true);
expect(await canRead(runtime.authority, fixture.oldRoot)).toBe(false);
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(true);
});
it("serializes overlapping reloads so an older read cannot commit last", async () => {
const fixture = await reloadFixture();
const firstReadStarted = deferred<void>();
const releaseFirstRead = deferred<void>();
const secondReadStarted = deferred<void>();
let secondStarted = false;
let reads = 0;
const runtime = await startRuntime(fixture.env, async () => {
reads += 1;
if (reads === 1) {
firstReadStarted.resolve();
await releaseFirstRead.promise;
return ok(projectStore(fixture.projectRoot, []));
}
secondStarted = true;
secondReadStarted.resolve();
return ok(projectStore(fixture.projectRoot, []));
});
configure(fixture.env, fixture.newRoot, true);
runtime.reload();
await firstReadStarted.promise;
configure(fixture.env, fixture.latestRoot, false);
runtime.reload();
expect(secondStarted).toBe(false);
releaseFirstRead.resolve();
await secondReadStarted.promise;
await runtime.notificationCount(2);
expect(runtime.options.processPolicy?.enabled).toBe(false);
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
fixture.latestRoot,
]);
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(false);
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(false);
expect(await canRead(runtime.authority, fixture.latestRoot)).toBe(true);
});
it("continues with later reloads after an unexpected reload rejection", async () => {
const fixture = await reloadFixture();
let reads = 0;
const runtime = await startRuntime(fixture.env, async () => {
reads += 1;
if (reads === 1) throw new Error("synthetic unexpected read failure");
return ok(projectStore(fixture.projectRoot, []));
});
configure(fixture.env, fixture.newRoot, true);
runtime.reload();
runtime.reload();
await runtime.notificationCount(1);
expect(reads).toBe(2);
expect(runtime.options.processPolicy?.enabled).toBe(true);
expect(runtime.options.evidenceFilePolicy?.roots).toEqual([
fixture.newRoot,
]);
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(true);
expect(await canRead(runtime.authority, fixture.oldRoot)).toBe(false);
expect(await canRead(runtime.authority, fixture.newRoot)).toBe(true);
});
});
const reloadFixture = async () => {
const directory = await createTestTempDirectory("rea-main-reload-");
directories.push(directory);
const oldRoot = join(directory, "old");
const newRoot = join(directory, "new");
const latestRoot = join(directory, "latest");
const outsideRoot = join(directory, "outside");
const projectRoot = join(directory, "project");
await Promise.all(
[oldRoot, newRoot, latestRoot, outsideRoot, projectRoot].map((path) =>
mkdir(path),
),
);
const env: NodeJS.ProcessEnv = {
REA_EVIDENCE_ROOTS_JSON: JSON.stringify([oldRoot]),
REA_PERMISSION_PROJECT_ROOT: projectRoot,
REA_PERMISSION_PROJECT_STORE: join(directory, "permissions.json"),
};
return { env, oldRoot, newRoot, latestRoot, outsideRoot, projectRoot };
};
const configure = (
env: NodeJS.ProcessEnv,
root: string,
enabled: boolean,
): void => {
env.REA_EVIDENCE_ROOTS_JSON = JSON.stringify([root]);
env.REA_PROCESS_CAPTURE_ENABLED = String(enabled);
env.REA_PROCESS_EXECUTABLE_ROOTS_JSON = JSON.stringify([root]);
env.REA_PROCESS_WORKING_ROOTS_JSON = JSON.stringify([root]);
env.REA_ARTIFACT_INTEGRITY_CONTINUE_ENABLED = String(enabled);
};
const startRuntime = async (
env: NodeJS.ProcessEnv,
readStore: NonNullable<RuntimeDependencies["readProjectPermissionStore"]>,
) => {
let reload: (() => void) | undefined;
let options: CreateServerOptions | undefined;
let notificationCount = 0;
let notification = deferred<void>();
const waiters = new Map<number, ReturnType<typeof deferred<void>>>();
const result = await run({
env,
serve: (factory) => {
void factory({ era: "legacy" });
return { close: () => Promise.resolve() };
},
writeStderr: () => undefined,
setExitCode: () => undefined,
registerShutdown: () => () => undefined,
registerReload: (handler) => {
reload = handler;
return () => undefined;
},
readProjectPermissionStore: readStore,
createServer: (analysis, session, received) => {
options = received;
const server = createServer(analysis, session, received);
server.sendToolListChanged = () => {
notificationCount += 1;
notification.resolve(undefined);
notification = deferred<void>();
waiters.get(notificationCount)?.resolve(undefined);
};
return server;
},
});
expect(result).toBe(0);
const authority = options?.permissionAuthority;
if (reload === undefined || options === undefined || authority === undefined)
throw new Error("Runtime reload seam was not initialized");
const capturedOptions = options;
return {
reload,
options: capturedOptions,
authority,
notifications: () => notificationCount,
notificationCount: (count: number) => {
if (notificationCount >= count) return Promise.resolve();
const waiter = deferred<void>();
waiters.set(count, waiter);
return waiter.promise;
},
};
};
const projectStore = (
projectRoot: string,
grants: readonly ReturnType<typeof projectGrant>[],
): ProjectPermissionStore => ({
schema_version: 1,
project_id: `project_${createHash("sha256").update(projectRoot).digest("hex")}`,
project_root: projectRoot,
grants: [...grants],
});
const projectGrant = (id: string, root: string) =>
({
grant_id: `project:${id}`,
capability: "evidence_read",
roots: [root],
executables: [],
environment_names: [],
network: "none",
mount: false,
lifetime: "project",
operation_identity: null,
expires_at: null,
}) satisfies PermissionGrant;
const canRead = async (
authority: PermissionAuthority,
root: string,
): Promise<boolean> =>
(
await authority.explain(
{
capability: "evidence_read",
roots: [root],
executables: [],
environment_names: [],
network: "none",
mount: false,
operation_identity: `read:${root}`,
},
"read",
)
).ok;
const deferred = <T>() => {
let resolvePromise!: (value: T | PromiseLike<T>) => void;
const promise = new Promise<T>((resolve) => {
resolvePromise = resolve;
});
return { promise, resolve: resolvePromise };
};
+400
View File
@@ -0,0 +1,400 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { expect, it } from "vitest";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { AnalysisProviderRegistry } from "../../../src/application/AnalysisProviderRegistry.js";
import { composeBinarySession } from "../../../src/application/BinarySessionComposition.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import { createPermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import { SessionProviderRouter } from "../../../src/application/SessionProviderRouter.js";
import { MANAGED_NATIVE_VERIFICATION_EXAMPLE } from "../../../src/contracts/managedWorkflowExamples.js";
import type { PermissionCeiling } from "../../../src/domain/permissionPolicy.js";
import { ManagedStaticProvider } from "../../../src/dotnet/ManagedStaticProvider.js";
import { createServer } from "../../../src/server/createServer.js";
import { buildManagedPeFixture } from "../../fixtures/managedPe.js";
it("opens a managed PE and executes the managed static provider through MCP", async () => {
const directory = await createTestTempDirectory("rea-managed-mcp-");
const path = join(directory, "fixture.exe");
const rightPath = join(directory, "fixture-renamed.exe");
const runtimePath = join(directory, "dotnet");
await writeFile(path, buildManagedPeFixture());
await writeFile(runtimePath, "#!/bin/sh\n");
await writeFile(rightPath, buildManagedPeFixture({ methodName: "Renamed" }));
const session = composeBinarySession(
SessionProviderRouter.selectable(new AnalysisProviderRegistry([]), [
new ManagedStaticProvider(),
]),
);
const runtimeCeiling: PermissionCeiling = {
capability: "managed_runtime",
roots: [directory],
executables: [runtimePath],
environment_names: [],
network: "none",
mount: false,
};
const authority = await createPermissionAuthority(
[runtimeCeiling],
[
{
...runtimeCeiling,
grant_id: "administrator:managed_runtime",
lifetime: "administrator",
operation_identity: null,
expires_at: null,
},
],
);
if (!authority.ok) throw authority.error;
const server = createServer(session, session, {
permissionAuthority: authority.value,
managedRuntimePolicy: {
enabled: true,
roots: [directory],
executablePath: runtimePath,
},
availabilityPolicy: () => ({
processCaptureEnabled: false,
evidenceFileRoots: 0,
investigationInputRoots: 0,
browserObservationEnabled: false,
electronObservationEnabled: false,
javascriptReplayEnabled: false,
managedRuntimeEnabled: true,
}),
});
const client = new Client({ name: "managed-mcp-test", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
await verifyManagedCatalogAndNativeWorkflow(client, session);
const members = await inspectManagedStaticWorkflow(client, session, path);
await verifyManagedComparisonAndReconstruction(
client,
session,
members,
rightPath,
);
} finally {
await Promise.all([client.close(), server.close()]);
await session.close();
}
}, 30_000);
const verifyManagedCatalogAndNativeWorkflow = async (
client: Client,
session: BinarySession,
): Promise<void> => {
const names = (await client.listTools()).tools.map(({ name }) => name);
expect(names).toEqual(
expect.arrayContaining([
"inspect_managed_artifact",
"inspect_managed_members",
"inspect_managed_native_boundaries",
"compare_managed_members",
"import_managed_reconstruction",
"verify_managed_native_boundaries",
"plan_managed_runtime_correlation",
]),
);
for (const evidence of [
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries,
...MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations,
])
expect(session.recordEvidence(evidence)).toMatchObject({ ok: true });
const verified = structured(
await client.callTool({
name: "verify_managed_native_boundaries",
arguments: {
managed_boundaries_evidence_id:
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries.evidence_id,
native_observation_evidence_ids:
MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations.map(
({ evidence_id: evidenceId }) => evidenceId,
),
limits: MANAGED_NATIVE_VERIFICATION_EXAMPLE.limits,
},
}),
);
expect(verified).toMatchObject({
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
evidence_uri: expect.stringMatching(/^rea:\/\/evidence\/ev_/u),
result: {
summary: { verified: 1 },
algorithm: { token_to_address_mapping: "not-inferred" },
},
});
const native = MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations[0];
if (native === undefined) throw new Error("missing native Evidence");
const wrong = await client.callTool({
name: "verify_managed_native_boundaries",
arguments: {
managed_boundaries_evidence_id: native.evidence_id,
native_observation_evidence_ids: [
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries.evidence_id,
],
},
});
expect(wrong).toMatchObject({
isError: true,
structuredContent: {
error: {
code: "evidence_integrity_mismatch",
details: { reason: "wrong_operation", actual: "inspect_macho" },
},
},
});
};
const inspectManagedStaticWorkflow = async (
client: Client,
session: BinarySession,
path: string,
): Promise<Record<string, unknown>> => {
const inspected = structured(
await client.callTool({
name: "inspect_managed_artifact",
arguments: { path, reference_limit: 1 },
}),
);
expect(inspected).toMatchObject({
result: {
classification: { status: "managed", runtime_family: "modern-dotnet" },
references: { limit: 1 },
},
});
const members = sessionEvidence(
session,
structured(
await client.callTool({
name: "inspect_managed_members",
arguments: { method_limit: 1 },
}),
),
);
expect(members).toMatchObject({
operation: "inspect_managed_members",
provider: { id: "rea-dotnet-static" },
subject: { local_path: path, format: "pe" },
normalized_result: {
identity_scope: { token_identity: "build-local" },
methods: { total: 1, returned: 1 },
call_edges: { total: 1 },
field_accesses: { total: 1 },
},
});
const boundaries = structured(
await client.callTool({
name: "inspect_managed_native_boundaries",
arguments: { import_limit: 1 },
}),
);
expect(boundaries).toMatchObject({
result: {
identity_scope: { token_identity: "build-local" },
pinvoke_imports: { total: 0, limit: 1 },
native_implementations: { total: 0 },
},
});
return members;
};
const methodFrom = (members: Record<string, unknown>) =>
z
.object({
items: z.array(
z.object({
token: z.string(),
signature: z.object({ raw_sha256: z.string() }),
body: z.object({ normalized_il_sha256: z.string().nullable() }),
}),
),
})
.parse(
z.record(z.string(), z.unknown()).parse(members.normalized_result)
.methods,
).items[0];
const verifyManagedComparisonAndReconstruction = async (
client: Client,
session: BinarySession,
members: Record<string, unknown>,
rightPath: string,
): Promise<void> => {
await client.callTool({
name: "open_binary",
arguments: { path: rightPath },
});
const right = sessionEvidence(
session,
structured(
await client.callTool({
name: "inspect_managed_members",
arguments: { method_limit: 1 },
}),
),
);
const compared = sessionEvidence(
session,
structured(
await client.callTool({
name: "compare_managed_members",
arguments: {
left_evidence_id: members.evidence_id,
right_evidence_id: right.evidence_id,
limits: {
max_method_matches: 100,
max_field_matches: 100,
max_candidates: 10,
},
},
}),
),
);
expect(compared).toMatchObject({
operation: "compare_managed_members",
provider: { id: "rea-dotnet-workflows" },
confidence: "inferred",
normalized_result: {
algorithm: { name_matching: "not-used" },
matching: { exact_il_signature: 1 },
},
});
const method = methodFrom(members);
expect(method).toBeDefined();
if (method === undefined) return;
await verifyImport(client, session, members, method);
await verifyRuntimePlan(client, session, members, method);
};
type ManagedMethod = NonNullable<ReturnType<typeof methodFrom>>;
const verifyImport = async (
client: Client,
session: BinarySession,
members: Record<string, unknown>,
method: ManagedMethod,
): Promise<void> => {
const imported = sessionEvidence(
session,
structured(
await client.callTool({
name: "import_managed_reconstruction",
arguments: {
static_members_evidence_id: members.evidence_id,
decompiler: {
name: "ilspycmd",
version: "9.1.0.7988",
family: "ilspy",
executable_sha256: null,
options: ["--type", "Example.Program"],
},
methods: [
{
token: method.token,
signature_sha256: method.signature.raw_sha256,
normalized_il_sha256: method.body.normalized_il_sha256,
reconstruction: {
kind: "decompiled-csharp",
language: "csharp",
text: "internal static void Main() { }",
},
},
],
notes: ["synthetic MCP import"],
},
}),
),
);
expect(imported).toMatchObject({
operation: "import_managed_reconstruction",
provider: { id: "rea-dotnet-workflows" },
confidence: "inferred",
normalized_result: {
executed: false,
summary: { imported_methods: 1, decompiled_csharp_methods: 1 },
methods: [
{
token: method.token,
validation: { canonical_observation: false },
},
],
},
});
};
const verifyRuntimePlan = async (
client: Client,
session: BinarySession,
members: Record<string, unknown>,
method: ManagedMethod,
): Promise<void> => {
const planned = sessionEvidence(
session,
structured(
await client.callTool({
name: "plan_managed_runtime_correlation",
arguments: {
static_members_evidence_id: members.evidence_id,
method: {
token: method.token,
signature_sha256: method.signature.raw_sha256,
normalized_il_sha256: method.body.normalized_il_sha256,
},
requested_effect: "attach",
host: {
os: "linux",
clr_family: "dotnet",
architecture: "x86_64",
},
bounds: {
timeout_ms: 5000,
max_threads: 32,
max_output_bytes: 65536,
allow_network: false,
allow_ui: false,
},
},
}),
),
);
expect(planned).toMatchObject({
operation: "plan_managed_runtime_correlation",
provider: { id: "rea-dotnet-workflows" },
confidence: "derived",
normalized_result: {
executed: false,
authority_model: { capability: "managed_runtime" },
requested_runtime: { effect: "attach", network: "none" },
effect_taxonomy: { attaches_process: true },
},
});
};
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);
};
const sessionEvidence = (
session: BinarySession,
result: Readonly<Record<string, unknown>>,
): Record<string, unknown> => {
const evidenceId = z.string().parse(result.evidence_id);
const evidence = session.evidenceById(evidenceId);
if (evidence === undefined) throw new Error("missing session Evidence");
return z.record(z.string(), z.unknown()).parse(evidence);
};
+112
View File
@@ -0,0 +1,112 @@
import { readFile, rm } from "node:fs/promises";
import { join, resolve } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
compareInventory,
runProductionMcpDoctor,
} from "../../../src/mcpDoctor.js";
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
const temporary: string[] = [];
afterEach(async () => {
await Promise.all(
temporary
.splice(0)
.map((path) => rm(path, { recursive: true, force: true })),
);
});
describe("production MCP doctor", () => {
it("connects to the production stdio child and verifies the canonical catalog", async () => {
const result = await runProductionMcpDoctor({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
cwd: process.cwd(),
environment: process.env,
});
expect(result).toMatchObject({
healthy: true,
adapter: "production-stdio",
inventory: {
tools: {
expected: expect.any(Number),
observed: expect.any(Number),
missing: [],
unexpected: [],
},
},
request_flow: { tool: "binary_session", ok: true },
});
expect(result.inventory?.tools.expected).toBe(
result.inventory?.tools.observed,
);
expect(result.inventory?.tools.expected).toBeLessThan(
CATALOG_IDENTITY.counts.mcp_tools,
);
}, 30_000);
it("reports exact missing, unexpected, and duplicate inventory names", () => {
expect(compareInventory(["a", "b"], ["b", "c", "c"])).toEqual({
expected: 2,
observed: 3,
missing: ["a"],
unexpected: ["c"],
duplicates: ["c"],
});
});
it("captures startup exit diagnostics", async () => {
const result = await runProductionMcpDoctor({
command: process.execPath,
args: [resolve("tests/fixtures/mcpDoctorExit.mjs")],
cwd: process.cwd(),
environment: process.env,
deadlineMs: 2_000,
});
expect(result).toMatchObject({
healthy: false,
checks: [{ name: "transport", ok: false }],
diagnostics: { stderr: expect.stringContaining("startup exit") },
});
});
it("kills a child that misses the absolute startup deadline", async () => {
const root = await createTestTempDirectory("rea-mcp-doctor-");
temporary.push(root);
const pidPath = join(root, "pid");
const result = await runProductionMcpDoctor({
command: process.execPath,
args: [resolve("tests/fixtures/mcpDoctorHang.mjs")],
cwd: process.cwd(),
environment: { ...process.env, REA_MCP_DOCTOR_PID_PATH: pidPath },
deadlineMs: 250,
});
expect(result.healthy).toBe(false);
const pid = Number.parseInt(await readFile(pidPath, "utf8"), 10);
await expect(waitForExit(pid)).resolves.toBeUndefined();
}, 10_000);
});
const waitForExit = async (pid: number): Promise<void> => {
for (let attempt = 0; attempt < 50; attempt += 1) {
try {
process.kill(pid, 0);
} catch (cause: unknown) {
if (
cause instanceof Error &&
"code" in cause &&
(cause as NodeJS.ErrnoException).code === "ESRCH"
)
return;
throw cause;
}
await new Promise<void>((resolve) => setTimeout(resolve, 20));
}
throw new Error(`MCP doctor fixture process ${String(pid)} remained alive`);
};
@@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest";
import { MCP_STARTUP_POLICY } from "../../../src/mcpStartupPolicy.js";
import {
createEsmModuleProfileCollector,
parseLinuxVmRssBytes,
} from "../../../scripts/lib/mcp-startup-probe.mjs";
describe("MCP startup policy", () => {
it("preserves headroom beneath the configured Codex timeout", () => {
const codexTimeoutMs =
MCP_STARTUP_POLICY.codexStartupTimeoutSeconds * 1_000;
expect(MCP_STARTUP_POLICY.initializeBudgetMs).toBeLessThan(codexTimeoutMs);
expect(MCP_STARTUP_POLICY.firstCatalogBudgetMs).toBeLessThan(
codexTimeoutMs,
);
expect(MCP_STARTUP_POLICY.firstCatalogBudgetMs).toBe(
MCP_STARTUP_POLICY.initializeBudgetMs +
MCP_STARTUP_POLICY.toolsListBudgetMs,
);
expect(MCP_STARTUP_POLICY.doctorDeadlineMs).toBeGreaterThanOrEqual(
codexTimeoutMs,
);
});
it("parses Linux resident memory without accepting other fields", () => {
expect(
parseLinuxVmRssBytes("Name:\tnode\nVmRSS:\t 12345 kB\nThreads:\t7\n"),
).toBe(12_641_280);
expect(parseLinuxVmRssBytes("VmSize:\t12345 kB\n")).toBeNull();
});
it("profiles unique file-backed ESM modules without retaining paths", () => {
const collector = createEsmModuleProfileCollector();
collector.append(
"ESM 1: Storing file:///opt/rea/dist/main.js\n" +
"ESM 1: Translating StandardModule file:///opt/rea/dist/main.js\n" +
"ESM 1: Storing file:///opt/rea/node_modules/zod/index.js",
);
expect(collector.result()).toEqual({
supported: true,
method: "node-debug-esm",
unique_file_modules: 2,
unique_package_modules: 0,
unique_dependency_modules: 1,
debug_lines: 3,
truncated: false,
});
});
});
+236
View File
@@ -0,0 +1,236 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { OFFICIAL_TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { HopperRemoteError } from "../../../src/domain/errors.js";
import { err } from "../../../src/domain/result.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import type { JsonValue } from "../../../src/domain/jsonValue.js";
import { createServer } from "../../../src/server/createServer.js";
const VALID_INPUTS: Readonly<
Record<string, Readonly<Record<string, JsonValue>>>
> = {
address_name: {},
comment: {},
current_address: {},
current_procedure: {},
current_document: {},
goto_address: { address: "0x1000" },
inline_comment: {},
list_bookmarks: {},
list_documents: {},
list_names: {},
list_procedures: {},
list_segments: {},
list_strings: {},
next_address: {},
prev_address: {},
procedure_address: { procedure: "main" },
procedure_assembly: { procedure: "main" },
procedure_callees: { procedure: "main" },
procedure_callers: { procedure: "main" },
procedure_info: { procedure: "main" },
read_function_instructions: { procedure: "main" },
read_bytes: { address: "0x1000", length: 4 },
address_to_file_offset: { address: "0x1000" },
procedure_references: { procedure: "main" },
procedure_pseudo_code: { procedure: "main" },
resolve_containing_procedure: { address: "0x1000" },
search_procedures: { pattern: "main" },
search_strings: { pattern: "hello" },
set_address_name: { address: "0x1000", name: "entry" },
set_addresses_names: { names: { "0x1000": "entry" } },
set_bookmark: { address: "0x1000" },
set_comment: { address: "0x1000", comment: "entry point" },
set_current_document: { document: "fixture" },
set_inline_comment: { address: "0x1000", comment: "entry point" },
unset_bookmark: { address: "0x1000" },
xrefs: {},
};
interface Invocation {
readonly name: string;
readonly arguments_: Readonly<Record<string, JsonValue>>;
}
const resources: Array<{ close(): Promise<void> }> = [];
afterEach(async () => {
await Promise.all(
resources.splice(0).map(async (resource) => resource.close()),
);
});
const connect = async (analysis: AnalysisOperationPort) => {
const server = createServer(analysis);
const client = new Client({ name: "contract-test", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
return client;
};
const page: JsonValue = {
items: [],
offset: 0,
limit: 100,
total: 0,
next_offset: null,
has_more: false,
};
const outputFor = (name: string): JsonValue => {
if (["list_procedures", "list_names", "list_strings"].includes(name))
return page;
if (["address_name", "comment", "inline_comment"].includes(name)) return null;
if (["procedure_callees", "procedure_callers", "xrefs"].includes(name))
return [];
if (["list_bookmarks", "list_documents", "list_segments"].includes(name))
return [];
if (
[
"set_address_name",
"set_bookmark",
"set_comment",
"set_inline_comment",
"unset_bookmark",
].includes(name)
)
return true;
if (name === "set_addresses_names") return { "0x1000": true };
if (["search_procedures", "search_strings"].includes(name)) return page;
if (name === "procedure_info")
return {
name: "main",
entrypoint: "0x1000",
basicblock_count: 1,
length: 4,
signature: null,
locals: [],
};
if (name === "resolve_containing_procedure")
return {
query_address: "0x1000",
found: true,
procedure: { address: "0x1000", name: "main" },
};
if (name === "read_function_instructions")
return {
procedure: { address: "0x1000", name: "main" },
instructions: {
items: ["0x1000: ret"],
total: 1,
returned: 1,
truncated: false,
next_offset: null,
},
instructions_scanned: 1,
instruction_scan_truncated: false,
limitations: ["Provider-specific instruction text."],
};
if (name === "read_bytes")
return {
address: "0x1000",
requested_bytes: 4,
returned_bytes: 4,
bytes_hex: "c3c3c3c3",
complete: true,
};
if (name === "address_to_file_offset")
return { address: "0x1000", file_offset: 0 };
if (name === "procedure_references")
return {
procedure: { address: "0x1000", name: "main" },
direction: "outgoing",
references: {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
},
instructions_scanned: 1,
instruction_scan_truncated: false,
};
return name.includes("address") ? "0x1000" : "fixture";
};
describe("official Hopper proxy tools", () => {
it("lists every official contract", async () => {
const client = await connect({
execute: () => Promise.resolve(ok(null)),
});
const listed = await client.listTools();
const officialNames = new Set<string>(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
);
expect(
listed.tools
.map(({ name }) => name)
.filter((name) => officialNames.has(name))
.sort(),
).toEqual(OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name).sort());
});
it("executes every handler and projects omitted Python optionals to null", async () => {
const invocations: Invocation[] = [];
const client = await connect({
execute: (name, arguments_) => {
invocations.push({ name, arguments_ });
return Promise.resolve(ok(outputFor(name)));
},
});
for (const contract of OFFICIAL_TOOL_CONTRACTS) {
const result = await client.callTool({
name: contract.name,
arguments: VALID_INPUTS[contract.name],
});
expect(result.isError).not.toBe(true);
expect(result.content).not.toEqual(
expect.arrayContaining([
expect.objectContaining({ type: "resource_link" }),
]),
);
}
expect(invocations.map(({ name }) => name)).toEqual(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
);
expect(
invocations.find(({ name }) => name === "address_name")?.arguments_,
).toEqual({
document: null,
address: null,
});
expect(
invocations.find(({ name }) => name === "search_procedures")?.arguments_,
).toEqual({
pattern: "main",
mode: "literal",
case_sensitive: false,
offset: 0,
limit: 100,
document: null,
});
});
it("returns stable safe MCP error content", async () => {
const client = await connect({
execute: () => Promise.resolve(err(new HopperRemoteError(-1, "denied"))),
});
const result = await client.callTool({
name: "list_documents",
arguments: {},
});
expect(result.isError).toBe(true);
expect(result.content[0]).toEqual({
type: "text",
text: JSON.stringify(result.structuredContent),
});
});
});
+60
View File
@@ -0,0 +1,60 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { realpath } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
import { createServer } from "../../../src/server/createServer.js";
describe("MCP permission preflight", () => {
it("denies extraction before dispatch and returns exact typed remediation", async () => {
const outputRoot = join(await realpath("/tmp"), "rea-permission-denied");
let dispatches = 0;
const analysis: AnalysisOperationPort = {
execute: () => {
dispatches += 1;
throw new Error("provider must not run");
},
};
const server = createServer(analysis, undefined, {
permissionAuthority: new PermissionAuthority(createPermissionPolicy([])),
});
const client = new Client({ name: "permission-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "extract_artifact",
arguments: {
approved: true,
output_root: outputRoot,
occurrence_ids: [`occ_${"0".repeat(64)}`],
},
});
expect(dispatches).toBe(0);
expect(result).toMatchObject({
isError: true,
structuredContent: {
error: {
code: "permission_required",
details: {
capability: "artifact_extract",
missing: { roots: [outputRoot] },
},
remediation: {
restart_required: true,
elicitation_supported: false,
},
},
},
});
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
});
@@ -0,0 +1,89 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { rm } from "node:fs/promises";
import { dirname } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { PROCESS_CAPTURE_ELICITATION_POLICY } from "../../../src/server/ProcessCaptureElicitation.js";
describe("process-capture MCP elicitation handshake", () => {
it("completes signed consent through the modern MCP client and server", async () => {
const root = await createTestTempDirectory("rea-elicit-mcp-");
const authority = new PermissionAuthority(
createPermissionPolicy([
{
capability: "process_capture",
roots: [root],
executables: [process.execPath],
environment_names: [],
network: "external",
mount: false,
},
]),
);
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const createTestServer = () =>
createServer(session, session, {
logger: silentLogger,
permissionAuthority: authority,
processPolicy: {
enabled: true,
executableRoots: [dirname(process.execPath)],
workingRoots: [root],
allowedEnvironment: [],
allowExternalNetwork: true,
},
});
const client = new Client(
{ name: "process-elicit", version: "1" },
{
capabilities: { elicitation: { form: {} } },
versionNegotiation: {
mode: {
pin: PROCESS_CAPTURE_ELICITATION_POLICY.protocolVersions[0],
},
},
inputRequired: { autoFulfill: true, maxRounds: 3 },
},
);
let prompts = 0;
client.setRequestHandler("elicitation/create", () => {
prompts += 1;
return Promise.resolve({
action: "accept" as const,
content: { lifetime: "session" },
});
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const server = serveStdio(createTestServer, {
transport: serverTransport,
legacy: "reject",
});
try {
await client.connect(clientTransport);
const captured = await client.callTool({
name: "capture_process_scenario",
arguments: {
approved: true,
executable: process.execPath,
arguments: ["-e", "process.exit(0)"],
working_directory: root,
},
});
expect(captured.isError).not.toBe(true);
expect(prompts).toBe(1);
} finally {
await Promise.allSettled([client.close(), server.close()]);
await rm(root, { recursive: true, force: true });
}
}, 20000);
});
@@ -0,0 +1,149 @@
import { isInputRequiredResult } from "@modelcontextprotocol/server";
import { describe, expect, it } from "vitest";
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
import {
authorizeProcessCaptureWithElicitation,
type ProcessCaptureElicitationState,
} from "../../../src/server/ProcessCaptureElicitation.js";
const request = {
capability: "process_capture" as const,
roots: ["/tmp"],
executables: [process.execPath],
environment_names: ["PATH"],
network: "external" as const,
mount: false,
operation_identity: "capture:test",
};
const now = Date.parse("2026-07-18T00:00:00.000Z");
const ceilingOnlyAuthority = (
origins?: readonly string[],
): PermissionAuthority =>
new PermissionAuthority(
createPermissionPolicy([
{
capability: "process_capture",
roots: request.roots,
executables: request.executables,
environment_names: request.environment_names,
...(origins === undefined ? {} : { origins }),
network: request.network,
mount: request.mount,
},
]),
);
const requestContext = (
state?: ProcessCaptureElicitationState,
response?: Record<string, unknown>,
) => ({
mcpReq: {
requestState: () => state,
...(response === undefined
? {}
: { inputResponses: { process_capture_grant: response } }),
},
});
const verifiedState = (
state: ProcessCaptureElicitationState | undefined,
): Promise<ProcessCaptureElicitationState> => {
if (state === undefined) throw new Error("state was not minted");
return Promise.resolve(state);
};
describe("process-capture MCP elicitation grants", () => {
it("grants and reuses a signed session scope on the modern protocol", async () => {
const authority = ceilingOnlyAuthority();
let state: ProcessCaptureElicitationState | undefined;
const elicitation = {
stateCodec: {
mint: (value: ProcessCaptureElicitationState) => {
state = value;
return Promise.resolve("signed-state");
},
verify: () => verifiedState(state),
},
supported: () => true,
now: () => now,
consumedNonces: new Map<string, number>(),
};
const first = await authorizeProcessCaptureWithElicitation(
authority,
request,
requestContext(),
elicitation,
);
expect(isInputRequiredResult(first)).toBe(true);
expect(first).toMatchObject({ requestState: "signed-state" });
expect(first).toMatchObject({
inputRequests: {
process_capture_grant: {
params: {
message: expect.stringContaining("Mount access: no"),
},
},
},
});
expect(state?.request).toEqual(request);
const accepted = await authorizeProcessCaptureWithElicitation(
authority,
request,
requestContext(state, {
action: "accept",
content: { lifetime: "session" },
}),
elicitation,
);
expect(isInputRequiredResult(accepted)).toBe(false);
if (isInputRequiredResult(accepted)) return;
expect(accepted.ok).toBe(true);
const reused = await authorizeProcessCaptureWithElicitation(
authority,
request,
requestContext(),
elicitation,
);
expect(isInputRequiredResult(reused)).toBe(false);
if (!isInputRequiredResult(reused)) expect(reused.ok).toBe(true);
});
it("fails closed for legacy clients and altered continuations", async () => {
const authority = ceilingOnlyAuthority();
let state: ProcessCaptureElicitationState | undefined;
const elicitation = {
stateCodec: {
mint: (value: ProcessCaptureElicitationState) => {
state = value;
return Promise.resolve("signed-state");
},
verify: () => verifiedState(state),
},
supported: () => false,
now: () => now,
consumedNonces: new Map<string, number>(),
};
const legacy = await authorizeProcessCaptureWithElicitation(
authority,
request,
requestContext(),
elicitation,
);
expect(isInputRequiredResult(legacy)).toBe(false);
if (!isInputRequiredResult(legacy)) expect(legacy.ok).toBe(false);
const modern = { ...elicitation, supported: () => true };
await authorizeProcessCaptureWithElicitation(
authority,
request,
requestContext(),
modern,
);
const altered = await authorizeProcessCaptureWithElicitation(
authority,
{ ...request, operation_identity: "capture:altered" },
requestContext(state, {
action: "accept",
content: { lifetime: "session" },
}),
modern,
);
expect(isInputRequiredResult(altered)).toBe(false);
if (!isInputRequiredResult(altered)) expect(altered.ok).toBe(false);
});
});
@@ -0,0 +1,167 @@
import { isInputRequiredResult } from "@modelcontextprotocol/server";
import { describe, expect, it } from "vitest";
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
import {
authorizeProcessCaptureWithElicitation,
type ProcessCaptureElicitationState,
} from "../../../src/server/ProcessCaptureElicitation.js";
const request = {
capability: "process_capture" as const,
roots: ["/tmp"],
executables: [process.execPath],
environment_names: ["PATH"],
network: "external" as const,
mount: false,
operation_identity: "capture:test",
};
const now = Date.parse("2026-07-18T00:00:00.000Z");
const ceilingOnlyAuthority = (
origins?: readonly string[],
): PermissionAuthority =>
new PermissionAuthority(
createPermissionPolicy([
{
capability: "process_capture",
roots: request.roots,
executables: request.executables,
environment_names: request.environment_names,
...(origins === undefined ? {} : { origins }),
network: request.network,
mount: request.mount,
},
]),
);
const requestContext = (
state?: ProcessCaptureElicitationState,
response?: Record<string, unknown>,
) => ({
mcpReq: {
requestState: () => state,
...(response === undefined
? {}
: { inputResponses: { process_capture_grant: response } }),
},
});
const verifiedState = (
state: ProcessCaptureElicitationState | undefined,
): Promise<ProcessCaptureElicitationState> => {
if (state === undefined) throw new Error("state was not minted");
return Promise.resolve(state);
};
describe("process-capture MCP elicitation grants", () => {
it("binds signed continuation state to exact origins", async () => {
const authority = ceilingOnlyAuthority([
"https://example.test",
"https://other.test",
]);
let state: ProcessCaptureElicitationState | undefined;
const elicitation = {
stateCodec: {
mint: (value: ProcessCaptureElicitationState) => {
state = value;
return Promise.resolve("signed-state");
},
verify: () => verifiedState(state),
},
supported: () => true,
now: () => now,
consumedNonces: new Map<string, number>(),
};
const scoped = { ...request, origins: ["https://example.test"] };
const prompted = await authorizeProcessCaptureWithElicitation(
authority,
scoped,
requestContext(),
elicitation,
);
expect(prompted).toMatchObject({
inputRequests: {
process_capture_grant: {
params: {
message: expect.stringContaining("Origins: https://example.test"),
},
},
},
});
const altered = await authorizeProcessCaptureWithElicitation(
authority,
{ ...scoped, origins: ["https://other.test"] },
requestContext(state, {
action: "accept",
content: { lifetime: "session" },
}),
elicitation,
);
expect(isInputRequiredResult(altered)).toBe(false);
if (!isInputRequiredResult(altered)) expect(altered.ok).toBe(false);
});
it("consumes once grants and rejects continuation replay", async () => {
const authority = ceilingOnlyAuthority();
let state: ProcessCaptureElicitationState | undefined;
const elicitation = {
stateCodec: {
mint: (value: ProcessCaptureElicitationState) => {
state = value;
return Promise.resolve("signed-state");
},
verify: () => verifiedState(state),
},
supported: () => true,
now: () => now,
consumedNonces: new Map<string, number>(),
};
await authorizeProcessCaptureWithElicitation(
authority,
request,
requestContext(),
elicitation,
);
const response = {
action: "accept",
content: { lifetime: "once" },
};
const accepted = await authorizeProcessCaptureWithElicitation(
authority,
request,
requestContext(state, response),
elicitation,
);
if (isInputRequiredResult(accepted)) throw new Error("grant was not used");
expect(accepted.ok).toBe(true);
const replayed = await authorizeProcessCaptureWithElicitation(
authority,
request,
requestContext(state, response),
elicitation,
);
expect(isInputRequiredResult(replayed)).toBe(false);
if (!isInputRequiredResult(replayed)) expect(replayed.ok).toBe(false);
const next = await authorizeProcessCaptureWithElicitation(
authority,
request,
requestContext(),
elicitation,
);
expect(isInputRequiredResult(next)).toBe(true);
const declined = await authorizeProcessCaptureWithElicitation(
authority,
request,
requestContext(state, { action: "decline" }),
elicitation,
);
expect(isInputRequiredResult(declined)).toBe(false);
const acceptedAfterDecline = await authorizeProcessCaptureWithElicitation(
authority,
request,
requestContext(state, {
action: "accept",
content: { lifetime: "session" },
}),
elicitation,
);
expect(isInputRequiredResult(acceptedAfterDecline)).toBe(false);
if (!isInputRequiredResult(acceptedAfterDecline))
expect(acceptedAfterDecline.ok).toBe(false);
});
});
@@ -0,0 +1,182 @@
import { isInputRequiredResult } from "@modelcontextprotocol/server";
import { mkdir, rm } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
import {
authorizeProcessCaptureWithElicitation,
type ProcessCaptureElicitationState,
} from "../../../src/server/ProcessCaptureElicitation.js";
const request = {
capability: "process_capture" as const,
roots: ["/tmp"],
executables: [process.execPath],
environment_names: ["PATH"],
network: "external" as const,
mount: false,
operation_identity: "capture:test",
};
const now = Date.parse("2026-07-18T00:00:00.000Z");
const ceilingOnlyAuthority = (
origins?: readonly string[],
): PermissionAuthority =>
new PermissionAuthority(
createPermissionPolicy([
{
capability: "process_capture",
roots: request.roots,
executables: request.executables,
environment_names: request.environment_names,
...(origins === undefined ? {} : { origins }),
network: request.network,
mount: request.mount,
},
]),
);
const requestContext = (
state?: ProcessCaptureElicitationState,
response?: Record<string, unknown>,
) => ({
mcpReq: {
requestState: () => state,
...(response === undefined
? {}
: { inputResponses: { process_capture_grant: response } }),
},
});
const verifiedState = (
state: ProcessCaptureElicitationState | undefined,
): Promise<ProcessCaptureElicitationState> => {
if (state === undefined) throw new Error("state was not minted");
return Promise.resolve(state);
};
describe("process-capture MCP elicitation grants", () => {
it("bounds replay state and prunes entries at the signed-state TTL", async () => {
const authority = ceilingOnlyAuthority();
let state: ProcessCaptureElicitationState | undefined;
const consumedNonces = new Map<string, number>();
const elicitation = {
stateCodec: {
mint: (value: ProcessCaptureElicitationState) => {
state = value;
return Promise.resolve("signed-state");
},
verify: () => verifiedState(state),
},
supported: () => true,
now: () => now,
consumedNonces,
};
await authorizeProcessCaptureWithElicitation(
authority,
request,
requestContext(),
elicitation,
);
const future = now + 600000;
for (let index = 0; index < 4096; index += 1)
consumedNonces.set(`occupied-${String(index)}`, future);
const rejectedAtCapacity = await authorizeProcessCaptureWithElicitation(
authority,
request,
requestContext(state, {
action: "accept",
content: { lifetime: "session" },
}),
elicitation,
);
expect(isInputRequiredResult(rejectedAtCapacity)).toBe(false);
if (!isInputRequiredResult(rejectedAtCapacity))
expect(rejectedAtCapacity.ok).toBe(false);
consumedNonces.set("occupied-0", now - 1);
const acceptedAfterPrune = await authorizeProcessCaptureWithElicitation(
authority,
request,
requestContext(state, {
action: "accept",
content: { lifetime: "session" },
}),
elicitation,
);
expect(isInputRequiredResult(acceptedAfterPrune)).toBe(false);
if (!isInputRequiredResult(acceptedAfterPrune))
expect(acceptedAfterPrune.ok).toBe(true);
expect(consumedNonces.has("occupied-0")).toBe(false);
expect(consumedNonces.size).toBe(4096);
});
it.each(["result", "throw"] as const)(
"revokes an elicited grant when final authorization ends with %s",
async (failure) => {
const root = await createTestTempDirectory("rea-elicit-rollback-");
const scoped = { ...request, roots: [root] };
const policy = createPermissionPolicy([
{
capability: "process_capture",
roots: scoped.roots,
executables: scoped.executables,
environment_names: scoped.environment_names,
network: scoped.network,
mount: scoped.mount,
},
]);
class FailingFinalAuthority extends PermissionAuthority {
private authorizationCount = 0;
override async authorize(
...arguments_: Parameters<PermissionAuthority["authorize"]>
): ReturnType<PermissionAuthority["authorize"]> {
this.authorizationCount += 1;
const result = await super.authorize(...arguments_);
if (failure === "result" && this.authorizationCount === 2)
await rm(root, { recursive: true, force: true });
if (failure === "throw" && this.authorizationCount === 3)
throw new Error("synthetic final authorization rejection");
return result;
}
}
const authority = new FailingFinalAuthority(policy);
let state: ProcessCaptureElicitationState | undefined;
const elicitation = {
stateCodec: {
mint: (value: ProcessCaptureElicitationState) => {
state = value;
return Promise.resolve("signed-state");
},
verify: () => verifiedState(state),
},
supported: () => true,
now: () => now,
consumedNonces: new Map<string, number>(),
};
await authorizeProcessCaptureWithElicitation(
authority,
scoped,
requestContext(),
elicitation,
);
const finalAuthorization = authorizeProcessCaptureWithElicitation(
authority,
scoped,
requestContext(state, {
action: "accept",
content: { lifetime: "session" },
}),
elicitation,
);
if (failure === "throw")
await expect(finalAuthorization).rejects.toThrow(
"synthetic final authorization rejection",
);
else {
const failed = await finalAuthorization;
expect(isInputRequiredResult(failed)).toBe(false);
if (!isInputRequiredResult(failed)) expect(failed.ok).toBe(false);
await mkdir(root);
}
const retry = await authority.authorize(scoped, "read", {
elicitationSupported: true,
});
expect(retry.ok).toBe(false);
},
);
});
@@ -0,0 +1,141 @@
import { isInputRequiredResult } from "@modelcontextprotocol/server";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { rm } from "node:fs/promises";
import { dirname } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { PROCESS_CAPTURE_ELICITATION_POLICY } from "../../../src/server/ProcessCaptureElicitation.js";
describe("process-capture MCP elicitation handshake", () => {
it.each(["tampered", "expired"] as const)(
"rejects %s signed state through the modern MCP client and server",
async (failure) => {
const startedAt = Date.parse("2026-07-23T00:00:00.000Z");
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(startedAt);
const root = await createTestTempDirectory("rea-elicit-state-");
const authority = new PermissionAuthority(
createPermissionPolicy([
{
capability: "process_capture",
roots: [root],
executables: [process.execPath],
environment_names: [],
network: "external",
mount: false,
},
]),
);
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const client = new Client(
{ name: "process-elicit-state", version: "1" },
{
capabilities: { elicitation: { form: {} } },
versionNegotiation: {
mode: {
pin: PROCESS_CAPTURE_ELICITATION_POLICY.protocolVersions[0],
},
},
inputRequired: { autoFulfill: false, maxRounds: 3 },
},
);
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const server = serveStdio(
() =>
createServer(session, session, {
logger: silentLogger,
permissionAuthority: authority,
processPolicy: {
enabled: true,
executableRoots: [dirname(process.execPath)],
workingRoots: [root],
allowedEnvironment: [],
allowExternalNetwork: true,
},
}),
{ transport: serverTransport, legacy: "reject" },
);
const call = {
name: "capture_process_scenario",
arguments: {
approved: true,
executable: process.execPath,
arguments: ["-e", "process.exit(0)"],
working_directory: root,
},
};
try {
await client.connect(clientTransport);
const required = await client.callTool(call, {
allowInputRequired: true,
});
expect(isInputRequiredResult(required)).toBe(true);
if (!isInputRequiredResult(required)) return;
const requestState = required.requestState;
expect(requestState).toEqual(expect.any(String));
if (requestState === undefined) return;
if (failure === "expired")
vi.setSystemTime(
startedAt +
(PROCESS_CAPTURE_ELICITATION_POLICY.stateTtlSeconds + 1) * 1000,
);
const echoedState =
failure === "tampered"
? `${requestState.startsWith("A") ? "B" : "A"}${requestState.slice(1)}`
: requestState;
const retryMethod: string = "tools/call";
await expect(
client.request(
{
method: retryMethod,
params: {
...call,
requestState: echoedState,
inputResponses: {
process_capture_grant: {
action: "accept",
content: { lifetime: "session" },
},
},
},
},
z.unknown(),
),
).rejects.toMatchObject({
code: -32602,
data: { reason: "invalid_request_state" },
});
expect(
await authority.authorize(
{
capability: "process_capture",
roots: [root],
executables: [process.execPath],
environment_names: [],
network: "external",
mount: false,
operation_identity: `capture_process_scenario:${process.execPath}`,
},
"read",
),
).toMatchObject({ ok: false });
} finally {
await Promise.allSettled([client.close(), server.close()]);
await rm(root, { recursive: true, force: true });
vi.useRealTimers();
}
},
20000,
);
});
@@ -0,0 +1,163 @@
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, describe, expect, it } from "vitest";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
import { compareProcessEvidenceFiles } from "../../../src/application/ProcessCli.js";
import { PROCESS_PROVIDER } from "../../../src/application/ProcessEvidence.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import type { ProcessTraceSpecification } from "../../../src/domain/processTraceComparison.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const resources: Array<{ close(): Promise<void> }> = [];
const temporaryRoots: string[] = [];
const beforeCheckpoint = {
name: "before",
at_ms: 0,
files: [],
effects: [],
truncated: false,
};
const afterCheckpoint = {
name: "after_settlement",
at_ms: 50,
files: [],
effects: [],
truncated: false,
};
const capture = {
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
event_journal: [
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
{ capture_order: 1, collection: "lifecycle", index: 0 },
{ capture_order: 2, collection: "lifecycle", index: 1 },
{ capture_order: 3, collection: "filesystem_checkpoints", index: 1 },
],
} as const;
const traceSpecification: ProcessTraceSpecification = {
version: 1,
events: [
{
id: "before",
source: "filesystem",
exact: beforeCheckpoint,
cardinality: { kind: "required" },
},
{
id: "exit",
source: "lifecycle",
exact: { event: "exit", ...capture.exit },
cardinality: { kind: "required" },
},
{
id: "settlement",
source: "lifecycle",
exact: { event: "settlement", ...capture.settlement },
cardinality: { kind: "required" },
},
{
id: "after",
source: "filesystem",
exact: afterCheckpoint,
cardinality: { kind: "required" },
},
],
language: {
kind: "finite_traces",
variants: [
{
id: "normal",
trace: ["before", "exit", "settlement", "after"],
},
],
},
};
const captureEvidence = (side: "left" | "right") =>
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture/v4",
operation: "capture_process_scenario",
parameters: { side },
result: jsonValueSchema.parse(capture),
confidence: "observed",
authority: "controlled-replay",
locations: [{ kind: "artifact-path", path: `/fixture/${side}` }],
});
afterEach(async () => {
await Promise.all(resources.splice(0).map((resource) => resource.close()));
await Promise.all(
temporaryRoots
.splice(0)
.map((root) => rm(root, { recursive: true, force: true })),
);
});
describe("declared trace adapter parity", () => {
it("returns identical CLI and MCP results and Evidence identity", async () => {
const left = captureEvidence("left");
const right = captureEvidence("right");
const root = await createTestTempDirectory("rea-trace-adapters-");
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(traceSpecification)),
]);
const cliEvidence = parseEvidence(
await compareProcessEvidenceFiles(leftPath, rightPath, specificationPath),
);
const session = composeBinarySessionFromFactory(
(_path) =>
({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(),
}) satisfies AnalysisClient,
);
expect(session.recordEvidence(left).ok).toBe(true);
expect(session.recordEvidence(right).ok).toBe(true);
const server = createServer(
{ execute: () => Promise.resolve(ok(null)) },
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 response = await client.callTool({
name: "compare_process_captures",
arguments: {
left_evidence_id: left.evidence_id,
right_evidence_id: right.evidence_id,
trace_spec: traceSpecification,
},
});
expect(response.isError).not.toBe(true);
expect(response.structuredContent).toMatchObject({
result: { trace: { verdict: "equivalent" } },
evidence_id: cliEvidence.evidence_id,
});
const structuredResult =
typeof response.structuredContent === "object" &&
response.structuredContent !== null
? Reflect.get(response.structuredContent, "result")
: undefined;
expect(structuredResult).toEqual(cliEvidence.normalized_result);
expect(cliEvidence.locations).toEqual([
{ kind: "artifact-path", path: "/fixture/left" },
{ kind: "artifact-path", path: "/fixture/right" },
]);
});
});
+77
View File
@@ -0,0 +1,77 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { AnalysisCancelledError } from "../../../src/domain/errors.js";
import { err } from "../../../src/domain/result.js";
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 () => {
const analysis: AnalysisOperationPort = {
execute: () => Promise.resolve(observed("0x1000")),
};
const server = createServer(analysis);
const client = new Client({ name: "progress-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const progress: number[] = [];
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool(
{ name: "current_address", arguments: {} },
{ onprogress: (update) => progress.push(update.progress) },
);
expect(result.isError).not.toBe(true);
expect(progress).toEqual([0, 1]);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
it("propagates client cancellation to the active provider request", async () => {
let providerObservedCancellation = false;
let markProviderStarted: (() => void) | undefined;
const providerStarted = new Promise<void>((resolve) => {
markProviderStarted = resolve;
});
const analysis: AnalysisOperationPort = {
execute: async (operation, _parameters, options) => {
markProviderStarted?.();
await new Promise<void>((resolve) => {
options?.signal?.addEventListener(
"abort",
() => {
providerObservedCancellation = true;
resolve();
},
{ once: true },
);
});
return err(new AnalysisCancelledError(operation));
},
};
const server = createServer(analysis);
const client = new Client({ name: "cancellation-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const controller = new AbortController();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const request = client.callTool(
{ name: "current_address", arguments: {} },
{ signal: controller.signal },
);
await providerStarted;
controller.abort();
await expect(request).rejects.toThrow(/abort/iu);
await expect.poll(() => providerObservedCancellation).toBe(true);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
});
+300
View File
@@ -0,0 +1,300 @@
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import { ARTIFACT_COMPARISON_EXAMPLE } from "../../../src/contracts/artifactComparisonExample.js";
import { PROCESS_CAPTURE_REFERENCE } from "../../../src/contracts/investigationExamples.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { createPromptCompletionSource } from "../../../src/server/promptCompletion.js";
import { observed } from "../../fixtures/analysisExecution.js";
let directory: string | undefined;
afterEach(async () => {
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
describe("guided prompt completion from live analysis", () => {
it("reads live documents and paged procedures without ambiguous names", async () => {
const requests: Array<Readonly<Record<string, unknown>>> = [];
const session = composeBinarySessionFromFactory(() => client(requests));
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([
"App",
"AppTests",
]);
expect(
await completion.complete("procedure", "", {
arguments: { document: "App" },
}),
).toEqual(["0x1000", "0x2000", "0x3000", "0x4000", "tail", "unique"]);
expect(requests).toEqual([
{ offset: 0, limit: 500, document: "App" },
{ offset: 2, limit: 500, document: "App" },
]);
expect(await completion.complete("provider", "uni")).toEqual([
"unidentified",
]);
expect(await completion.complete("document", "x".repeat(4_097))).toEqual(
[],
);
await session.close();
expect(await completion.complete("document", "")).toEqual([]);
expect(await completion.complete("procedure", "")).toEqual([]);
});
});
describe("guided prompt completion from investigation records", () => {
it("projects only validated typed identifiers from the evidence ledger", async () => {
const session = composeBinarySessionFromFactory(() => client([]));
const invalidCapture = createEvidence(undefined, fixtureProvider, {
operation: "capture_process_scenario",
parameters: {},
result: { schema_version: 4 },
confidence: "observed",
authority: "controlled-replay",
environment: fixtureEnvironment,
});
const invalidInventory = createEvidence(undefined, fixtureProvider, {
operation: "fixture_inventory",
parameters: {},
result: ARTIFACT_COMPARISON_EXAMPLE.right.normalized_result,
confidence: "observed",
authority: "shipped-artifact",
});
for (const evidence of [
ARTIFACT_COMPARISON_EXAMPLE.left,
PROCESS_CAPTURE_REFERENCE,
invalidCapture,
invalidInventory,
])
expect(session.recordEvidence(evidence).ok).toBe(true);
const unknown = session.recordUnknown({
approved: true,
question: "Which branch handles the fallback?",
severity: "medium",
domain: "control-flow",
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
required_authority: "analyst-inference",
required_confidence: "derived",
required_environment: null,
recommended_probes: [],
relationships: [],
});
if (!unknown.ok) throw unknown.error;
const completion = createPromptCompletionSource(session, session);
expect(await completion.complete("capture", "ev_")).toEqual([
PROCESS_CAPTURE_REFERENCE.evidence_id,
]);
expect(await completion.complete("manifest", "agm_")).toEqual([
`agm_${"0".repeat(64)}`,
]);
expect(await completion.complete("occurrence", "occ_")).toEqual([
`occ_${"0".repeat(64)}`,
]);
expect(await completion.complete("unknown", "unk_")).toEqual([
unknown.value.unknown_id,
]);
const resolved = session.updateUnknown({
approved: true,
unknown_id: unknown.value.unknown_id,
expected_revision: unknown.value.revision,
status: "resolved",
severity: unknown.value.severity,
supporting_evidence_ids: unknown.value.supporting_evidence_ids,
contradicting_evidence_ids: unknown.value.contradicting_evidence_ids,
required_authority: unknown.value.required_authority,
required_confidence: unknown.value.required_confidence,
required_environment: unknown.value.required_environment,
recommended_probes: unknown.value.recommended_probes,
relationships: unknown.value.relationships,
resolution: {
disposition: "withdrawn",
rationale: "The requested fallback is outside the current scope.",
evidence_ids: [],
},
});
expect(resolved.ok).toBe(true);
expect(await completion.complete("unknown", "")).toEqual([]);
await session.close();
expect(await completion.complete("evidence", "ev_")).toEqual([]);
});
it("deduplicates, case-folds, and returns deterministic live evidence IDs", async () => {
const session = composeBinarySessionFromFactory(() => client([]));
for (let index = 149; index >= 0; index -= 1) {
const evidence = createEvidence(undefined, fixtureProvider, {
operation: `fixture-${String(index)}`,
parameters: { index },
result: index,
confidence: "derived",
authority: "analyst-inference",
});
expect(session.recordEvidence(evidence).ok).toBe(true);
expect(session.recordEvidence(evidence).ok).toBe(true);
}
const completion = createPromptCompletionSource(session, session);
const values = await completion.complete("evidence", "EV_");
expect(values).toHaveLength(150);
expect(values).toEqual([...values].sort());
});
});
describe("guided prompt completion validation and limits", () => {
it("does not offer procedure names from an incomplete discovery", async () => {
let calls = 0;
const completion = createPromptCompletionSource({
execute() {
calls += 1;
return Promise.resolve(
observed(
calls === 1
? page(0, [{ address: "0x1000", value: "possibly_ambiguous" }], 1)
: null,
),
);
},
});
expect(await completion.complete("procedure", "")).toEqual(["0x1000"]);
});
it("bounds procedure scans and rejects non-advancing continuation metadata", async () => {
let calls = 0;
const bounded = createPromptCompletionSource({
execute(_operation, parameters) {
calls += 1;
const offset = Number(parameters.offset);
const items = Array.from({ length: 500 }, (_, index) => {
const address = offset + index;
return {
address: `0x${address.toString(16).padStart(8, "0")}`,
value: `procedure_${String(address)}`,
};
});
return Promise.resolve(
observed({
items,
offset,
limit: 500,
total: 6_000,
next_offset: offset + 500,
has_more: true,
}),
);
},
});
const values = await bounded.complete("procedure", "");
expect(calls).toBe(10);
expect(values).toHaveLength(5_000);
expect(values.every((value) => value.startsWith("0x"))).toBe(true);
let nonAdvancingCalls = 0;
const nonAdvancing = createPromptCompletionSource({
execute() {
nonAdvancingCalls += 1;
return Promise.resolve(
observed(page(0, [{ address: "0x5000", value: "unsafe_name" }], 0)),
);
},
});
expect(await nonAdvancing.complete("procedure", "")).toEqual(["0x5000"]);
expect(nonAdvancingCalls).toBe(1);
});
it("normalizes Unicode prefixes while preserving distinct exact identifiers", async () => {
const completion = createPromptCompletionSource({
execute(operation) {
return Promise.resolve(
observed(
operation === "list_documents"
? ["App", "App", "app", "Zulu"]
: null,
),
);
},
});
expect(await completion.complete("document", "AP")).toEqual([
"App",
"app",
"App",
]);
const malformed = createPromptCompletionSource({
execute: () => Promise.resolve(observed(["valid", 1])),
});
expect(await malformed.complete("document", "")).toEqual([]);
});
});
const fixtureProvider = { id: "fixture", name: "Fixture", version: "1" };
const fixtureEnvironment = {
id: "fixture-linux",
platform: "linux",
architecture: "x86_64",
isolation: "process" as const,
};
const client = (
requests: Array<Readonly<Record<string, unknown>>>,
): AnalysisClient => ({
execute(operation, parameters) {
if (operation === "list_documents")
return Promise.resolve(observed(["AppTests", "App", "App"]));
if (operation === "list_procedures") {
requests.push(parameters);
const offset = parameters.offset;
return Promise.resolve(
observed(
offset === 0
? page(
0,
[
{ address: "0x1000", value: "duplicate" },
{ address: "0x2000", value: "unique" },
],
2,
)
: page(
2,
[
{ address: "0x3000", value: "duplicate" },
{ address: "0x4000", value: "tail" },
],
null,
),
),
);
}
return Promise.resolve(observed(null));
},
close: () => Promise.resolve(),
});
const page = (
offset: number,
items: readonly { readonly address: string; readonly value: string }[],
nextOffset: number | null,
) => ({
items,
offset,
limit: 500,
total: 4,
next_offset: nextOffset,
has_more: nextOffset !== null,
});
+430
View File
@@ -0,0 +1,430 @@
import { rm, writeFile } from "node:fs/promises";
import { basename, join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import { PROMPT_CONTRACTS } from "../../../src/contracts/promptContracts.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { createServer } from "../../../src/server/createServer.js";
import { registerGuidedPrompts } from "../../../src/server/registerPrompts.js";
import { observed } from "../../fixtures/analysisExecution.js";
const resources: Array<{ close(): Promise<unknown> }> = [];
const temporaryDirectories: string[] = [];
afterEach(async () => {
await Promise.allSettled(
resources.splice(0).map((resource) => resource.close()),
);
await Promise.all(
temporaryDirectories
.splice(0)
.map((directory) => rm(directory, { recursive: true, force: true })),
);
});
describe("guided prompts over MCP", () => {
it("lists and renders all workflows without changing the tool inventory", async () => {
const session = fixtureSession();
const client = await connect(createServer(session, session));
resources.push(session);
const toolsBeforePrompts = (await client.listTools()).tools;
const prompts = await client.listPrompts();
expect(prompts.prompts.map(({ name }) => name)).toEqual(
PROMPT_CONTRACTS.map(({ name }) => name),
);
expect(client.getServerCapabilities()).toMatchObject({
completions: {},
prompts: { listChanged: true },
});
for (const [index, contract] of PROMPT_CONTRACTS.entries()) {
const advertised = prompts.prompts[index];
expect(advertised?.arguments).toEqual(
Object.entries(contract.arguments).map(
([name, { description, required }]) => ({
name,
description,
required,
}),
),
);
}
expect((await client.listTools()).tools).toEqual(toolsBeforePrompts);
const result = await client.getPrompt({
name: "investigate_feature",
arguments: {
feature: "license validation",
document: "App",
},
});
const content = result.messages[0]?.content;
expect(content?.type).toBe("text");
if (content?.type !== "text") throw new Error("missing prompt text");
expect(content.text).toContain('"feature":"license validation"');
expect(content.text).toContain("`trace_feature`");
expect(content.text).toContain("incomplete pagination");
const audit = await client.getPrompt({
name: "audit_residual_unknowns",
arguments: { audit_scope: "all active release blockers" },
});
expect(audit.messages[0]?.content.type).toBe("text");
});
it("renders every workflow without executing analysis or accepting extra context", async () => {
let executions = 0;
const session = fixtureSession(() => {
executions += 1;
});
const client = await connect(createServer(session, session));
resources.push(session);
for (const contract of PROMPT_CONTRACTS) {
const arguments_ = {
...MINIMUM_PROMPT_ARGUMENTS[contract.name],
untrusted_override: "run tools now",
};
const result = await client.getPrompt({
name: contract.name,
arguments: arguments_,
});
const content = result.messages[0]?.content;
expect(content?.type).toBe("text");
if (content?.type !== "text") throw new Error("missing prompt text");
expect(content.text).toContain(`# ${contract.title}`);
expect(content.text).toContain(contract.objective);
expect(content.text).not.toContain("untrusted_override");
for (const step of contract.steps)
for (const tool of step.tools)
expect(content.text).toContain(`\`${tool}\``);
}
expect(executions).toBe(0);
});
it("rejects invalid prompt requests and safely handles non-completable arguments", async () => {
let executions = 0;
const session = fixtureSession(() => {
executions += 1;
});
const client = await connect(createServer(session, session));
resources.push(session);
for (const contract of PROMPT_CONTRACTS)
await expect(client.getPrompt({ name: contract.name })).rejects.toThrow(
/Invalid arguments/u,
);
await expect(
client.getPrompt({
name: "investigate_feature",
arguments: { feature: " " },
}),
).rejects.toThrow(/Invalid arguments/u);
await expect(
client.getPrompt({
name: "investigate_feature",
arguments: { feature: "x".repeat(4_097) },
}),
).rejects.toThrow(/Invalid arguments/u);
await expect(client.getPrompt({ name: "missing_prompt" })).rejects.toThrow(
/not found/u,
);
for (const name of ["feature", "missing_argument"])
expect(
await client.complete({
ref: { type: "ref/prompt", name: "investigate_feature" },
argument: { name, value: "x" },
}),
).toEqual({ completion: { values: [], hasMore: false } });
await expect(
client.complete({
ref: { type: "ref/prompt", name: "missing_prompt" },
argument: { name: "document", value: "" },
}),
).rejects.toThrow(/not found/u);
expect(
await client.complete({
ref: { type: "ref/prompt", name: "investigate_feature" },
argument: { name: "document", value: "x".repeat(4_097) },
}),
).toEqual({
completion: { values: [], total: 0, hasMore: false },
});
expect(executions).toBe(0);
});
});
describe("guided prompt completion registry", () => {
it("applies the MCP 100-value limit while reporting total and hasMore", async () => {
const session = fixtureSession();
for (let index = 0; index < 150; index += 1)
expect(
session.recordEvidence(
createEvidence(undefined, fixtureProvider, {
operation: `fixture-${String(index)}`,
parameters: { index },
result: index,
confidence: "derived",
authority: "analyst-inference",
}),
).ok,
).toBe(true);
const client = await connect(createServer(session, session));
resources.push(session);
const result = await client.complete({
ref: { type: "ref/prompt", name: "verify_reconstruction" },
argument: { name: "comparison_evidence_id", value: "ev_" },
});
expect(result.completion.values).toHaveLength(100);
expect(result.completion.total).toBe(150);
expect(result.completion.hasMore).toBe(true);
expect(result.completion.values).toEqual(
[...result.completion.values].sort(),
);
});
it("emits prompts/list_changed and exposes the updated prompt", async () => {
const session = fixtureSession();
const server = new McpServer({
name: "prompt-registry-test",
version: "1",
});
const registry = registerGuidedPrompts(server, session, session);
const client = new Client({ name: "prompt-registry-client", version: "1" });
const changed = new Promise<void>((resolve) => {
client.setNotificationHandler("notifications/prompts/list_changed", () =>
resolve(),
);
});
await connectPair(server, client);
resources.push(session);
expect((await client.listPrompts()).prompts[0]?.title).toBe(
"Investigate a feature",
);
registry.update({
...PROMPT_CONTRACTS[0],
title: "Investigate a feature (updated)",
arguments: {
...PROMPT_CONTRACTS[0].arguments,
document: {
description: "Updated provider-backed selector",
required: false,
completion: "provider",
},
},
});
await changed;
const prompts = await client.listPrompts();
expect(prompts.prompts[0]?.title).toBe("Investigate a feature (updated)");
expect(await complete(client, "document", "uni")).toEqual(["unidentified"]);
});
});
describe("guided prompt completion lifecycle", () => {
it("survives a cancelled completion and ignores its late result", async () => {
let calls = 0;
let markStarted = (): void => undefined;
let release = (): void => undefined;
const started = new Promise<void>((resolve) => {
markStarted = resolve;
});
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const server = new McpServer({
name: "prompt-cancellation-test",
version: "1",
});
registerGuidedPrompts(server, {
async execute() {
calls += 1;
if (calls === 1) {
markStarted();
await gate;
return observed(["late-document"]);
}
return observed(["fresh-document"]);
},
});
const client = new Client({ name: "prompt-cancel-client", version: "1" });
await connectPair(server, client);
const controller = new AbortController();
const pending = client.complete(
{
ref: { type: "ref/prompt", name: "investigate_feature" },
argument: { name: "document", value: "" },
},
{ signal: controller.signal },
);
await started;
controller.abort();
await expect(pending).rejects.toThrow();
release();
await new Promise((resolve) => setTimeout(resolve, 0));
expect(await complete(client, "document", "fresh")).toEqual([
"fresh-document",
]);
expect(calls).toBe(2);
});
it("refreshes wire completions across open, switch, concurrency, and close", async () => {
const directory = await createTestTempDirectory("rea-prompt-mcp-");
temporaryDirectories.push(directory);
const first = join(directory, "first.hop");
const second = join(directory, "second.hop");
await Promise.all([writeFile(first, "first"), writeFile(second, "second")]);
const procedureRequests: Array<Readonly<Record<string, unknown>>> = [];
const session = composeBinarySessionFromFactory((target) =>
lifecycleClient(basename(target.path, ".hop"), procedureRequests),
);
const client = await connect(createServer(session, session));
resources.push(session);
expect(await complete(client, "document", "")).toEqual([]);
expect(
(
await client.callTool({
name: "open_binary",
arguments: { path: first },
})
).isError,
).not.toBe(true);
expect(await complete(client, "document", "first")).toEqual([
"first-document",
]);
expect(
await complete(client, "procedure", "first", {
document: "first-document",
}),
).toEqual(["first-procedure"]);
const concurrent = await Promise.all(
Array.from({ length: 16 }, () => complete(client, "procedure", "0x")),
);
expect(concurrent.every((values) => values[0] === "0x1000")).toBe(true);
expect(
(
await client.callTool({
name: "open_binary",
arguments: { path: second },
})
).isError,
).not.toBe(true);
expect(await complete(client, "document", "first")).toEqual([]);
expect(await complete(client, "document", "second")).toEqual([
"second-document",
]);
expect(
procedureRequests.some(({ document }) => document === "first-document"),
).toBe(true);
expect(
(await client.callTool({ name: "close_binary", arguments: {} })).isError,
).not.toBe(true);
expect(await complete(client, "document", "")).toEqual([]);
expect(await complete(client, "procedure", "")).toEqual([]);
}, 10_000);
});
const fixtureProvider = { id: "fixture", name: "Fixture", version: "1" };
const fixtureSession = (
onExecute: () => void = () => undefined,
): BinarySession =>
composeBinarySessionFromFactory(() => ({
execute: () => {
onExecute();
return Promise.resolve(observed(null));
},
close: () => Promise.resolve(),
}));
const MINIMUM_PROMPT_ARGUMENTS: Readonly<
Record<string, Readonly<Record<string, string>>>
> = {
investigate_feature: { feature: "offline search" },
compare_application_versions: {
left_target_path: "/tmp/left.app",
right_target_path: "/tmp/right.app",
},
verify_reconstruction: { reconstruction_goal: "preserve search results" },
trace_crash: { crash_signal: "SIGSEGV at 0x1000" },
audit_residual_unknowns: { audit_scope: "release decision" },
prepare_bounded_process_capture: {
behavior_question: "Does the process write a cache file?",
executable: "/usr/bin/true",
working_directory: "/tmp",
},
};
const lifecycleClient = (
target: string,
requests: Array<Readonly<Record<string, unknown>>>,
): AnalysisClient => ({
execute(operation, parameters) {
if (operation === "list_documents")
return Promise.resolve(observed([`${target}-document`]));
if (operation === "list_procedures") {
requests.push(parameters);
return Promise.resolve(
observed({
items: [
{
address: target === "first" ? "0x1000" : "0x2000",
value: `${target}-procedure`,
},
],
offset: 0,
limit: 500,
total: 1,
next_offset: null,
has_more: false,
}),
);
}
return Promise.resolve(observed(null));
},
close: () => Promise.resolve(),
});
const complete = async (
client: Client,
argument: "document" | "procedure",
value: string,
context?: Readonly<Record<string, string>>,
): Promise<string[]> =>
(
await client.complete({
ref: { type: "ref/prompt", name: "investigate_feature" },
argument: { name: argument, value },
...(context === undefined ? {} : { context: { arguments: context } }),
})
).completion.values;
const connect = async (
server: Awaited<ReturnType<typeof createServer>>,
): Promise<Client> => {
const client = new Client({ name: "prompt-test", version: "1" });
await connectPair(server, client);
return client;
};
const connectPair = async (
server: McpServer,
client: Client,
): Promise<void> => {
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
};
@@ -0,0 +1,242 @@
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, describe, expect, it } from "vitest";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
createAnalysisExecution,
type AnalysisProviderCandidate,
type CapabilityDescriptor,
type ProviderIdentity,
} from "../../../src/application/AnalysisProvider.js";
import { AnalysisProviderRegistry } from "../../../src/application/AnalysisProviderRegistry.js";
import { composeBinarySession } from "../../../src/application/BinarySessionComposition.js";
import { SessionProviderRouter } from "../../../src/application/SessionProviderRouter.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { ok } from "../../../src/domain/result.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
const resources: Array<{ close(): Promise<unknown> }> = [];
let directory: string | undefined;
afterEach(async () => {
await Promise.all(resources.splice(0).map((resource) => resource.close()));
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
describe("provider selection over MCP", () => {
it("keeps open_binary and binary_session binding semantics exact", async () => {
directory = await createTestTempDirectory("rea-provider-mcp-");
const target = join(directory, "fixture.hop");
await writeFile(target, "fixture");
const starts: string[] = [];
const session = composeBinarySession(
SessionProviderRouter.selectable(
new AnalysisProviderRegistry([
candidate("beta", starts),
candidate("alpha", starts),
]),
[],
),
);
const server = createServer(session, session, { logger: silentLogger });
const mcp = new Client({ name: "provider-selection", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(mcp, server);
await server.connect(serverTransport);
await mcp.connect(clientTransport);
const before = structured(
await mcp.callTool({
name: "binary_session",
arguments: { detail: "full" },
}),
);
expect(before.result).toMatchObject({
open: false,
analysis_run: null,
analysis_provider_binding: null,
analysis_provider_candidates: [
{
provider: { id: "alpha" },
target_support: { status: "unknown" },
selected: false,
},
{
provider: { id: "beta" },
target_support: { status: "unknown" },
selected: false,
},
],
});
expect(starts).toEqual([]);
const malformed = await mcp.callTool({
name: "open_binary",
arguments: { path: target, provider_id: "Beta" },
});
expect(malformed.isError).toBe(true);
expect(starts).toEqual([]);
const ambiguous = await mcp.callTool({
name: "open_binary",
arguments: { path: target },
});
expect(ambiguous.isError).toBe(true);
expect(structured(ambiguous)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
selection_reason: "ambiguous",
requested_provider_id: "auto",
candidate_ids: ["alpha", "beta"],
},
},
});
expect(starts).toEqual([]);
const opened = await mcp.callTool({
name: "open_binary",
arguments: { path: target, provider_id: "beta" },
});
expect(opened.isError).not.toBe(true);
expect(starts).toEqual([]);
const observed = await mcp.callTool({
name: "address_name",
arguments: {},
});
expect(observed.isError).not.toBe(true);
expect(structured(observed)).toMatchObject({
result: "beta:address_name",
evidence_id: expect.stringMatching(/^ev_/u),
});
expect(starts).toEqual(["beta"]);
const status = structured(
await mcp.callTool({
name: "binary_session",
arguments: { detail: "full" },
}),
);
expect(status.result).toMatchObject({
open: true,
analysis_run: {
run_id: expect.stringMatching(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,
),
process_lineage: { status: "not_observed" },
},
analysis_provider_binding: {
provider: { id: "beta", version: "1" },
selection_source: "request",
},
analysis_provider_candidates: [
{ provider: { id: "alpha" }, selected: false },
{ provider: { id: "beta", version: "1" }, selected: true },
],
});
const unknown = await mcp.callTool({
name: "open_binary",
arguments: { path: target, provider_id: "missing" },
});
expect(unknown.isError).toBe(true);
expect(structured(unknown)).toMatchObject({
error: { details: { selection_reason: "unknown_provider" } },
});
expect(
structured(
await mcp.callTool({
name: "binary_session",
arguments: { detail: "full" },
}),
).result,
).toMatchObject({
analysis_provider_binding: { provider: { id: "beta" } },
});
});
});
const candidate = (id: string, starts: string[]): AnalysisProviderCandidate => {
const identity: ProviderIdentity = {
id,
name: `${id} provider`,
version: null,
};
return {
identity: () => identity,
capabilities: () => [capability(identity)],
inspectAvailability: () => ({
status: "available",
code: null,
reason: null,
diagnostics: { executable_path: `/opt/${id}/bin/analyze` },
}),
inspectTargetSupport: () => ({
status: "supported",
code: null,
reason: null,
diagnostics: {},
}),
resolveAnalysisProfile: () =>
Promise.resolve(
ok({
profile: createAnalysisProfile(
{ id, name: identity.name, version: "1" },
1,
{ fixture: id },
),
compatibility: {},
}),
),
createClient: (_target, profile) => {
starts.push(id);
return {
execute: (operation) =>
Promise.resolve(
ok(
createAnalysisExecution(
`${id}:${operation}`,
profile?.provider ?? identity,
),
),
),
close: () => Promise.resolve(),
};
},
};
};
const capability = (provider: ProviderIdentity): CapabilityDescriptor => ({
provider,
operation: "address_name",
inputContractVersion: 1,
outputContractVersion: 1,
available: true,
reason: null,
pagination: "none",
exhaustive: true,
effects: {
mutatesArtifact: false,
launchesProcess: true,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
},
limits: { maxResults: null, maxPayloadBytes: 1_000, timeoutMs: 1_000 },
limitations: [],
});
const structured = (result: CallToolResult): Record<string, unknown> =>
z.record(z.string(), z.unknown()).parse(result.structuredContent);
@@ -0,0 +1,248 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { rm } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import { INVESTIGATION_EXAMPLES } from "../../../src/contracts/investigationExamples.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import {
createReconstructionCoverageWorkspace,
createReconstructionVerifierContract,
} from "../../../src/domain/reconstructionCoverage.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
const digest = (character: string): string => character.repeat(64);
describe("reconstruction coverage MCP parity", () => {
it("commits and queries the same evidence-backed fail-closed workspace", async () => {
const root = await createTestTempDirectory("rea-coverage-mcp-");
const path = join(root, "coverage.json");
const policy = {
roots: [root],
maxBytes: 64 * 1024 * 1024,
maxDepth: 64,
maxStringLength: 1024 * 1024,
maxNodes: 1_000_000,
};
const authority = await permissionAuthorityForRoot(
root,
["investigation_workspace_read", "investigation_workspace_write"],
["investigation_workspace_read", "investigation_workspace_write"],
);
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
evidenceFilePolicy: policy,
permissionAuthority: authority,
});
const client = new Client({ name: "coverage-mcp-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const workspace = fixtureWorkspace();
const committed = await client.callTool({
name: "commit_reconstruction_coverage",
arguments: {
approved: true,
workspace_path: path,
expected_revision: null,
workspace,
},
});
expect(committed.isError).not.toBe(true);
expect(committed.structuredContent).toMatchObject({
revision: 1,
revision_sha256: workspace.revision_sha256,
});
const resourceUri = `rea://reconstruction-coverage/${workspace.workspace_id}/revision/1`;
expect(committed.content).toContainEqual(
expect.objectContaining({ type: "resource_link", uri: resourceUri }),
);
const resource = await client.readResource({ uri: resourceUri });
expect(resource.contents[0]).toEqual(
expect.objectContaining({
text: expect.stringContaining(workspace.revision_sha256),
}),
);
const queried = await client.callTool({
name: "query_reconstruction_coverage",
arguments: {
workspace_path: path,
boundary_id: "replacement.cli",
},
});
expect(queried.isError).not.toBe(true);
expect(queried.structuredContent).toMatchObject({
status: "ready",
summary: { reasons: 0 },
});
const staleVerification = await client.callTool({
name: "verify_reconstruction",
arguments: {
...INVESTIGATION_EXAMPLES.verify_reconstruction,
coverage: {
workspace_id: workspace.workspace_id,
revision: workspace.revision,
revision_sha256: digest("9"),
boundary_id: "replacement.cli",
},
},
});
expect(staleVerification.isError).toBe(true);
expect(staleVerification.structuredContent).toMatchObject({
error: { code: "evidence_integrity_mismatch" },
});
const unknownBoundary = await client.callTool({
name: "verify_reconstruction",
arguments: {
...INVESTIGATION_EXAMPLES.verify_reconstruction,
coverage: {
workspace_id: workspace.workspace_id,
revision: workspace.revision,
revision_sha256: workspace.revision_sha256,
boundary_id: "replacement.unknown",
},
},
});
expect(unknownBoundary.isError).toBe(true);
expect(unknownBoundary.structuredContent).toMatchObject({
error: { code: "invalid_request" },
});
} finally {
await client.close();
await server.close();
await session.close();
await rm(root, { recursive: true, force: true });
}
});
});
const fixtureWorkspace = () => {
const record = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
predicateType: "rea.coverage-fixture/v1",
operation: "verify-cli",
parameters: {},
result: { status: "pass" },
authority: "controlled-replay",
environment: {
id: "fixture",
platform: "linux",
architecture: "x86_64",
isolation: "container",
},
},
);
const contract = createReconstructionVerifierContract({
verifier_id: "verify.cli",
claim_ids: ["claim.cli"],
dimensions: ["output"],
authority: "controlled-replay",
max_age_ms: Number.MAX_SAFE_INTEGER,
minimum_repeats: 1,
normalization_sha256: digest("4"),
normalization_removes_dimensions: false,
});
return createReconstructionCoverageWorkspace({
name: "mcp-fixture",
revision: 1,
previous_revision_sha256: null,
evidence_bundle: createEvidenceBundle([record]),
artifacts: [
{
artifact_id: "authority",
artifact_sha256: digest("1"),
version: "1",
environment_sha256: digest("2"),
evidence_ids: [record.evidence_id],
},
],
surfaces: [
{
surface_id: "cli.help",
family: "cli-command",
artifact_id: "authority",
occurrence_id: null,
location: "app --help",
authority: "observed",
dependency_surface_ids: [],
evidence_ids: [record.evidence_id],
},
],
owners: [
{
surface_id: "cli.help",
ownership: {
disposition: "implemented",
owner_path: "src/cli.ts",
owner_export: null,
owner_sha256: digest("3"),
path_state: "present",
package_state: "distributed",
authority_route: "none",
},
},
],
claims: [
{
claim_id: "claim.cli",
title: "CLI help matches",
kind: "behavioral",
surface_ids: ["cli.help"],
required_dimensions: ["output"],
required_authority: "controlled-replay",
},
],
verifier_contracts: [contract],
verifier_results: [
{
verifier_id: contract.verifier_id,
contract_sha256: contract.contract_sha256,
observed_at: "2026-07-16T00:00:00.000Z",
status: "pass",
covered_claim_ids: ["claim.cli"],
covered_dimensions: ["output"],
artifact_sha256s: [digest("1")],
owner_sha256s: [digest("3")],
normalization_sha256: digest("4"),
repeats: 1,
evidence_ids: [record.evidence_id],
},
],
residual_unknown_ids: [],
contradictions: [],
package_proofs: [
{
proof_id: "proof.install",
kind: "clean-install",
status: "pass",
artifact_sha256s: [digest("1")],
evidence_ids: [record.evidence_id],
},
],
boundaries: [
{
boundary_id: "replacement.cli",
title: "CLI replacement",
required_surface_ids: ["cli.help"],
required_claim_ids: ["claim.cli"],
required_package_proof_kinds: ["clean-install"],
allowed_dispositions: [],
allowed_unknown_ids: [],
},
],
});
};
@@ -0,0 +1,73 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
describe("reconstruction obligation ledger MCP parity", () => {
it("builds an Evidence-backed page and exposes the retained resource", async () => {
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session);
const client = new Client({ name: "obligation-ledger-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "build_reconstruction_obligation_ledger",
arguments: {
evidence_bundle: createEvidenceBundle([]),
reviewed_obligations: [],
manifest: {
schema_version: 1,
bindings: [],
contradictions: [],
},
limits: { max_obligations: 100 },
page: { offset: 0, limit: 50 },
},
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
evidence_uri: expect.stringMatching(
/^rea:\/\/evidence\/ev_[a-f0-9]{64}$/u,
),
result: {
schema: "ReconstructionObligationLedger",
status: "unknown",
summary: { total: 0 },
},
});
const evidence = result.structuredContent;
if (
evidence === undefined ||
evidence === null ||
typeof evidence !== "object" ||
!("evidence_id" in evidence) ||
typeof evidence.evidence_id !== "string"
)
throw new TypeError("Missing obligation ledger Evidence ID");
const resource = await client.readResource({
uri: `rea://evidence/${evidence.evidence_id}/reconstruction-obligation-ledger`,
});
expect(resource.contents[0]).toEqual(
expect.objectContaining({
text: expect.stringContaining(
'"schema": "ReconstructionObligationLedger"',
),
}),
);
} finally {
await client.close();
await server.close();
await session.close();
}
});
});
@@ -0,0 +1,65 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import { RECONSTRUCTION_READINESS_EXAMPLE } from "../../../src/contracts/reconstructionReadinessExample.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
describe("reconstruction readiness MCP parity", () => {
it("returns a passing compact result and retains the full report resource", async () => {
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session);
const client = new Client({ name: "readiness-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "evaluate_reconstruction_readiness",
arguments: RECONSTRUCTION_READINESS_EXAMPLE,
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
result: {
schema: "ReconstructionReadinessReport",
status: "pass",
summary: { passed_required_stages: 9 },
report_resource_uri: expect.stringMatching(
/^rea:\/\/evidence\/ev_[a-f0-9]{64}\/reconstruction-readiness-report$/u,
),
},
});
expect(result.structuredContent).not.toHaveProperty("result.snapshot");
expect(result.structuredContent).not.toHaveProperty("result.stages");
const content = result.structuredContent;
if (
content === undefined ||
content === null ||
typeof content !== "object" ||
!("evidence_id" in content) ||
typeof content.evidence_id !== "string"
)
throw new TypeError("Missing readiness Evidence ID");
const resource = await client.readResource({
uri: `rea://evidence/${content.evidence_id}/reconstruction-readiness-report`,
});
expect(resource.contents[0]).toEqual(
expect.objectContaining({
text: expect.stringContaining(
'"schema": "ReconstructionReadinessReport"',
),
}),
);
} finally {
await client.close();
await server.close();
await session.close();
}
});
});
@@ -0,0 +1,73 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import { REPLAY_MACHINE_RUN_EXAMPLE } from "../../../src/contracts/replayMachineExample.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
describe("direct replay machine MCP parity", () => {
it("returns typed journal output and safe validation failures", async () => {
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session);
const client = new Client({ name: "replay-machine-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const example = REPLAY_MACHINE_RUN_EXAMPLE;
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "run_replay_machine",
arguments: example,
});
expect(result).toMatchObject({
structuredContent: {
result: {
schema_version: 1,
final_state: "complete",
terminal: true,
decisions: [{ outcome: "matched", transition_sequence: 0 }],
transition_journal: [
{
transition_id: "accept_callback",
captured_aliases: [{ name: "token", sensitive: true }],
},
],
},
},
});
expect(JSON.stringify(result)).not.toContain("opaque");
const invalid = await client.callTool({
name: "run_replay_machine",
arguments: {
...example,
events: [
{
protocol: "http",
connection: "not_applicable",
at_ms: 0,
method: null,
path: "/callback",
headers: {},
body: "private-request-body",
},
],
},
});
expect(invalid).toMatchObject({
isError: true,
structuredContent: { error: { code: "invalid_request" } },
});
expect(JSON.stringify(invalid)).not.toContain("private-request-body");
} finally {
await client.close();
await server.close();
await session.close();
}
});
});
+386
View File
@@ -0,0 +1,386 @@
import { readFile } from "node:fs/promises";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { composeBinarySessionFromProvider } from "../../../src/application/BinarySessionComposition.js";
import {
CATALOG_IDENTITY,
CLI_COMMAND_NAMES,
} from "../../../src/catalogIdentity.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 { TOOL_KINDS } from "../../../src/contracts/toolContractTypes.js";
import { createServer } from "../../../src/server/createServer.js";
import { createServerIdentity } from "../../../src/serverIdentity.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { buildCapabilityInventory } from "../../../src/application/CapabilityInventory.js";
import type {
AnalysisProvider,
CapabilityDescriptor,
} from "../../../src/application/AnalysisProvider.js";
const availabilityProvider = (): AnalysisProvider => {
const identity = { id: "fixture", name: "Fixture", version: "1" };
const capability: CapabilityDescriptor = {
provider: identity,
operation: "current_address",
inputContractVersion: 1,
outputContractVersion: 1,
available: true,
reason: null,
pagination: "none",
exhaustive: true,
effects: {
mutatesArtifact: false,
launchesProcess: false,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
},
limits: {
maxResults: null,
maxPayloadBytes: null,
timeoutMs: null,
},
limitations: [],
};
return {
identity: () => identity,
capabilities: () => [capability],
createClient: () => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}),
};
};
describe("server and catalog identity", () => {
it("derives package and SDK versions from canonical package metadata", async () => {
const packageJson = JSON.parse(await readFile("package.json", "utf8"));
const packageLock = JSON.parse(await readFile("package-lock.json", "utf8"));
expect(PACKAGE_METADATA).toMatchObject({
name: packageJson.name,
version: packageJson.version,
serverSdkVersion:
packageJson.dependencies["@modelcontextprotocol/server"],
clientSdkVersion:
packageJson.dependencies["@modelcontextprotocol/client"],
coreSdkVersion:
packageLock.packages["node_modules/@modelcontextprotocol/core"].version,
});
expect(PRODUCT_IDENTITY.packageVersion).toBe(packageJson.version);
expect(SDK_IDENTITY.server).toBe(
packageJson.dependencies["@modelcontextprotocol/server"],
);
expect(CLI_COMMAND_NAMES).toHaveLength(67);
expect(new Set(CLI_COMMAND_NAMES).size).toBe(67);
expect(CATALOG_IDENTITY.counts).toEqual({
cli_commands: 67,
mcp_tools: TOOL_CONTRACTS.length,
mcp_prompts: 6,
mcp_resources: 2,
mcp_resource_templates: 11,
});
expect(CATALOG_IDENTITY.digests.combined_sha256).toMatch(/^[a-f0-9]{64}$/u);
});
it("reports unknown without a live comparison and distinguishes aligned from stale", () => {
const unknown = createServerIdentity({
startedAt: "2026-07-13T00:00:00.000Z",
});
expect(unknown.alignment.state).toBe("unknown");
const aligned = createServerIdentity({
startedAt: "2026-07-13T00:00:00.000Z",
expected: {
package_version: PRODUCT_IDENTITY.packageVersion,
catalog_digest: CATALOG_IDENTITY.digests.combined_sha256,
server_path: process.argv[1] ?? "unknown",
},
});
expect(aligned.alignment).toMatchObject({ state: "aligned", reasons: [] });
const stale = createServerIdentity({
startedAt: "2026-07-13T00:00:00.000Z",
expected: {
package_version: "1.2.0",
catalog_digest: "0".repeat(64),
},
});
expect(stale.alignment).toMatchObject({
state: "mcp_server_restart_required",
reasons: ["package_version_mismatch", "catalog_digest_mismatch"],
});
});
it("reports composed, host, and target-specific availability truthfully", () => {
const policy = {
processCaptureEnabled: true,
evidenceFileRoots: 1,
investigationInputRoots: 1,
};
const composed = buildCapabilityInventory(
{
open: true,
kind: "executable",
format: "mach-o",
capabilities: [
"list_segments",
"list_documents",
"list_procedures",
"list_strings",
].map((operation) => ({ operation, available: true, reason: null })),
},
policy,
);
expect(composed).toContainEqual(
expect.objectContaining({ name: "binary_overview", available: true }),
);
const artifactTarget = buildCapabilityInventory(
{
open: true,
kind: "artifact",
format: "javascript",
capabilities: [
{ operation: "current_address", available: true, reason: null },
],
},
policy,
);
expect(artifactTarget).toContainEqual(
expect.objectContaining({
name: "current_address",
available: false,
reason: "target_unsupported",
}),
);
const unsupportedHost = buildCapabilityInventory(
{
open: true,
kind: "executable",
format: "elf",
capabilities: [
{
operation: "inspect_macho",
available: false,
availability_code: "unsupported_host",
reason: "Native macOS utilities require macOS.",
},
],
},
policy,
);
expect(unsupportedHost).toContainEqual(
expect.objectContaining({
name: "inspect_macho",
available: false,
reason: "unsupported_host",
}),
);
});
});
describe("live server identity over MCP", () => {
it("exposes live identity, labeled inventories, availability, and list changes", async () => {
const session = composeBinarySessionFromProvider(availabilityProvider());
const server = createServer(session, session);
const client = new Client(
{ name: "identity-test", version: "9" },
{
capabilities: {
elicitation: { form: {} },
},
},
);
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
let toolListChanges = 0;
client.setNotificationHandler("notifications/tools/list_changed", () => {
toolListChanges += 1;
});
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
await assertLiveIdentity(client);
await assertSessionIdentity(client);
await assertCapabilityViews(client);
expect(
(await client.listTools()).tools.map(({ name }) => name),
).not.toContain("current_address");
await client.callTool({
name: "open_binary",
arguments: { path: process.execPath },
});
await expect.poll(() => toolListChanges).toBeGreaterThan(0);
expect(
(await client.listTools()).tools.map(({ name }) => name),
).toContain("current_address");
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
}, 10_000);
});
const assertLiveIdentity = async (client: Client): Promise<void> => {
const instructions = client.getInstructions();
expect(instructions?.length).toBeLessThanOrEqual(640);
expect(instructions).toContain(
"ASAR/JavaScript -> analyze_javascript_application",
);
expect(instructions).toContain(
"native binary/database -> open_binary, then binary_overview",
);
expect(instructions).toContain("Never repeat identical analysis");
expect(instructions).toContain("cite Evidence IDs");
const resource = await client.readResource({ uri: "rea://server/identity" });
const content = resource.contents[0];
expect(content).toBeDefined();
if (content === undefined || !("text" in content))
throw new Error("missing identity resource text");
expect(JSON.parse(content.text)).toMatchObject({
package: { version: PRODUCT_IDENTITY.packageVersion },
server: { version: PRODUCT_IDENTITY.packageVersion },
sdk: {
server: SDK_IDENTITY.server,
client_test: PACKAGE_METADATA.clientSdkVersion,
},
client: { name: "identity-test", version: "9" },
alignment: { state: "unknown" },
});
};
const assertSessionIdentity = async (client: Client): Promise<void> => {
const status = await client.callTool({
name: "binary_session",
arguments: { detail: "full", expected_package_version: "1.2.0" },
});
expect(status.structuredContent).toMatchObject({
result: {
server_identity: {
catalog: {
counts: {
mcp_tools: TOOL_CONTRACTS.length,
cli_commands: CLI_COMMAND_NAMES.length,
},
},
alignment: { state: "mcp_server_restart_required" },
},
tool_availability: expect.arrayContaining([
expect.objectContaining({
name: "current_address",
available: false,
reason: "target_required",
}),
expect.objectContaining({
name: "capture_process_scenario",
available: false,
reason: "policy_disabled",
client_requirements: {
required: [],
optional: ["elicitation_form"],
missing_required: [],
missing_optional: [],
},
}),
expect.objectContaining({
name: "inspect_web_page",
available: false,
reason: "policy_disabled",
}),
expect.objectContaining({
name: "analyze_javascript_application",
available: false,
reason: "policy_disabled",
remediation: expect.stringContaining(
"REA_INVESTIGATION_INPUT_ROOTS_JSON",
),
}),
]),
client_features: {
elicitation_form: true,
elicitation_url: false,
roots: false,
sampling: false,
},
},
});
const summary = await client.callTool({
name: "binary_session",
arguments: { expected_package_version: "1.2.0" },
});
expect(summary.structuredContent).toMatchObject({
result: {
view: "summary",
open: false,
target: null,
alignment: { state: "mcp_server_restart_required" },
recommended_actions: expect.arrayContaining([
"For a supplied target, route by format: ASAR/JavaScript to analyze_javascript_application; archive/package to open_binary(path), then inspect_artifact or inventory_artifact on the active target; managed PE/CLI to inspect_managed_artifact; browser/Electron runtimes to their list-target tools; native binaries to open_binary.",
]),
},
});
expect(JSON.stringify(summary.structuredContent)).not.toContain(
"tool_availability",
);
};
const assertCapabilityViews = async (client: Client): Promise<void> => {
const capabilities = await client.callTool({
name: "binary_session",
arguments: {
detail: "capabilities",
capability_family: "browser-provider",
cursor: 0,
limit: 1,
},
});
expect(capabilities.structuredContent).toMatchObject({
result: {
view: "capabilities",
capability_family: "browser-provider",
capabilities: {
items: [expect.objectContaining({ surface: "browser-provider" })],
cursor: 0,
limit: 1,
total: expect.any(Number),
next_cursor: expect.any(Number),
has_more: true,
},
client_features: {
elicitation_form: true,
elicitation_url: false,
roots: false,
sampling: false,
},
},
});
for (const capabilityFamily of TOOL_KINDS) {
const familyCapabilities = await client.callTool({
name: "binary_session",
arguments: {
detail: "capabilities",
capability_family: capabilityFamily,
limit: 100,
},
});
expect(familyCapabilities.structuredContent).toMatchObject({
result: {
view: "capabilities",
capability_family: capabilityFamily,
capabilities: {
items: expect.arrayContaining([
expect.objectContaining({ surface: capabilityFamily }),
]),
total: expect.any(Number),
},
},
});
}
};
@@ -0,0 +1,119 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { HopperRemoteError } from "../../../src/domain/errors.js";
import { err } from "../../../src/domain/result.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import { createServer } from "../../../src/server/createServer.js";
import {
SESSION_TOOL_CONTRACTS,
TOOL_CONTRACTS,
} from "../../../src/contracts/toolContracts.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../../../src/contracts/managedWorkflowToolContracts.js";
const resources: Array<{ close(): Promise<void> }> = [];
afterEach(async () => {
await Promise.all(
resources.splice(0).map(async (resource) => resource.close()),
);
});
const connect = async (analysis: AnalysisOperationPort) => {
const server = createServer(analysis);
const client = new Client({
name: "integration-test",
version: "1.0.0",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
return client;
};
const text = (result: CallToolResult): string => {
const content = result.content.find((item) => item.type === "text");
if (content?.type !== "text") throw new Error("missing text result");
return content.text;
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
)
throw new Error("missing structured result");
return Object.fromEntries(Object.entries(result.structuredContent));
};
it("preserves the target-open tool inventory without a session", async () => {
const client = await connect({
execute: () => Promise.resolve(ok(null)),
});
const listed = await client.listTools();
expect(listed.tools).toHaveLength(
TOOL_CONTRACTS.length -
SESSION_TOOL_CONTRACTS.length -
MANAGED_WORKFLOW_TOOL_CONTRACTS.length,
);
const names = listed.tools.map((t) => t.name);
expect(names).toContain("binary_overview");
expect(names).toContain("batch_decompile");
expect(names).not.toContain("open_binary");
});
it("projects remote failures without provider or bridge details", async () => {
const client = await connect({
execute: () =>
Promise.resolve(err(new HopperRemoteError(-32000, "bridge timeout"))),
});
const result = await client.callTool({
name: "list_documents",
arguments: {},
});
expect(result.isError).toBe(true);
expect(structured(result)).toMatchObject({
error: {
category: "execution_failure",
},
});
expect(text(result)).toBe(JSON.stringify(result.structuredContent));
});
it("handles concurrent tool calls without corruption", async () => {
const invocations: string[] = [];
const client = await connect({
execute: (name) => {
invocations.push(name);
return Promise.resolve(
ok(
["list_procedures", "list_strings"].includes(name)
? {
items: [],
offset: 0,
limit: 100,
total: 0,
next_offset: null,
has_more: false,
}
: [],
),
);
},
});
const results = await Promise.all([
client.callTool({ name: "list_procedures", arguments: {} }),
client.callTool({ name: "list_segments", arguments: {} }),
client.callTool({ name: "list_strings", arguments: {} }),
]);
expect(results.every((r) => !r.isError)).toBe(true);
expect(invocations).toHaveLength(3);
expect(new Set(invocations).size).toBe(3);
});
@@ -0,0 +1,307 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, expect, it } from "vitest";
import {
composeBinarySessionFromFactory,
composeBinarySessionFromProvider,
} from "../../../src/application/BinarySessionComposition.js";
import type {
AnalysisClient,
AnalysisOperationPort,
AnalysisProvider,
CapabilityDescriptor,
} from "../../../src/application/AnalysisProvider.js";
import { AnalysisCapabilityUnavailableError } from "../../../src/domain/errors.js";
import { err } from "../../../src/domain/result.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import { createServer } from "../../../src/server/createServer.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { processCaptureSchema } from "../../../src/domain/processCapture.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { PROCESS_PROVIDER } from "../../../src/server/sessionToolPolicies.js";
const resources: Array<{ close(): Promise<void> }> = [];
afterEach(async () => {
await Promise.all(
resources.splice(0).map(async (resource) => resource.close()),
);
});
const providerWithCapabilities = (
operations: readonly CapabilityDescriptor["operation"][],
): AnalysisProvider => {
const identity = { id: "fixture", name: "Fixture", version: "1" };
const capabilities: readonly CapabilityDescriptor[] = operations.map(
(operation) => ({
provider: identity,
operation,
inputContractVersion: 1,
outputContractVersion: 1,
available: true,
reason: null,
pagination: "none",
exhaustive: true,
effects: {
mutatesArtifact: false,
launchesProcess: false,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
},
limits: {
maxResults: null,
maxPayloadBytes: null,
timeoutMs: null,
},
limitations: [],
}),
);
return {
identity: () => identity,
capabilities: () => capabilities,
createClient: () => ({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(),
}),
};
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
)
throw new Error("missing structured result");
return Object.fromEntries(Object.entries(result.structuredContent));
};
it("records approved trace truncation as a deduplicated residual unknown", async () => {
const analysis: AnalysisOperationPort = {
execute: () =>
Promise.resolve(
ok({
items: [],
offset: 0,
limit: 500,
total: 0,
next_offset: null,
has_more: false,
}),
),
};
const session = composeBinarySessionFromProvider(
providerWithCapabilities([
"list_strings",
"list_procedures",
"xrefs",
"resolve_containing_procedure",
]),
);
const server = createServer(analysis, session);
const client = new Client({ name: "unknown-workflow", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
await client.callTool({
name: "open_binary",
arguments: { path: process.execPath },
});
for (let attempt = 0; attempt < 2; attempt += 1) {
const traced = await client.callTool({
name: "trace_feature",
arguments: {
query: "license",
max_operations: 1,
unknown_registry_approved: true,
},
});
expect(traced.isError).not.toBe(true);
}
const listed = structured(
await client.callTool({ name: "list_unknowns", arguments: {} }),
);
expect(listed).toMatchObject({
result: {
items: [
{
unknown: {
status: "open",
domain: "control-flow",
question: "Investigation reached the operation budget.",
},
},
],
},
});
}, 10_000);
it("records approved typed capability unavailability without forwarding the flag", async () => {
const received: Array<Readonly<Record<string, unknown>>> = [];
const analysis: AnalysisOperationPort = {
execute: (name, arguments_) => {
received.push(arguments_);
return Promise.resolve(
err(
new AnalysisCapabilityUnavailableError(
"partial",
name,
"Decompiler is not installed.",
),
),
);
},
};
const session = composeBinarySessionFromProvider(
providerWithCapabilities(["procedure_pseudo_code"]),
);
const server = createServer(analysis, session);
const client = new Client({ name: "unavailable-unknown", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
await client.callTool({
name: "open_binary",
arguments: { path: process.execPath },
});
const unavailable = await client.callTool({
name: "procedure_pseudo_code",
arguments: {
procedure: "main",
unknown_registry_approved: true,
},
});
expect(unavailable.isError).toBe(true);
expect(structured(unavailable)).toMatchObject({
error: {
category: "unsupported_provider",
},
});
expect(received[0]).not.toHaveProperty("unknown_registry_approved");
expect(
structured(await client.callTool({ name: "list_unknowns", arguments: {} })),
).toMatchObject({
result: {
items: [
{
unknown: {
domain: "analysis-capability",
question:
"The requested analysis is unavailable for the current target.",
recommended_probes: [
{
rationale:
"Choose another analysis or target that can answer this question.",
},
],
},
},
],
},
});
});
it("records approved capture disagreement as a contradicted unknown", async () => {
const session = composeBinarySessionFromFactory(
() =>
({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(),
}) satisfies AnalysisClient,
);
const left = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
const right = processCaptureSchema.parse({
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
interaction_events: [
{
sequence: 0,
scheduled_at_ms: 0,
dispatched_at_ms: 0,
type: "input",
data: "fixture",
outcome: "dispatched",
},
],
shim_events: [
{
sequence: 0,
at_ms: 0,
command: "fixture",
route_index: null,
arguments: [],
working_directory: "/tmp",
outcome: "unmatched",
},
],
});
const captureEvidence = (capture: typeof left) =>
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture/v4",
operation: "capture_process_scenario",
parameters: {},
result: jsonValueSchema.parse(capture),
confidence: "observed",
authority: "controlled-replay",
});
const leftEvidence = captureEvidence(left);
const rightEvidence = captureEvidence(right);
expect(session.recordEvidence(leftEvidence).ok).toBe(true);
expect(session.recordEvidence(rightEvidence).ok).toBe(true);
const server = createServer(
{ execute: () => Promise.resolve(ok(null)) },
session,
);
const client = new Client({ name: "comparison-unknown", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
const mismatched = await client.callTool({
name: "compare_process_captures",
arguments: {
left_evidence_id: leftEvidence.evidence_id,
left: right,
right_evidence_id: rightEvidence.evidence_id,
right,
},
});
expect(mismatched.isError).toBe(true);
const compared = await client.callTool({
name: "compare_process_captures",
arguments: {
left_evidence_id: leftEvidence.evidence_id,
right_evidence_id: rightEvidence.evidence_id,
unknown_registry_approved: true,
},
});
expect(compared.isError).not.toBe(true);
expect(
structured(await client.callTool({ name: "list_unknowns", arguments: {} })),
).toMatchObject({
result: {
items: [
{
unknown: {
status: "contradicted",
domain: "process-comparison",
question: "Process captures disagree across: interaction, shim",
contradicting_evidence_ids: [rightEvidence.evidence_id],
},
},
],
},
});
});
@@ -0,0 +1,236 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, expect, it } from "vitest";
import { z } from "zod";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import type {
AnalysisClient,
AnalysisOperationPort,
} 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";
const resources: Array<{ close(): Promise<void> }> = [];
afterEach(async () => {
await Promise.all(
resources.splice(0).map(async (resource) => resource.close()),
);
});
const connect = async (analysis: AnalysisOperationPort) => {
const server = createServer(analysis);
const client = new Client({
name: "integration-test",
version: "1.0.0",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
return client;
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
)
throw new Error("missing structured result");
return Object.fromEntries(Object.entries(result.structuredContent));
};
const objectEntries = (value: unknown): readonly [string, unknown][] =>
typeof value === "object" && value !== null && !Array.isArray(value)
? Object.entries(value)
: [];
const referencedSchema = (schema: unknown, root: unknown): unknown => {
const object = Object.fromEntries(objectEntries(schema));
const reference = object.$ref;
if (typeof reference !== "string" || !reference.startsWith("#/$defs/"))
return schema;
return Object.fromEntries(objectEntries(root)).$defs instanceof Object
? Object.fromEntries(
objectEntries(Object.fromEntries(objectEntries(root)).$defs),
)[reference.slice(8)]
: schema;
};
const assertDescribedStrictObjects = (
schema: unknown,
root = schema,
path = "$",
): void => {
for (const [key, value] of objectEntries(schema)) {
if (key === "examples") continue;
if (key === "properties") {
const properties = objectEntries(value);
for (const [property, propertySchema] of properties) {
const resolved = referencedSchema(propertySchema, root);
const propertyObject = Object.fromEntries(
objectEntries(propertySchema),
);
expect(
propertyObject.description ??
Object.fromEntries(objectEntries(resolved)).description,
`${path}.properties.${property}`,
).toEqual(expect.any(String));
assertDescribedStrictObjects(
propertySchema,
root,
`${path}.properties.${property}`,
);
}
expect(
Object.fromEntries(objectEntries(schema)).additionalProperties,
).toBe(false);
continue;
}
assertDescribedStrictObjects(value, root, `${path}.${key}`);
}
if (Array.isArray(schema))
for (const [index, value] of schema.entries())
assertDescribedStrictObjects(value, root, `${path}[${String(index)}]`);
};
const assertDescribedRootObject = (schema: unknown, path: string): void => {
const object = Object.fromEntries(objectEntries(schema));
expect(object.additionalProperties, path).toBe(false);
for (const [property, propertySchema] of objectEntries(object.properties))
expect(
Object.fromEntries(objectEntries(propertySchema)).description,
`${path}.properties.${property}`,
).toEqual(expect.any(String));
};
it("executes a realistic workflow: list methods, decompile selected, get xrefs", async () => {
const client = await connect({
execute: (name, args) => {
switch (name) {
case "list_procedures":
return Promise.resolve(
ok({
items: [
{ address: "0x1000", value: "main" },
{ address: "0x2000", value: "helper" },
],
offset: 0,
limit: 100,
total: 2,
next_offset: null,
has_more: false,
}),
);
case "procedure_pseudo_code":
return Promise.resolve(
ok(`pseudo for ${(args as { procedure: string }).procedure}`),
);
case "xrefs":
return Promise.resolve(ok(["0x1000"]));
default:
return Promise.resolve(ok(null));
}
},
});
const listResult = await client.callTool({
name: "list_procedures",
arguments: {},
});
expect(listResult.isError).not.toBe(true);
expect(structured(listResult)).toMatchObject({
result: {
items: [
{ address: "0x1000", value: "main" },
{ address: "0x2000", value: "helper" },
],
total: 2,
has_more: false,
},
});
const decompileResult = await client.callTool({
name: "procedure_pseudo_code",
arguments: { procedure: "0x1000" },
});
expect(structured(decompileResult)).toMatchObject({
result: "pseudo for 0x1000",
});
const xrefResult = await client.callTool({
name: "xrefs",
arguments: {},
});
expect(structured(xrefResult)).toMatchObject({
result: ["0x1000"],
});
});
it("advertises the complete currently available inventory with a session", async () => {
const session = composeBinarySessionFromFactory(
(_path) =>
({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(),
}) satisfies AnalysisClient,
);
const server = createServer(
{ execute: () => Promise.resolve(ok(null)) },
session,
);
const client = new Client({
name: "integration-test",
version: "1.0.0",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
const listed = await client.listTools();
const names = listed.tools.map((t) => t.name);
expect(names).toContain("open_binary");
expect(names).toContain("close_binary");
expect(names).toContain("binary_session");
expect(names).not.toContain("binary_overview");
expect(names).not.toContain("batch_decompile");
const status = structured(
await client.callTool({
name: "binary_session",
arguments: { detail: "full" },
}),
);
const available = new Set(
z
.object({
result: z.object({
tool_availability: z.array(
z.object({ name: z.string(), available: z.boolean() }),
),
}),
})
.parse(status)
.result.tool_availability.filter((item) => item.available)
.map(({ name }) => name),
);
expect(new Set(names)).toEqual(available);
const contracts = new Map<string, (typeof TOOL_CONTRACTS)[number]>(
TOOL_CONTRACTS.map((contract) => [contract.name, contract]),
);
for (const tool of listed.tools) {
const contract = contracts.get(tool.name);
expect(contract, tool.name).toBeDefined();
expect(tool.title, tool.name).toBe(contract?.title);
expect(tool.description, tool.name).toBe(contract?.description);
expect(tool.annotations, tool.name).toEqual(contract?.annotations);
expect(tool.outputSchema, tool.name).toBeDefined();
assertDescribedStrictObjects(tool.inputSchema, tool.inputSchema, tool.name);
assertDescribedRootObject(tool.outputSchema, `${tool.name}.output`);
}
}, 10_000);
+351
View File
@@ -0,0 +1,351 @@
import { readFile, realpath, rm, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, describe, expect, it } from "vitest";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
composeBinarySessionFromFactory,
composeBinarySessionFromProvider,
} from "../../../src/application/BinarySessionComposition.js";
import type {
AnalysisClient,
AnalysisProvider,
CapabilityDescriptor,
} from "../../../src/application/AnalysisProvider.js";
import { probeProcessCaptureCapability } from "../../../src/application/ProcessHarness.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import { createServer } from "../../../src/server/createServer.js";
import { silentLogger } from "../../../src/logger.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import {
createSessionMcpHarness,
snapshotAndRecordUnknown,
} from "./sessionMcpHarness.js";
const SNAPSHOT_PROFILE = createAnalysisProfile(
{ id: "fixture", name: "Fixture analysis provider", version: "1" },
1,
{ fixture: true },
);
const resources: Array<{ close(): Promise<unknown> }> = [];
const processFixture = fileURLToPath(
new URL("../../fixtures/processFidelity.mjs", import.meta.url),
);
let directory: string | undefined;
afterEach(async () => {
await Promise.all(resources.splice(0).map((resource) => resource.close()));
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
describe("target-free MCP lifecycle", () => {
it("reopens replaced content at one canonical path through MCP", async () => {
directory = await createTestTempDirectory("rea-mcp-replaced-target-");
const targetPath = join(directory, "mutable.hop");
await writeFile(targetPath, "first");
const closed: string[] = [];
const session = composeBinarySessionFromProvider(provider(closed), {
resolveAnalysisProfile: () =>
Promise.resolve(
resultOk({ profile: SNAPSHOT_PROFILE, compatibility: {} }),
),
});
const server = createServer(session, session, { logger: silentLogger });
const mcp = new Client({ name: "replaced-target", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(mcp, server);
await server.connect(serverTransport);
await mcp.connect(clientTransport);
const first = structured(
await mcp.callTool({
name: "open_binary",
arguments: { path: targetPath },
}),
).result;
await writeFile(targetPath, "second");
const second = structured(
await mcp.callTool({
name: "open_binary",
arguments: { path: targetPath },
}),
).result;
const canonicalTargetPath = await realpath(targetPath);
expect(first).toMatchObject({ path: canonicalTargetPath });
expect(second).toMatchObject({ path: canonicalTargetPath });
expect(z.object({ sha256: z.string() }).parse(second).sha256).not.toBe(
z.object({ sha256: z.string() }).parse(first).sha256,
);
expect(closed).toEqual([canonicalTargetPath]);
expect(
z
.object({
result: z.object({ path: z.string(), sha256: z.string() }),
})
.parse(
structured(
await mcp.callTool({
name: "binary_session",
arguments: { detail: "full" },
}),
),
).result,
).toEqual({
path: canonicalTargetPath,
sha256: z.object({ sha256: z.string() }).parse(second).sha256,
});
}, 30_000);
});
describe("target-free MCP workflow", () => {
it("reports no-target, opens, analyzes, switches, reports status, and closes", async () => {
directory = await createTestTempDirectory("rea-mcp-session-");
const lifecycle = await createSessionMcpHarness(
directory,
provider,
resources,
);
const { mcp, first, second, closed } = lifecycle;
const beforeTools = (await mcp.listTools()).tools;
const beforeNames = beforeTools.map(({ name }) => name);
expect(mcp.getInstructions()).toContain(
"archive/package -> open_binary(path), then inspect_artifact/inventory_artifact (active target)",
);
expect(
beforeTools.find(({ name }) => name === "inventory_artifact")
?.description,
).toContain(
"This tool accepts no path; in a target-free session open the target first.",
);
expect(beforeNames).toContain("open_binary");
expect(beforeNames).toContain("binary_session");
expect(beforeNames).not.toContain("current_document");
expect(beforeNames).not.toContain("capture_process_scenario");
expect(
(await mcp.callTool({ name: "open_binary", arguments: { path: first } }))
.isError,
).not.toBe(true);
expect(
structured(
await mcp.callTool({
name: "binary_session",
arguments: { detail: "full" },
}),
),
).toMatchObject({ result: { path: await realpath(first) } });
expect(
text(await mcp.callTool({ name: "current_document", arguments: {} })),
).toContain("first.hop");
const { recordedUnknown, changesBeforeMutation } =
await snapshotAndRecordUnknown(lifecycle, directory);
const resolved = await mcp.callTool({
name: "update_unknown",
arguments: {
approved: true,
unknown_id: recordedUnknown.unknown_id,
expected_revision: 1,
status: "resolved",
severity: "medium",
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
required_authority: "controlled-replay",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
resolution: {
disposition: "out-of-scope",
rationale: "Operator explicitly excluded this branch from scope.",
evidence_ids: [],
},
},
});
expect(resolved.isError).not.toBe(true);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(lifecycle.unknownResourceUpdates()).toBe(1);
expect(lifecycle.resourceListChanges()).toBe(changesBeforeMutation);
expect(
structured(
await mcp.callTool({
name: "verify_unknown_resolution",
arguments: { unknown_id: recordedUnknown.unknown_id },
}),
).result,
).toMatchObject({ valid: true, truthVerified: false });
await mcp.callTool({ name: "open_binary", arguments: { path: second } });
expect(closed.some((path) => path.endsWith("first.hop"))).toBe(true);
expect(
text(await mcp.callTool({ name: "binary_session", arguments: {} })),
).toContain("second.hop");
const snapshotPath = join(directory, "analysis.json");
expect(
structured(
await mcp.callTool({
name: "close_binary",
arguments: { snapshot_path: snapshotPath },
}),
).result,
).toMatchObject({ path: snapshotPath, entries: 0 });
expect(JSON.parse(await readFile(snapshotPath, "utf8"))).toMatchObject({
evidence_bundle: { records: [], unknowns: [] },
});
expect(
text(await mcp.callTool({ name: "binary_session", arguments: {} })),
).toContain('"open":false');
expect(
(
await mcp.callTool({
name: "open_binary",
arguments: { path: first, snapshot_path: snapshotPath },
})
).isError,
).toBe(true);
expect(
structured(await mcp.callTool({ name: "list_unknowns", arguments: {} }))
.result,
).toMatchObject({ items: [] });
expect(
(
await mcp.callTool({
name: "open_binary",
arguments: { path: second, snapshot_path: snapshotPath },
})
).isError,
).not.toBe(true);
await mcp.callTool({ name: "close_binary", arguments: {} });
}, 10_000);
});
describe("process residuals over MCP", () => {
it("records approved process residuals in the unknown registry", async () => {
if (!(await probeProcessCaptureCapability()).available) return;
const session = composeBinarySessionFromFactory(() =>
client("fixture", []),
);
const server = createServer(session, session, {
logger: silentLogger,
processPolicy: {
enabled: true,
executableRoots: [dirname(process.execPath)],
workingRoots: [dirname(processFixture)],
allowedEnvironment: [],
allowExternalNetwork: true,
},
});
const mcp = new Client({ name: "process-unknown", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(mcp, server);
await server.connect(serverTransport);
await mcp.connect(clientTransport);
const captured = await mcp.callTool({
name: "capture_process_scenario",
arguments: {
approved: true,
unknown_registry_approved: true,
executable: process.execPath,
arguments: [processFixture, "partial"],
working_directory: dirname(processFixture),
limits: { output_bytes: 1 },
},
});
expect(captured.isError, text(captured)).not.toBe(true);
const listedUnknowns = await mcp.callTool({
name: "list_unknowns",
arguments: {},
});
expect(listedUnknowns.isError, text(listedUnknowns)).not.toBe(true);
const listed = z
.object({
result: z.object({
items: z.array(
z.object({
unknown: z.object({
question: z.string(),
domain: z.string(),
}),
}),
),
}),
})
.parse(structured(listedUnknowns)).result.items;
expect(listed).toContainEqual({
unknown: expect.objectContaining({
question: "Was network behavior fully observed during capture?",
domain: "process-network",
}),
});
});
});
const client = (path: string, closed: string[]): AnalysisClient => ({
execute: (name) =>
Promise.resolve(
ok(name === "health" ? null : name === "current_document" ? path : null),
),
close: () => {
closed.push(path);
return Promise.resolve();
},
});
const provider = (closed: string[]): AnalysisProvider => {
const identity = { id: "fixture", name: "Fixture", version: "1" };
const capability: CapabilityDescriptor = {
provider: identity,
operation: "current_document",
inputContractVersion: 1,
outputContractVersion: 1,
available: true,
reason: null,
pagination: "none",
exhaustive: true,
effects: {
mutatesArtifact: false,
launchesProcess: false,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
},
limits: {
maxResults: null,
maxPayloadBytes: null,
timeoutMs: null,
},
limitations: [],
};
return {
identity: () => identity,
capabilities: () => [capability],
createClient: (target) => client(target.path, closed),
};
};
const text = (result: CallToolResult): string => {
const content = result.content.find((item) => item.type === "text");
if (content?.type !== "text") throw new Error("missing text result");
return content.text;
};
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);
};
+195
View File
@@ -0,0 +1,195 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { expect } from "vitest";
import { z } from "zod";
import { composeBinarySessionFromProvider } from "../../../src/application/BinarySessionComposition.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import {
createEvidenceBundle,
evidenceBundleSchema,
} from "../../../src/domain/evidenceBundle.js";
import { ok } from "../../../src/domain/result.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import type { AnalysisProvider } from "../../../src/application/AnalysisProvider.js";
const SNAPSHOT_PROFILE = createAnalysisProfile(
{ id: "fixture", name: "Fixture analysis provider", version: "1" },
1,
{ fixture: true },
);
export interface SessionMcpHarness {
readonly mcp: Client;
readonly first: string;
readonly second: string;
readonly closed: string[];
readonly resourceListChanges: () => number;
readonly unknownResourceUpdates: () => number;
}
export const createSessionMcpHarness = async (
root: string,
provider: (closed: string[]) => AnalysisProvider,
resources: Array<{ close(): Promise<unknown> }>,
): Promise<SessionMcpHarness> => {
const first = join(root, "first.hop");
const second = join(root, "second.hop");
await Promise.all([writeFile(first, "one"), writeFile(second, "two")]);
const closed: string[] = [];
const session = composeBinarySessionFromProvider(provider(closed), {
resolveAnalysisProfile: () =>
Promise.resolve(ok({ profile: SNAPSHOT_PROFILE, compatibility: {} })),
});
const filePolicy = {
roots: [root],
maxBytes: 1024 * 1024,
maxDepth: 68,
maxStringLength: 1024,
maxNodes: 10_000,
};
const server = createServer(session, session, {
logger: silentLogger,
evidenceFilePolicy: filePolicy,
analysisSnapshotFilePolicy: filePolicy,
});
const mcp = new Client({ name: "session-test", version: "1.0.0" });
let resourceChanges = 0;
let unknownUpdates = 0;
mcp.setNotificationHandler("notifications/resources/list_changed", () => {
resourceChanges += 1;
});
mcp.setNotificationHandler("notifications/resources/updated", (notice) => {
if (notice.params.uri.startsWith("rea://unknown/")) unknownUpdates += 1;
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(mcp, server);
await server.connect(serverTransport);
await mcp.connect(clientTransport);
return {
mcp,
first,
second,
closed,
resourceListChanges: () => resourceChanges,
unknownResourceUpdates: () => unknownUpdates,
};
};
export const snapshotAndRecordUnknown = async (
harness: SessionMcpHarness,
root: string,
): Promise<{
recordedUnknown: { unknown_id: string; revision: number };
changesBeforeMutation: number;
}> => {
const { mcp } = harness;
const snapshotted = await mcp.callTool({
name: "snapshot_evidence_bundle",
arguments: {},
});
const snapshotResult = z
.object({ result: z.object({ bundle_uri: z.string() }) })
.parse(structured(snapshotted)).result;
const bundleResource = await mcp.readResource({
uri: snapshotResult.bundle_uri,
});
const bundle = evidenceBundleSchema.parse(
JSON.parse(
z.object({ text: z.string() }).parse(bundleResource.contents[0]).text,
),
);
expect(bundle.records).toHaveLength(1);
const evidencePath = join(root, "evidence.json");
expect(
structured(
await mcp.callTool({
name: "export_evidence_bundle",
arguments: { path: evidencePath },
}),
).result,
).toMatchObject({ path: evidencePath, records: 1 });
expect(
structured(
await mcp.callTool({
name: "import_evidence_bundle",
arguments: { path: evidencePath },
}),
).result,
).toEqual({ imported: 0, total: 1 });
const externalEvidencePath = join(root, "external-evidence.json");
await writeFile(
externalEvidencePath,
JSON.stringify(
createEvidenceBundle([
createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{ operation: "external_observation", parameters: {}, result: true },
),
]),
),
);
expect(
structured(
await mcp.callTool({
name: "import_evidence_bundle",
arguments: { path: externalEvidencePath },
}),
).result,
).toEqual({ imported: 1, total: 2 });
await new Promise<void>((resolve) => setImmediate(resolve));
expect(harness.resourceListChanges()).toBe(0);
const changesBeforeMutation = harness.resourceListChanges();
const recordedUnknown = z
.object({
result: z.object({ unknown_id: z.string(), revision: z.number() }),
})
.parse(
structured(
await mcp.callTool({
name: "record_unknown",
arguments: {
approved: true,
question: "Does the alternate branch execute?",
severity: "medium",
domain: "control-flow",
required_authority: "controlled-replay",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
},
}),
),
).result;
expect(recordedUnknown.revision).toBe(1);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(harness.resourceListChanges()).toBe(changesBeforeMutation);
const listedUnknowns = await mcp.callTool({
name: "list_unknowns",
arguments: {},
});
expect(listedUnknowns.isError).not.toBe(true);
expect(
z
.object({ result: z.object({ items: z.array(z.unknown()) }) })
.parse(structured(listedUnknowns)).result.items,
).toHaveLength(1);
return { recordedUnknown, changesBeforeMutation };
};
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);
};
@@ -0,0 +1,68 @@
import { describe, expect, it } from "vitest";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
describe("tool registration options", () => {
it("reuses finalized advertised schemas", () => {
const contract = TOOL_CONTRACTS[0];
expect(contract).toBeDefined();
if (contract === undefined) return;
const first = toolRegistrationOptions(contract);
const second = toolRegistrationOptions(contract);
expect(first.inputSchema["~standard"].jsonSchema.input()).toBe(
second.inputSchema["~standard"].jsonSchema.output(),
);
expect(first.outputSchema["~standard"].jsonSchema.input()).toBe(
second.outputSchema["~standard"].jsonSchema.output(),
);
});
it("gives fallback parameter guidance operational meaning", () => {
const contract = TOOL_CONTRACTS.find(
({ name }) => name === "analyze_function",
);
expect(contract).toBeDefined();
if (contract === undefined) return;
const advertisedSchema =
toolRegistrationOptions(contract).inputSchema[
"~standard"
].jsonSchema.input();
const properties = Object.fromEntries(
Object.entries(advertisedSchema.properties ?? {}),
);
expect(properties.include_assembly).toMatchObject({
description: "Whether to include assembly in the result.",
});
expect(properties.max_instructions).toMatchObject({
description: "Maximum permitted instructions for this operation.",
});
expect(properties.pseudocode_offset).toMatchObject({
description: "Zero-based index of the first pseudocode to return.",
});
});
it("advertises validated contract examples on the MCP input schema", () => {
for (const name of [
"record_unknown",
"run_replay_machine",
"build_reconstruction_obligation_ledger",
]) {
const contract = TOOL_CONTRACTS.find(
(candidate) => candidate.name === name,
);
expect(contract).toBeDefined();
if (contract === undefined) continue;
const schema =
toolRegistrationOptions(contract).inputSchema[
"~standard"
].jsonSchema.input();
expect(schema.examples).toEqual(
contract.examples.map(({ input }) => input),
);
}
});
});
+149
View File
@@ -0,0 +1,149 @@
import { describe, expect, it } from "vitest";
import { z } from "zod";
import type { ToolContract } from "../../../src/contracts/toolContracts.js";
import { ok } from "../../../src/domain/result.js";
import { err } from "../../../src/domain/result.js";
import { HopperProcessError } from "../../../src/domain/errors.js";
import { toCallToolResult } from "../../../src/server/toolResult.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { evidenceResultOf } from "../../../src/contracts/toolOutputSchemas.js";
const contract: ToolContract = {
name: "provider_neutral_fixture",
title: "Provider Neutral Fixture",
description: "Fixture contract for provider-neutral output validation.",
kind: "enhanced",
inputSchema: z.object({}),
outputSchema: z.object({ value: z.string() }),
effects: {
mutatesTarget: false,
mutatesSession: false,
writesFilesystem: false,
launchesProcess: false,
accessesNetwork: false,
changesUiState: false,
mayDiscardData: false,
idempotent: true,
},
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [{ title: "Example fixture request", input: {} }],
};
describe("tool result projection", () => {
it("exposes an actionable adapter code to MCP callers", () => {
const result = toCallToolResult(err(new HopperProcessError(76)), contract);
expect(result.structuredContent).toMatchObject({
error: {
code: "provider_unavailable",
details: { failure_code: "unsupported_demo_dialog" },
category: "execution_failure",
},
});
expect(JSON.stringify(result)).not.toContain("expected Hopper");
});
it("projects bounded private-display coordinates without raw stderr", () => {
const result = toCallToolResult(
err(
new HopperProcessError(80, {
schema_version: 1,
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,
xvfb_stderr_truncated: false,
}),
),
contract,
);
expect(result.structuredContent).toMatchObject({
error: {
details: {
failure_code: "x11_socket_directory_unusable",
diagnostics: {
socket_directory: "/tmp/.X11-unix",
mount_read_only: true,
wsl: true,
strategy: "user-mount-namespace",
xvfb_stderr_truncated: false,
},
},
},
});
expect(JSON.stringify(result)).not.toContain("cookie");
});
it("classifies output contract failures without naming a provider", () => {
const result = toCallToolResult(ok({ value: 42 }), contract);
expect(result).toMatchObject({
structuredContent: {
error: {
code: "unreadable_output",
category: "execution_failure",
message:
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
retryable: false,
remediation: {
action:
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
restart_required: false,
},
},
},
isError: true,
});
expect(result.content[0]).toEqual({
type: "text",
text: JSON.stringify(result.structuredContent),
});
});
it("links successful evidence only when its session resource exists", () => {
const evidence = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: "fixture",
parameters: {},
result: { value: "observed" },
limitations: [],
},
);
const evidenceContract: ToolContract = {
...contract,
outputSchema: evidenceResultOf(z.object({ value: z.string() })),
};
expect(
toCallToolResult(ok(evidence), evidenceContract).content,
).not.toEqual(
expect.arrayContaining([
expect.objectContaining({ type: "resource_link" }),
]),
);
expect(
toCallToolResult(ok(evidence), evidenceContract, {
evidenceResourcesAvailable: true,
}).content,
).toContainEqual(
expect.objectContaining({
type: "resource_link",
uri: `rea://evidence/${evidence.evidence_id}`,
}),
);
});
});