chore: merge current main into PR #2801

This commit is contained in:
morluto
2026-10-13 23:55:24 +08:00
387 changed files with 20117 additions and 3031 deletions
+4 -9
View File
@@ -1,3 +1,4 @@
import { advertisedMcpToolSchemas } from "../../fixtures/advertisedMcpTool.js";
import { API_SURFACE_EXAMPLE } from "../../../src/contracts/analysisViewApiSurfaceExample.js";
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
@@ -212,16 +213,10 @@ it("advertises exact schemas and projects one layout section from retained Evide
inspect: () => Promise.resolve(ok(layout)),
});
const { client, session } = await connect(service);
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_analysis_view",
const { ajv, inputSchema, outputSchema } = await advertisedMcpToolSchemas(
client,
"inspect_analysis_view",
);
if (advertised?.outputSchema === undefined)
throw new Error("inspect_analysis_view must publish both schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
expect(
ajv.validate(inputSchema, {
source: { kind: "inline", evidence: analysisViewLayoutEvidence() },
@@ -0,0 +1,60 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import { createServer } from "../../../src/server/createServer.js";
import { nestedAsarHeader } from "../../fixtures/asarHeader.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("reports expanded ASAR admission failure through MCP and permits a valid retry", async () => {
const root = await createTestTempDirectory("rea-asar-listing-mcp-");
const path = join(root, "app.asar");
const bytes = nestedAsarHeader(64, "d".repeat(256), 4000);
await writeFile(path, bytes);
const session = createTestBinarySession(new ArtifactProvider(process.env));
const server = createServer({ kind: "session", session });
const client = new Client({ name: "asar-listing-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
expect(
(await client.callTool({ name: "open_binary", arguments: { path } }))
.isError,
).not.toBe(true);
const result = await client.callTool({
name: "inspect_artifact",
arguments: {},
});
expect(result.isError).toBe(true);
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "truncated",
category: "truncated",
},
});
expect(result.structuredContent).toBeUndefined();
expect(await readFile(path)).toEqual(bytes);
const valid = join(root, "valid.asar");
await writeFile(valid, nestedAsarHeader(1, "lib", 1));
expect(
(
await client.callTool({
name: "open_binary",
arguments: { path: valid },
})
).isError,
).not.toBe(true);
expect(
(await client.callTool({ name: "inspect_artifact", arguments: {} }))
.isError,
).not.toBe(true);
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
});
+15 -23
View File
@@ -1,9 +1,11 @@
import {
advertisedMcpToolSchemas,
assertRecordedMcpEvidence,
} from "../../fixtures/advertisedMcpTool.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished } from "vitest";
import { BinaryLayoutService } from "../../../src/application/binaryDiagnostics/BinaryLayoutService.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
@@ -43,16 +45,11 @@ it("advertises exact valid schemas and records inline layout without a binary ta
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_binary_layout",
const schemas = await advertisedMcpToolSchemas(
client,
"inspect_binary_layout",
);
if (advertised?.outputSchema === undefined)
throw new Error("layout must publish both schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const { ajv, inputSchema } = schemas;
expect(ajv.validate(inputSchema, { path: value.artifact.path })).toBe(true);
expect(
ajv.validate(inputSchema, {
@@ -64,19 +61,14 @@ it("advertises exact valid schemas and records inline layout without a binary ta
name: "inspect_binary_layout",
arguments: { path: value.artifact.path },
});
expect(response.isError).not.toBe(true);
expect(
ajv.validate(outputSchema, response.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const parsed = toolContract("inspect_binary_layout").outputSchema.parse(
response.structuredContent,
const evidence = assertRecordedMcpEvidence(
response,
"inspect_binary_layout",
schemas,
session,
value,
"observed",
);
const evidence = parseEvidence(parsed);
expect(evidence.confidence).toBe("observed");
expect(evidence.subject?.digest.sha256).toBe(value.artifact.sha256);
expect(parsed.normalized_result).toEqual(value);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
const viewed = await client.callTool({
name: "inspect_analysis_view",
arguments: {
@@ -49,6 +49,9 @@ const observeAgain = (
result,
confidence: source.confidence,
authority: source.authority,
...(source.relationship_coverage === null
? {}
: { relationshipCoverage: source.relationship_coverage }),
},
);
@@ -0,0 +1,86 @@
import { describe, expect, it } from "vitest";
import type {
CallToolResult,
ServerContext,
} from "@modelcontextprotocol/server";
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import type { Evidence } from "../../../src/domain/evidence.js";
import { err, ok } from "../../../src/domain/result.js";
import { silentLogger } from "../../../src/logger.js";
import { createEvidenceToolHandler } from "../../../src/server/contractToolHandler.js";
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
const UNTRUSTED_TARGET_CONTENT = {
provenance: { untrusted_content: true, source: "analysis_target" },
};
const context = {
mcpReq: { signal: new AbortController().signal },
} as ServerContext;
/**
* Deliver one retained partial-observation failure through the shared Evidence
* handler. The handler is the producer of the result: `EvidenceMcpServer` only
* adds the marker later for results that bypass `ToolResultDelivery`, so a
* missing marker here also undercounts the wire budget by the marker's bytes.
*/
const deliverPartialFailure = async (): Promise<{
readonly result: CallToolResult;
readonly evidence: Evidence;
}> => {
const evidence = createEvidence(
undefined,
{ id: "fixture", name: "Completed capture fixture", version: "1" },
{
operation: "inspect_packet_capture",
parameters: { path: "recording.pcap" },
result: { packets: [{ "frame.number": ["1"] }] },
confidence: "observed",
},
);
const failure = new AnalysisCancelledError("inspect_packet_capture", {
partialObservation: evidence,
});
const writer = { recordEvidence: () => ok("added" as const) };
const server = new EvidenceMcpServer(
{ name: "partial-error-framing-test", version: "1" },
{ capabilities: {} },
writer.recordEvidence,
new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE),
);
const contract = toolContract("inspect_packet_capture");
const handler = createEvidenceToolHandler(
server,
async () => err(failure),
silentLogger,
writer.recordEvidence,
);
return {
result: await handler(contract)({ path: "recording.pcap" }, context),
evidence,
};
};
describe("shared Evidence handler target-content framing", () => {
it("marks a retained partial-observation error as untrusted target content", async () => {
const { result, evidence } = await deliverPartialFailure();
expect(result.isError).toBe(true);
expect(result.structuredContent).toMatchObject({
error: {
details: {
partial_observation: {
kind: "retained-evidence",
evidence_id: evidence.evidence_id,
},
},
},
});
expect(result._meta).toEqual(UNTRUSTED_TARGET_CONTENT);
});
});
+36 -24
View File
@@ -1,4 +1,9 @@
import {
advertisedMcpToolSchemas,
assertRecordedMcpEvidence,
} from "../../fixtures/advertisedMcpTool.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { createHash } from "node:crypto";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished, vi } from "vitest";
import { EvmInterfaceService } from "../../../src/application/evm/EvmInterfaceService.js";
@@ -10,6 +15,7 @@ import {
} from "../../../src/domain/analysisErrorCore.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { evmInterfaceSummaryViewResultSchema } from "../../../src/domain/analysisView/analysisView.js";
import { inspectSolidityMetadata } from "../../../src/evm/SolidityMetadata.js";
import { err, ok } from "../../../src/domain/result.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
@@ -26,8 +32,21 @@ import {
evmInterfaceExecution,
} from "../../fixtures/evm/interface.js";
it("advertises exact valid schemas and records inline EVM interface evidence without a binary target", async () => {
const decodedMetadataFixture = () => {
const bytes = Buffer.from("00a1011bffffffffffffffff000b", "hex");
const value = evmInterfaceFixture();
value.bytecode = {
...value.bytecode,
hex: bytes.toString("hex"),
bytes: bytes.length,
sha256: createHash("sha256").update(bytes).digest("hex"),
metadata: inspectSolidityMetadata(bytes),
};
return value;
};
it("advertises exact valid schemas and records inline EVM interface evidence without a binary target", async () => {
const value = decodedMetadataFixture();
const inspect = vi.fn(() =>
Promise.resolve(ok(evmInterfaceExecution(value))),
);
@@ -51,16 +70,11 @@ it("advertises exact valid schemas and records inline EVM interface evidence wit
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_evm_interface",
const schemas = await advertisedMcpToolSchemas(
client,
"inspect_evm_interface",
);
if (advertised?.outputSchema === undefined)
throw new Error("EVM interface inspection must publish both schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const { ajv, inputSchema } = schemas;
expect(
ajv.validate(inputSchema, { path: value.artifact.path, encoding: "hex" }),
).toBe(true);
@@ -84,19 +98,14 @@ it("advertises exact valid schemas and records inline EVM interface evidence wit
name: "inspect_evm_interface",
arguments: { path: value.artifact.path, encoding: "hex" },
});
expect(response.isError).not.toBe(true);
expect(
ajv.validate(outputSchema, response.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const parsed = toolContract("inspect_evm_interface").outputSchema.parse(
response.structuredContent,
assertRecordedMcpEvidence(
response,
"inspect_evm_interface",
schemas,
session,
value,
"inferred",
);
const evidence = parseEvidence(parsed);
expect(evidence.confidence).toBe("inferred");
expect(evidence.subject?.digest.sha256).toBe(value.artifact.sha256);
expect(parsed.normalized_result).toEqual(value);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
expect(
(
await client.callTool({
@@ -280,7 +289,8 @@ it("settles the admitted EVM operation after SDK cancellation and accepts a subs
});
it("returns the exact inferred interface summary while preserving complete defaults and retained source", async () => {
const value = evmInterfaceFixture();
const value = decodedMetadataFixture();
expect(value.bytecode.metadata?.status).toBe("decoded");
value.functions = [
{
selector: "0x11223344",
@@ -419,6 +429,7 @@ it.each(["valid", "wrong-subject", "no-subject"])(
"preserves historical portable EVM Evidence and rejects incompatible identity: %s",
async (scenario) => {
const value = evmInterfaceFixture();
const { metadata: _metadata, ...historicalBytecode } = value.bytecode;
const source = createEvidence(
scenario === "no-subject"
? undefined
@@ -434,7 +445,7 @@ it.each(["valid", "wrong-subject", "no-subject"])(
{
operation: "inspect_evm_interface",
parameters: { path: value.artifact.path, encoding: "hex" },
result: value,
result: { ...value, bytecode: historicalBytecode },
confidence: "inferred",
rawResult: { original: true },
},
@@ -463,6 +474,7 @@ it.each(["valid", "wrong-subject", "no-subject"])(
expect(view.parent_evidence_id).toBe(source.evidence_id);
expect(view.summary.functions).toEqual([]);
expect(view.summary.discovery_completeness).toBe("unknown");
expect(view.summary.bytecode.metadata).toBeNull();
expect(view.coverage).toMatchObject({
total: 0,
examined: 0,
@@ -1,6 +1,14 @@
import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { describe, expect, it, onTestFinished } from "vitest";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { compareFunctions } from "../../../src/domain/functionComparison.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
@@ -271,3 +279,130 @@ describe("function comparison MCP integration", () => {
}
});
});
it.each([
{ status: "changed", expected: "fail" },
{ status: "unknown", expected: "unknown" },
{ status: "unchanged", expected: "pass" },
] as const)(
"checks the aggregate status of imported $status function comparisons",
async ({ status, expected }) => {
const left = FUNCTION_COMPARISON_EXAMPLE.left;
const right =
status === "changed"
? FUNCTION_COMPARISON_EXAMPLE.right
: createEvidence(
{
path: "/fixture/function-right",
sha256: "3".repeat(64),
format: "mach-o",
},
status === "unknown"
? { ...left.provider, id: "other-provider" }
: left.provider,
{
operation: left.operation,
parameters: left.parameters,
result: left.normalized_result,
confidence: left.confidence,
authority: left.authority,
relationshipCoverage: { status: "complete" },
},
);
const result = compareFunctions(left, right);
expect(result.status).toBe(status);
const provider = {
id: "rea-function-comparison",
name: "REA function comparison",
version: "1",
};
const observation = {
operation: "compare_functions",
predicateType: "rea.function-comparison",
parameters: {
left_evidence_id: left.evidence_id,
right_evidence_id: right.evidence_id,
},
confidence: "derived" as const,
authority: "analyst-inference" as const,
evidenceLinks: [left.evidence_id, right.evidence_id],
};
const consistent = createEvidence(undefined, provider, {
...observation,
result: jsonValueSchema.parse(result),
});
const inconsistent =
status === "unchanged"
? null
: createEvidence(undefined, provider, {
...observation,
result: jsonValueSchema.parse({ ...result, status: "unchanged" }),
});
const directory = await createTestTempDirectory("rea-function-status-");
const path = join(directory, "bundle.json");
await writeFile(
path,
JSON.stringify(
createEvidenceBundle([
left,
right,
consistent,
...(inconsistent === null ? [] : [inconsistent]),
]),
),
);
const session = createTestBinarySession(() => {
throw new Error("Imported comparison must not launch a provider");
});
const harness = await createApplicationMcpHarness({ session });
onTestFinished(harness.close);
const imported = await harness.client.callTool({
name: "import_evidence_bundle",
arguments: { path },
});
expect(imported.isError).not.toBe(true);
const verification = (evidence_id: string) =>
harness.client.callTool({
name: "verify_reconstruction",
arguments: {
specification: {
name: "Function aggregate",
claims: [
{
kind: "structural-function",
claim_id: "overall",
title: "Function agrees",
comparison_evidence_id: evidence_id,
dimension: "overall",
},
],
},
},
});
if (inconsistent !== null) {
const rejected = await verification(inconsistent.evidence_id);
expect(parseMcpToolError(rejected).error).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
reason: "invalid_value",
message: expect.stringContaining(
"Function comparison status contradicts its dimensions or function match",
),
},
],
},
});
expect(harness.session.evidenceById(inconsistent.evidence_id)).toEqual(
inconsistent,
);
}
const verified = await verification(consistent.evidence_id);
expect(verified.isError).not.toBe(true);
expect(
parseEvidence(verified.structuredContent).normalized_result,
).toMatchObject({ status: expected });
await harness.client.ping();
},
);
+346 -2
View File
@@ -1,9 +1,353 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { expect, it } from "vitest";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { nativeAotPeFixture } from "../../fixtures/nativeaotPe.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { ok } from "../../../src/domain/result.js";
import { err, ok } from "../../../src/domain/result.js";
import { ghidraFunctionIdentity } from "../../../src/domain/ghidraValues.fixture.js";
import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js";
import {
connectGhidraMcp,
ghidraInstallationHost,
sessionEvidence,
} from "./ghidraMcpHarness.js";
import { spawn } from "node:child_process";
import { mkdir } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { GhidraClient } from "../../../src/ghidra/GhidraClient.js";
import { GhidraProvider } from "../../../src/ghidra/GhidraProvider.js";
import { parseConfig } from "../../../src/config/parseConfig.js";
import { silentLogger } from "../../../src/logger.js";
import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js";
import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js";
import { createServer } from "../../../src/server/createServer.js";
import { waitForExit } from "../../support/process/processFixture.js";
import { GhidraSessionError } from "../../../src/ghidra/GhidraSessionError.js";
it("retains byte-search coverage and rejects malformed pages before creating Evidence", async () => {
const page = {
matches: [
{
address: "0x401000",
segment: ".text",
file_offset: null,
procedure: null,
},
],
searched: {
blocks: [
{ segment: ".text", start: "0x401000", end: "0x40100f", bytes: 16 },
],
bytes: 16,
skipped_uninitialized: [
{ segment: ".bss", start: "0x402000", end: "0x40200f", bytes: 16 },
],
skipped_not_loaded: [
{ segment: ".symtab", start: "0x0", end: "0x17f", bytes: 384 },
],
},
complete: false,
next_cursor: "continuation",
};
let output = jsonValueSchema.parse(page);
const harness = await connectGhidraMcp("byte-search-projection", () =>
Promise.resolve(ok(output)),
);
try {
const first = await harness.mcp.callTool({
name: "search_bytes",
arguments: { pattern: "48 ??", limit: 1 },
});
expect(first.isError).not.toBe(true);
expect(
sessionEvidence(harness.session, first.structuredContent)
.normalized_result,
).toEqual(page);
output = jsonValueSchema.parse({
...page,
matches: [],
complete: true,
next_cursor: null,
});
const last = await harness.mcp.callTool({
name: "search_bytes",
arguments: { pattern: "48 ??", cursor: "continuation" },
});
expect(last.isError).not.toBe(true);
expect(
sessionEvidence(harness.session, last.structuredContent)
.normalized_result,
).toEqual(output);
output = jsonValueSchema.parse({ ...page, complete: true });
const malformed = await harness.mcp.callTool({
name: "search_bytes",
arguments: { pattern: "49 ??" },
});
expect(parseMcpToolError(malformed)).toMatchObject({
error: { code: "unreadable_output" },
});
for (const block of [
{ segment: ".text", start: "0x1000", end: "0x1009", bytes: 1 },
{ segment: ".text", start: "0x1009", end: "0x1000", bytes: 1 },
{ segment: ".text", start: "overlay:0x1000", end: "0x1000", bytes: 1 },
{ segment: ".text", start: "invalid", end: "0x1000", bytes: 1 },
]) {
output = jsonValueSchema.parse({
...page,
searched: { ...page.searched, blocks: [block], bytes: block.bytes },
});
const invalidCoverage = await harness.mcp.callTool({
name: "search_bytes",
arguments: { pattern: "48 ??" },
});
expect(parseMcpToolError(invalidCoverage)).toMatchObject({
error: { code: "unreadable_output" },
});
expect(invalidCoverage.structuredContent).toBeUndefined();
}
const calls = harness.calls.length;
for (const args of [{ pattern: "??" }, { pattern: "48", mask: "ffff" }]) {
const invalid = await harness.mcp.callTool({
name: "search_bytes",
arguments: args,
});
expect(invalid.isError).toBe(true);
expect(JSON.stringify(invalid.content)).toContain(
"Input validation error",
);
}
expect(harness.calls).toHaveLength(calls);
} finally {
await harness.close();
}
});
it("projects cancelled byte searches as typed failures without successful partial Evidence", async () => {
const harness = await connectGhidraMcp("byte-search-cancelled", () =>
Promise.resolve(
err(new GhidraSessionError("cancelled", "Search cancelled")),
),
);
try {
const reply = await harness.mcp.callTool({
name: "search_bytes",
arguments: { pattern: "48 8b" },
});
expect(reply.isError).toBe(true);
expect(parseMcpToolError(reply)).toMatchObject({
error: { code: "cancelled" },
});
expect(reply.structuredContent).toBeUndefined();
} finally {
await harness.close();
}
});
it("searches bytes through MCP and the socket bridge with pagination and skipped coverage", async () => {
const config = parseConfig({ GHIDRA_INSTALL_DIR: "/fixture/ghidra" });
if (!config.ok) throw config.error;
const provider = new GhidraProvider(
config.value,
silentLogger,
{},
ghidraInstallationHost(),
(options) =>
new GhidraClient({
...options,
platform: process.platform,
startupTimeoutMs: 5000,
launcher: {
launch: async (launch) => {
const projectRoot = join(launch.runtimeRoot, "project");
await mkdir(projectRoot);
const child = spawn(
process.execPath,
[
fileURLToPath(
new URL("../../fixtures/fakeGhidra.mjs", import.meta.url),
),
],
{
stdio: ["ignore", "pipe", "pipe"],
env: {
...process.env,
REA_GHIDRA_FIXTURE_CONFIG: JSON.stringify({
endpointPath: launch.endpointPath,
token: launch.token,
runId: launch.runId,
providerVersion: launch.providerVersion,
profileDigest: launch.profileDigest,
targetSha256: launch.targetSha256,
transport: launch.transport,
}),
},
},
);
return ok({
process: child,
ownsProcessLifetime: true as const,
projectRoot,
ghidraLogPath: join(launch.runtimeRoot, "ghidra.log"),
scriptLogPath: join(launch.runtimeRoot, "script.log"),
cleanup: async () => {
const signaled =
child.exitCode === null && child.signalCode === null;
if (signaled) child.kill("SIGTERM");
return (await waitForExit(child, 2000))
? { cleaned: true as const, signaled }
: { cleaned: false as const, reason: "Fixture did not exit" };
},
});
},
},
}),
);
const session = composeBinarySession(
new AnalysisProviderRegistry([provider]),
);
const server = createServer(
{ kind: "session", session },
{ logger: silentLogger },
);
const client = new Client({ name: "byte-search", 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: process.execPath },
});
expect(opened.isError).not.toBe(true);
const first = await client.callTool({
name: "search_bytes",
arguments: { pattern: "48 8b ?? ?? 89", limit: 1 },
});
expect(first.isError, JSON.stringify(first)).not.toBe(true);
const firstEvidence = sessionEvidence(session, first.structuredContent);
expect(firstEvidence.normalized_result).toMatchObject({
matches: [
{
address: "0x1000",
segment: ".text",
file_offset: 0,
procedure: { name: "fixture_main" },
},
],
searched: {
bytes: 10,
skipped_uninitialized: [{ segment: ".bss", bytes: 16 }],
},
complete: false,
next_cursor: "fixture-second-page",
});
const second = await client.callTool({
name: "search_bytes",
arguments: {
pattern: "48 8b ?? ?? 89",
limit: 1,
cursor: "fixture-second-page",
},
});
expect(second.isError).not.toBe(true);
expect(
sessionEvidence(session, second.structuredContent).normalized_result,
).toMatchObject({
matches: [{ address: "0x1005", file_offset: 5 }],
complete: true,
next_cursor: null,
});
const invalid = await client.callTool({
name: "search_bytes",
arguments: { pattern: "??" },
});
expect(invalid.isError).toBe(true);
expect(JSON.stringify(invalid.content)).toContain(
"Pattern must constrain at least one bit",
);
} finally {
await client.close();
await server.close();
const closed = await session.close();
if (!closed.ok) throw closed.error;
}
});
it("retains missing PDB coverage in empty PE name-search Evidence and snapshot replay", async () => {
const root = await createTestTempDirectory("rea-pdb-evidence-");
const targetPath = join(root, "fixture.exe");
await writeFile(targetPath, nativeAotPeFixture());
// Synthetic post-analysis facts at the real provider boundary; no engine is simulated as verified.
const pdb = {
file: "C:\\build\\fixture.pdb",
guid: "01234567-89AB-CDEF-0123-456789ABCDEF",
age: "a",
signature: null,
version: "RSDS",
loaded: false,
};
const harness = await connectGhidraMcp(
"ghidra-pdb-coverage",
(operation) =>
Promise.resolve(
ok(
operation === "procedure_pseudo_code"
? {
value: "int FUN_140001000(void) { return 0; }",
limitations: [],
}
: [],
),
),
{
targetPath,
pdb,
},
);
try {
const reply = await harness.mcp.callTool({
name: "search_procedures",
arguments: { pattern: "add_numbers" },
});
expect(reply.isError).not.toBe(true);
const evidence = sessionEvidence(harness.session, reply.structuredContent);
expect(evidence.normalized_result).toEqual([]);
expect(evidence.analysis_profile?.parameters.pdb_observations).toBe(
"program-info-v1",
);
const limitation = evidence.limitations.find((value) =>
value.includes(pdb.file),
);
expect(limitation).toContain(pdb.guid);
expect(limitation).toContain("age (hex) a");
expect(limitation).toContain("not loaded");
const decompiled = await harness.mcp.callTool({
name: "procedure_pseudo_code",
arguments: { procedure: "0x140001000", document: "fixture" },
});
expect(decompiled.isError).not.toBe(true);
const functionEvidence = sessionEvidence(
harness.session,
decompiled.structuredContent,
);
expect(functionEvidence.limitations).toContain(limitation);
const replay = await harness.session.execute(
"procedure_pseudo_code",
functionEvidence.parameters,
);
if (!replay.ok) throw replay.error;
expect(replay.value.limitations).toContain(limitation);
expect(replay.value.limitations).toContainEqual(
expect.stringContaining("Loaded from a local REA analysis snapshot"),
);
} finally {
await harness.close();
}
});
it("retains defined-string coverage in empty and matching search Evidence", async () => {
let output = jsonValueSchema.parse([]);
+12 -4
View File
@@ -12,6 +12,7 @@ import type { GhidraOperation } from "../../../src/ghidra/GhidraClient.js";
import { GhidraProvider } from "../../../src/ghidra/GhidraProvider.js";
import type { GhidraProviderClientFactory } from "../../../src/ghidra/GhidraProviderClient.js";
import { GHIDRA_SESSION_CAPABILITIES } from "../../../src/ghidra/GhidraSessionValues.js";
import type { GhidraSessionInfo } from "../../../src/ghidra/GhidraSessionValues.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import {
@@ -26,12 +27,19 @@ const INSTALL = "/opt/ghidra_12.1.4_PUBLIC";
export const connectGhidraMcp = async (
name: string,
execute?: ReturnType<GhidraProviderClientFactory>["callTool"],
observations: {
readonly targetPath?: string;
readonly pdb?: GhidraSessionInfo["pdb"];
} = {},
) => {
const calls: GhidraOperation[] = [];
const factory: GhidraProviderClientFactory = (options) => ({
start: () =>
Promise.resolve(
ok(sessionInfo(options.profileDigest, options.targetSha256)),
ok({
...sessionInfo(options.profileDigest, options.targetSha256),
...(observations.pdb === undefined ? {} : { pdb: observations.pdb }),
}),
),
callTool: (operation, input, options) => {
calls.push(operation);
@@ -46,7 +54,7 @@ export const connectGhidraMcp = async (
config.value,
silentLogger,
{},
installationHost(),
ghidraInstallationHost(),
factory,
);
const session = composeBinarySession(
@@ -68,7 +76,7 @@ export const connectGhidraMcp = async (
await mcp.connect(clientTransport);
const opened = await mcp.callTool({
name: "open_binary",
arguments: { path: process.execPath },
arguments: { path: observations.targetPath ?? process.execPath },
});
if (opened.isError === true)
throw new Error(
@@ -92,7 +100,7 @@ export const sessionEvidence = (session: BinarySession, value: unknown) => {
return evidence;
};
const installationHost = (): GhidraInstallationHost => ({
export const ghidraInstallationHost = (): GhidraInstallationHost => ({
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
+23 -1
View File
@@ -43,7 +43,23 @@ describe("official operation arguments", () => {
const execute: AnalysisOperationPort["execute"] = (name, parameters) => {
calls.push({ name, parameters });
return Promise.resolve(
observed(name === "search_strings" ? [] : "int main() {}"),
observed(
name === "search_bytes"
? {
matches: [],
searched: {
blocks: [],
bytes: 0,
skipped_uninitialized: [],
skipped_not_loaded: [],
},
complete: true,
next_cursor: null,
}
: name === "search_strings"
? []
: "int main() {}",
),
);
};
const createSession = () =>
@@ -59,6 +75,7 @@ describe("official operation arguments", () => {
const client = await connect({ execute });
for (const [name, mcpParameters, cliParameters] of [
["procedure_pseudo_code", { procedure: "main" }, { procedure: "main" }],
["search_bytes", { pattern: "48 ??" }, { pattern: "48 ??", limit: 100 }],
[
"search_strings",
{ pattern: "entry" },
@@ -93,6 +110,11 @@ describe("official operation arguments", () => {
["list_procedures", { document: null }],
["procedure_pseudo_code", { procedure: "main", document: 3 }],
["search_strings", { pattern: "entry", case_sensitive: null }],
["search_bytes", { pattern: "??" }],
["search_bytes", { pattern: "48 8B", mask: "ff" }],
["search_bytes", { pattern: "4?" }],
["search_bytes", { pattern: "48", limit: 1001 }],
["search_bytes", { pattern: "48", cursor: null }],
] as const) {
const result = await client.callTool({ name, arguments: parameters });
expect(result.isError).toBe(true);
+67
View File
@@ -10,6 +10,12 @@ 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";
import { HopperProvider } from "../../../src/hopper/HopperProvider.js";
import { parseConfig } from "../../../src/config/parseConfig.js";
import { silentLogger } from "../../../src/logger.js";
import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js";
import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js";
import { createBinarySessionTargets } from "../../fixtures/binarySession.js";
interface Invocation {
readonly name: string;
@@ -18,6 +24,67 @@ interface Invocation {
const resources: Array<{ close(): Promise<void> }> = [];
it("returns typed Hopper byte-search unavailability without launching the provider", async () => {
const [target] = await createBinarySessionTargets();
const config = parseConfig({ HOPPER_LAUNCHER_PATH: process.execPath });
if (!config.ok) throw config.error;
const provider = new HopperProvider(config.value, silentLogger, {}, "linux");
const session = composeBinarySession(
new AnalysisProviderRegistry([provider]),
);
const server = createServer(
{ kind: "session", session },
{ logger: silentLogger },
);
const client = new Client({
name: "hopper-byte-search-unavailable",
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: target },
});
expect(opened.isError).not.toBe(true);
const result = await client.callTool({
name: "search_bytes",
arguments: { pattern: "48 8b" },
});
expect(result.isError).toBe(true);
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
details: { provider_id: "hopper", operation: "search_bytes" },
},
});
} finally {
await client.close();
await server.close();
const closed = await session.close();
if (!closed.ok) throw closed.error;
}
});
it("advertises strict masked-byte arguments and bounded pages", () => {
const contract = OFFICIAL_TOOL_CONTRACTS.find(
({ name }) => name === "search_bytes",
);
expect(
contract?.inputSchema.parse({ pattern: "48 8B ?? ?? 89" }),
).toMatchObject({ limit: 100 });
expect(
contract?.inputSchema.safeParse({ pattern: "48", ignored: true }).success,
).toBe(false);
expect(
contract?.inputSchema.safeParse({ pattern: "48", mask: "f0", limit: 1000 })
.success,
).toBe(true);
});
describe("read_bytes contract", () => {
it("accepts lengths above the former arbitrary ceiling and rejects zero", () => {
const contract = OFFICIAL_TOOL_CONTRACTS.find(
@@ -257,3 +257,72 @@ it("keeps the untrusted target-content marker on an oversized error's replacemen
await Promise.all([client.close(), server.close()]);
}
});
// The delivered error wire omits only the private structured carrier; its
// `isError` flag and any provenance marker count against the result budget.
const deliveredErrorBytes = (nameBytes: number, targetContent: boolean) => {
const { structuredContent: _carrier, ...wire } = failureWithName(
nameBytes,
targetContent,
);
return Buffer.byteLength(JSON.stringify(wire));
};
it.each([false, true])(
"applies the result budget to the complete delivered error (target content: %s)",
async (targetContent) => {
const fittingName =
delivery.resultBudgetBytes - deliveredErrorBytes(0, targetContent);
expect(deliveredErrorBytes(fittingName, targetContent)).toBe(
delivery.resultBudgetBytes,
);
const server = new EvidenceMcpServer(
{ name: "error-budget-test", version: "1" },
{ capabilities: {} },
undefined,
delivery,
);
server.registerTool(
"fitting_failure",
{ inputSchema: z.object({}) },
async () => failureWithName(fittingName, targetContent),
);
server.registerTool(
"one_byte_over_failure",
{ inputSchema: z.object({}) },
async () => failureWithName(fittingName + 1, targetContent),
);
const client = new Client({ name: "error-budget-client", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const fitting = await client.callTool({
name: "fitting_failure",
arguments: {},
});
expect(fitting.isError).toBe(true);
expect(parseMcpToolError(fitting)).toEqual(
failureWithName(fittingName, targetContent).structuredContent,
);
const over = await client.callTool({
name: "one_byte_over_failure",
arguments: {},
});
expect(over.isError).toBe(true);
expect(over.structuredContent).toBeUndefined();
expect(parseMcpToolError(over)).toMatchObject({
error: {
code: "resource_constraint",
details: {
reported_limits: { original_error_code: "invalid_request" },
},
},
});
} finally {
await Promise.all([client.close(), server.close()]);
}
},
20000,
);
@@ -0,0 +1,184 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { z } from "zod";
import { createServer } from "../../../src/server/createServer.js";
import { evidenceBundleSchema } from "../../../src/domain/evidenceBundle.js";
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
import { err, ok } from "../../../src/domain/result.js";
import {
createCacheProvider,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
const bundleResult = (reply: CallToolResult) =>
z.object({ result: evidenceBundleSchema }).parse(reply.structuredContent)
.result;
const successfulTool = async (
client: Client,
name: string,
arguments_: Record<string, unknown> = {},
): Promise<CallToolResult> => {
const reply = await client.callTool({ name, arguments: arguments_ });
expect(reply.isError, `${name}: ${JSON.stringify(reply.content)}`).not.toBe(
true,
);
return reply;
};
const recordUnknownHistory = async (client: Client): Promise<void> => {
const fields = {
severity: "medium",
required_authority: "shipped-artifact",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
};
const unknown = await successfulTool(client, "record_unknown", {
...fields,
question: "Which source revision produced this target?",
domain: "provenance",
});
const recorded = z
.object({ result: z.object({ unknown_id: z.string() }) })
.parse(unknown.structuredContent).result;
await successfulTool(client, "update_unknown", {
...fields,
unknown_id: recorded.unknown_id,
expected_revision: 1,
status: "investigating",
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
resolution: null,
});
};
it.each(["switch", "restart"] as const)(
"preserves investigation records through failed target %s and cleanup retries",
async (transition) => {
const root = await createTestTempDirectory("rea-mcp-switch-evidence-");
const first = join(root, "first.hop");
const second = join(root, "second.hop");
await writeFile(first, "first source-owned target");
await writeFile(second, "second source-owned target");
const application = join(root, "application");
await mkdir(application);
await writeFile(
join(application, "index.js"),
'export const label = "retained";',
);
const nextTarget = transition === "switch" ? second : first;
const calls: string[] = [];
const base = createCacheProvider(calls);
let cleanupAllowed = true;
let created = 0;
const failure = new ProviderCleanupError(
"fixture",
[join(root, "runtime")],
{
reason: "fixture cleanup temporarily unavailable",
},
);
const session = createTestBinarySession({
...base,
createClient: (target, profile, context) => {
created += 1;
return {
...base.createClient(target, profile, context),
operationHealthSnapshot: () => ({
state: cleanupAllowed ? "idle" : "exited",
stage: "analysis",
retryAction: cleanupAllowed ? null : "restart_provider",
exitCode: cleanupAllowed ? null : 1,
requests: [],
}),
close: () =>
Promise.resolve(cleanupAllowed ? ok(null) : err(failure)),
};
},
});
const server = createServer(
{ kind: "session", session },
{ environment: {} },
);
const client = new Client({
name: "switch-evidence-recovery",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const call = (name: string, arguments_: Record<string, unknown> = {}) =>
successfulTool(client, name, arguments_);
const query = { address: "0x1000", document: "fixture" };
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
await call("open_binary", { path: first });
// The cached primitive must be discarded when the provider is retired,
// independently of the investigation's Evidence and Unknown history.
await call("address_name", query);
const analyzed = await call("analyze_javascript_application", {
input_path: application,
format: "directory",
max_heap_mb: 128,
});
const applicationId = z
.object({ evidence_id: z.string() })
.parse(analyzed.structuredContent).evidence_id;
await recordUnknownHistory(client);
const before = bundleResult(await call("get_evidence_bundle"));
expect(before.records).toHaveLength(4);
expect(before.unknowns).toHaveLength(2);
cleanupAllowed = false;
for (let attempt = 0; attempt < 2; attempt += 1) {
const replacement = await client.callTool({
name: "open_binary",
arguments: { path: nextTarget },
});
expect(parseMcpToolError(replacement)).toMatchObject({
error: { code: "cleanup_incomplete" },
});
expect(session.activeTarget()).toBeUndefined();
expect(created).toBe(1);
expect(bundleResult(await call("get_evidence_bundle"))).toEqual(before);
}
const exportedPath = join(root, "retained.json");
await call("export_evidence_bundle", { path: exportedPath });
expect(
evidenceBundleSchema.parse(
JSON.parse(await readFile(exportedPath, "utf8")),
),
).toEqual(before);
cleanupAllowed = true;
await call("open_binary", { path: nextTarget });
expect(bundleResult(await call("get_evidence_bundle"))).toEqual(before);
await call("address_name", query);
expect(
calls.filter((operation) => operation === "address_name"),
).toHaveLength(2);
expect(created).toBe(2);
await call("inspect_analysis_view", {
source: { kind: "retained-evidence", evidence_id: applicationId },
view: { kind: "page", collection: "modules", offset: 0, limit: 10 },
});
await call("close_binary");
const closed = bundleResult(await call("get_evidence_bundle"));
expect(closed.records).toEqual([]);
expect(closed.unknowns).toEqual([]);
} finally {
cleanupAllowed = true;
await client.close();
await server.close();
await session.close();
}
},
);
@@ -217,6 +217,46 @@ function resolveReference(schema: unknown, reference: string): unknown {
return value;
}
function localReferenceExpansions(schema: Record<string, unknown>): number {
// Clients that render SDK declarations from the advertised input expand
// schema-local references against a shared per-input budget; Pi 1.1.0
// code-mode allows 32 and renders every later reference as `unknown`.
// Count conservatively: every resolvable, non-cyclic reference occurrence
// reached while walking the input, never the definitions themselves.
let count = 0;
const visit = (node: unknown, active: ReadonlySet<string>): void => {
if (Array.isArray(node)) {
node.forEach((child) => visit(child, active));
return;
}
if (!isRecord(node)) return;
if (typeof node.$ref === "string" && !active.has(node.$ref)) {
const target = resolveReference(schema, node.$ref);
if (target !== undefined) {
count += 1;
visit(target, new Set([...active, node.$ref]));
return;
}
}
for (const [key, value] of Object.entries(node)) {
if (
[
"$defs",
"definitions",
"examples",
"default",
"const",
"enum",
].includes(key)
)
continue;
visit(value, active);
}
};
visit(schema, new Set());
return count;
}
function recursiveReferences(tools: readonly ToolSchemas[]): string[] {
return tools.flatMap((tool) =>
(["inputSchema", "outputSchema"] as const).flatMap((kind) => {
@@ -674,6 +714,14 @@ it("ships nonrecursive input and output schemas in the generated catalog", () =>
expect(recursiveReferences(GENERATED_MCP_TOOL_CATALOG)).toEqual([]);
});
it("keeps advertised input references within the client expansion budget", () => {
for (const tool of GENERATED_MCP_TOOL_CATALOG)
expect(
localReferenceExpansions(tool.inputSchema),
`${tool.name} exhausts the shared reference-expansion budget`,
).toBeLessThanOrEqual(32);
});
it("rejects unresolved output-schema references even for uncalled tools", () => {
const errors = schemaErrors([
{
+97 -95
View File
@@ -1,5 +1,9 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import {
advertisedMcpToolSchemas,
assertRecordedMcpEvidence,
} from "../../fixtures/advertisedMcpTool.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it, onTestFinished, vi } from "vitest";
import { readFile, realpath, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -20,20 +24,6 @@ import {
wasmArtifactExecution,
} from "../../fixtures/wasm/artifact.js";
const wasmToolSchemas = async (client: Client) => {
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_wasm_artifact",
);
if (advertised?.outputSchema === undefined)
throw new Error("WASM recovery must name an advertised static tool");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
return { name: advertised.name, ajv, inputSchema, outputSchema };
};
const assertFirstSummaryDelivery = async (
harness: Awaited<ReturnType<typeof createApplicationMcpHarness>>,
value: ReturnType<typeof wasmArtifactFixture>,
@@ -43,7 +33,7 @@ const assertFirstSummaryDelivery = async (
ajv: wasmAjv,
inputSchema,
outputSchema,
} = await wasmToolSchemas(harness.client);
} = await advertisedMcpToolSchemas(harness.client, "inspect_wasm_artifact");
const summaryInput = { path: value.artifact.path, detail: "summary" };
expect(wasmAjv.validate(inputSchema, summaryInput)).toBe(true);
expect(
@@ -91,73 +81,86 @@ const assertFirstSummaryDelivery = async (
return { summary, retained };
};
it("directs rejected native WASM opening to the advertised static tool while preserving missing-WABT diagnostics", async () => {
const directory = await createTestTempDirectory("rea-wasm-recovery-");
const path = join(
await realpath(directory),
process.platform === "win32" ? "module space.bin" : 'module "quoted".bin',
);
await writeFile(path, Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]));
const createClient = vi.fn(() => {
throw new Error("native provider must not start for WASM");
});
const session = createTestBinarySession(createClient);
const harness = await createApplicationMcpHarness({
session,
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const { client } = harness;
const { name, ajv, inputSchema } = await wasmToolSchemas(client);
const input = { path };
expect(
toolContract("inspect_wasm_artifact").inputSchema.safeParse(input).success,
).toBe(true);
const opening = await client.callTool({
name: "open_binary",
arguments: input,
});
expect(opening.isError).toBe(true);
const failure = parseMcpToolError(opening);
expect(failure).toMatchObject({
error: {
code: "target_unavailable",
category: "unsupported_target",
details: { constraint: "wasm_requires_static_inspection" },
},
});
expect(failure.error.remediation.action).toContain(JSON.stringify({ path }));
expect(ajv.validate(inputSchema, input)).toBe(true);
const inspection = await client.callTool({
name,
arguments: input,
});
expect(inspection.isError).toBe(true);
expect(parseMcpToolError(inspection)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: "inspect_wasm_artifact",
reason: expect.stringContaining("REA_WABT_BIN_DIRECTORY"),
it.each(["bin", "hop"])(
"directs rejected native WASM opening (%s suffix) to the advertised static tool while preserving missing-WABT diagnostics",
async (extension) => {
const directory = await createTestTempDirectory("rea-wasm-recovery-");
const path = join(
await realpath(directory),
process.platform === "win32"
? `module space.${extension}`
: `module "quoted".${extension}`,
);
await writeFile(path, Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]));
const createClient = vi.fn(() => {
throw new Error("native provider must not start for WASM");
});
const session = createTestBinarySession(createClient);
const harness = await createApplicationMcpHarness({
session,
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const { client } = harness;
const { name, ajv, inputSchema } = await advertisedMcpToolSchemas(
client,
"inspect_wasm_artifact",
);
const input = { path };
const opening = await client.callTool({
name: "open_binary",
arguments: input,
});
expect(opening.isError).toBe(true);
const failure = parseMcpToolError(opening);
expect(failure).toMatchObject({
error: {
code: "target_unavailable",
category: "unsupported_target",
details: { constraint: "wasm_requires_static_inspection" },
},
},
});
const summary = await client.callTool({
name,
arguments: { ...input, detail: "summary" },
});
expect(parseMcpToolError(summary)).toMatchObject({
error: {
code: "capability_unavailable",
details: { reason: expect.stringContaining("REA_WABT_BIN_DIRECTORY") },
},
});
await client.ping();
expect(createClient).not.toHaveBeenCalled();
expect(await readFile(path)).toEqual(
Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]),
);
});
});
const [, recoveryName, serializedInput] =
failure.error.remediation.action.match(
/call (\w+) with (\{.*\}) or run/,
) ?? [];
expect(recoveryName).toBe(name);
const recoveryInput = z
.object({ path: z.literal(path) })
.strict()
.parse(JSON.parse(serializedInput ?? "null"));
expect(ajv.validate(inputSchema, recoveryInput)).toBe(true);
const inspection = await client.callTool({
name: recoveryName ?? "",
arguments: recoveryInput,
});
expect(inspection.isError).toBe(true);
expect(parseMcpToolError(inspection)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: "inspect_wasm_artifact",
reason: expect.stringContaining("REA_WABT_BIN_DIRECTORY"),
},
},
});
const summary = await client.callTool({
name,
arguments: { ...input, detail: "summary" },
});
expect(parseMcpToolError(summary)).toMatchObject({
error: {
code: "capability_unavailable",
details: { reason: expect.stringContaining("REA_WABT_BIN_DIRECTORY") },
},
});
await client.ping();
expect(createClient).not.toHaveBeenCalled();
expect(await readFile(path)).toEqual(
Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]),
);
},
);
it("advertises exact valid schemas and records inline WASM interface evidence without a binary target", async () => {
const value = wasmArtifactFixture();
@@ -175,7 +178,11 @@ it("advertises exact valid schemas and records inline WASM interface evidence wi
});
onTestFinished(harness.close);
const { client } = harness;
const { ajv, inputSchema, outputSchema } = await wasmToolSchemas(client);
const schemas = await advertisedMcpToolSchemas(
client,
"inspect_wasm_artifact",
);
const { ajv, inputSchema } = schemas;
expect(ajv.validate(inputSchema, { path: value.artifact.path })).toBe(true);
expect(
ajv.validate(inputSchema, {
@@ -188,19 +195,14 @@ it("advertises exact valid schemas and records inline WASM interface evidence wi
name: "inspect_wasm_artifact",
arguments: { path: value.artifact.path },
});
expect(response.isError).not.toBe(true);
expect(
ajv.validate(outputSchema, response.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const parsed = toolContract("inspect_wasm_artifact").outputSchema.parse(
response.structuredContent,
assertRecordedMcpEvidence(
response,
"inspect_wasm_artifact",
schemas,
session,
value,
"observed",
);
const evidence = parseEvidence(parsed);
expect(evidence.confidence).toBe("observed");
expect(evidence.subject?.digest.sha256).toBe(value.artifact.sha256);
expect(parsed.normalized_result).toEqual(value);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
expect(
(
await client.callTool({