chore: merge main and preserve tool effect exceptions

This commit is contained in:
64579525
2026-10-12 22:17:04 +08:00
67 changed files with 6982 additions and 288 deletions
+236
View File
@@ -0,0 +1,236 @@
import { expect, it } from "vitest";
import { createCli } from "../../../src/cli.js";
import type { FridaInstrumentationPort } from "../../../src/application/frida/FridaInstrumentationPort.js";
import { AnalysisCapabilityUnavailableError } from "../../../src/domain/analysisErrorCore.js";
import { FridaInstrumentationManager } from "../../../src/frida/FridaInstrumentationManager.js";
it("maps one-shot Frida CLI target, script, duration, and remote options", async () => {
const calls: unknown[] = [];
const provider: FridaInstrumentationPort = {
async listDevices() {
calls.push({ operation: "devices" });
return { ok: true, value: { devices: [], cleanupError: null } };
},
async listProcesses() {
return {
ok: true,
value: { deviceId: "local", processes: [], cleanupError: null },
};
},
async startSession(input) {
calls.push({ operation: "start", input });
return {
ok: true,
value: {
sessionId: "00000000-0000-4000-8000-000000000001",
deviceId: "remote",
target: "fixture",
pid: 71,
mode: input.mode,
state: "running",
},
};
},
async loadScript(sessionId, source) {
calls.push({ operation: "load", sessionId, source });
return {
ok: true,
value: {
scriptId: "00000000-0000-4000-8000-000000000002",
sourceKind: source.sourceKind,
sourcePath: source.sourceKind === "file" ? source.path : null,
sourceSha256: "a".repeat(64),
messages: [{ type: "send", payload: "observed" }],
messagesTruncated: false,
},
};
},
async resumeSession(sessionId) {
calls.push({ operation: "resume", sessionId });
return { ok: true, value: null };
},
async unloadScript() {
return { ok: true, value: null };
},
status(sessionId) {
return {
sessionId,
deviceId: "remote",
target: "fixture",
pid: 71,
mode: "attach",
state: "running",
targetResumeObserved: false,
scripts: [],
messages: [],
messagesTruncated: false,
};
},
async closeSession(sessionId) {
calls.push({ operation: "close", sessionId });
return { ok: true, value: { targetResumeObserved: false } };
},
async closeAll() {},
};
const cli = createCli({}, undefined, provider);
let stdout = "";
let exitCode = 0;
await cli.serve(
[
"instrument-with-frida",
"attach",
"71",
"--script",
"send('hello')",
"--remote-address",
"127.0.0.1:27042",
"--token",
"synthetic-secret-token",
"--keepalive-interval",
"10",
"--duration-ms",
"0",
"--json",
],
{
env: {},
exit: (code) => {
exitCode = code;
},
stdout: (text) => {
stdout += text;
},
},
);
expect(exitCode).toBe(0);
const result: unknown = JSON.parse(stdout);
expect(JSON.stringify(result)).not.toContain("synthetic-secret-token");
expect(calls).toEqual([
{
operation: "start",
input: {
mode: "attach",
pid: 71,
remote: {
address: "127.0.0.1:27042",
token: "synthetic-secret-token",
keepaliveInterval: 10,
},
source: { sourceKind: "inline", source: "send('hello')" },
durationMs: 0,
},
},
{
operation: "load",
sessionId: "00000000-0000-4000-8000-000000000001",
source: { sourceKind: "inline", source: "send('hello')" },
},
{
operation: "close",
sessionId: "00000000-0000-4000-8000-000000000001",
},
]);
stdout = "";
exitCode = 0;
await cli.serve(
["list-frida-devices", "--token", "synthetic-secret-token", "--json"],
{
env: {},
exit: (code) => {
exitCode = code;
},
stdout: (text) => {
stdout += text;
},
},
);
expect(exitCode).not.toBe(0);
expect(calls).toHaveLength(3);
expect(stdout).not.toContain("synthetic-secret-token");
});
it("awaits failed startup cleanup and retains the primary error if cleanup still fails", async () => {
for (const cleanupFails of [false, true]) {
const calls: string[] = [];
const provider: FridaInstrumentationPort =
new FridaInstrumentationManager();
provider.startSession = async () => {
calls.push("start");
return {
ok: false,
error: new AnalysisCapabilityUnavailableError(
"frida",
"start_frida_session",
"attach failed after spawn",
{
cleanup: {
reason: "first resume failed",
resources: ["paused spawn"],
},
},
),
};
};
provider.closeAll = async () => {
calls.push("cleanup");
if (cleanupFails) throw new Error("resume still failed");
};
let stdout = "";
await createCli({}, undefined, provider).serve(
[
"instrument-with-frida",
"spawn",
"/tmp/fixture",
"--script",
"send('ready')",
"--json",
],
{
env: {},
exit: () => {},
stdout: (text) => {
stdout += text;
},
},
);
expect(calls).toEqual(["start", "cleanup"]);
const output: unknown = JSON.parse(stdout);
expect(output).toMatchObject({
code: cleanupFails ? "cleanup_incomplete" : "capability_unavailable",
});
expect(stdout).toContain("attach failed after spawn");
if (cleanupFails) expect(stdout).toContain("primary_error");
}
});
it("preserves observed devices when CLI provider cleanup fails", async () => {
const provider: FridaInstrumentationPort = new FridaInstrumentationManager();
const devices = [
{ deviceId: "remote-device", name: "selected endpoint", type: "remote" },
];
provider.listDevices = async () => ({
ok: true,
value: { devices, cleanupError: null },
});
provider.closeAll = async () => {
throw new Error("remote removal failed");
};
let stdout = "";
await createCli({}, undefined, provider).serve(
["list-frida-devices", "--json"],
{
env: {},
exit: () => {},
stdout: (text) => {
stdout += text;
},
},
);
const output: unknown = JSON.parse(stdout);
expect(output).toMatchObject({
code: "cleanup_incomplete",
details: { diagnostics: { partial_observation: { devices } } },
});
});
+11
View File
@@ -30,3 +30,14 @@ it("validates decompile item input before contacting the engine", async () => {
],
});
});
it("reports an invalid endpoint without breaking other commands", async () => {
const environment = { REA_JEB_MCP_URL: "http://localhost:8425/mcp" };
const jeb = await serveCli(["inspect-jeb-client", "--json"], environment);
expect(JSON.parse(jeb.stdout)).toMatchObject({
code: "configuration_invalid",
details: { settings: [{ setting: "REA_JEB_MCP_URL" }] },
});
const capabilities = await serveCli(["capabilities", "--json"], environment);
expect(capabilities.exitCode).toBe(0);
});
@@ -1,5 +1,6 @@
import { constants as fsConstants } from "node:fs";
import {
chmod,
copyFile,
lstat,
mkdir,
@@ -21,6 +22,7 @@ import { PRODUCT_IDENTITY } from "../../../src/identity.js";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import { readConfigurationFile } from "../../../src/application/ClientConfigurationFiles.js";
import {
detectClients,
systemSetupHost,
@@ -1526,6 +1528,68 @@ describe("client configuration filesystem removal", () => {
);
});
it("removes emptied skill directories and keeps ones with user files", async () => {
const home = await createTestTempDirectory("rea-uninstall-skill-dirs-");
roots.push(home);
const shared = join(home, ".agents/skills/reverse-engineer-anything");
const claude = join(home, ".claude/skills/reverse-engineer-anything");
for (const root of [shared, claude]) {
await mkdir(join(root, "references"), { recursive: true });
await writeFile(join(root, "SKILL.md"), ownedSkillManifest);
await writeFile(
join(root, "references/evidence-workflows.md"),
"managed",
);
}
await writeFile(join(claude, "notes.md"), "user");
const result = await runUninstall(
false,
systemUninstallHost(home, undefined, {
HOME: home,
CLAUDE_CONFIG_DIR: join(home, ".claude"),
}),
);
expect(result.status).toBe("complete");
await expect(lstat(shared)).rejects.toMatchObject({ code: "ENOENT" });
await expect(lstat(join(claude, "references"))).rejects.toMatchObject({
code: "ENOENT",
});
expect(await readFile(join(claude, "notes.md"), "utf8")).toBe("user");
});
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"reports an emptied skill directory that cannot be removed",
async () => {
const home = await createTestTempDirectory("rea-uninstall-skill-perm-");
roots.push(home);
const parent = join(home, ".agents/skills");
const root = join(parent, "reverse-engineer-anything");
await mkdir(join(root, "references"), { recursive: true });
await writeFile(join(root, "SKILL.md"), ownedSkillManifest);
await chmod(parent, 0o555);
try {
const result = await runUninstall(
false,
systemUninstallHost(home, undefined, { HOME: home }),
);
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({
name: "skill",
status: "failed",
detail: expect.stringContaining(
`Managed skill directory could not be removed: ${root}.`,
),
}),
);
} finally {
await chmod(parent, 0o755);
}
},
);
it("removes an owned entry through a symlink without replacing it", async () => {
const home = await createTestTempDirectory("rea-uninstall-symlink-");
roots.push(home);
@@ -1593,6 +1657,34 @@ describe("uninstall configuration preflight", () => {
expect(await readFile(config, "utf8")).toBe("not-json");
});
it.each([
['{"mcpServers": null}', '"mcpServers" must be an object'],
["[]", "The configuration root must be an object"],
])(
"names the structural problem in valid JSON %s",
async (content, problem) => {
const home = await createTestTempDirectory("rea-uninstall-shape-");
roots.push(home);
const config = join(home, ".cursor/mcp.json");
await mkdir(dirname(config), { recursive: true });
await writeFile(config, content);
expect(await readConfigurationFile(config, "json")).toMatchObject({
ok: false,
error: {
kind: "malformed",
detail: `Configuration ${config} is malformed: ${problem}`,
},
});
const result = await runUninstall(false, systemUninstallHost(home));
expect(result.items).toContainEqual({
name: "cursor",
status: "failed",
detail: `Configuration was not changed: ${problem}. Repair it, then rerun uninstall.`,
});
expect(await readFile(config, "utf8")).toBe(content);
},
);
it("stops before any removal when one client configuration is malformed", async () => {
const home = await createTestTempDirectory("rea-uninstall-stop-");
roots.push(home);
@@ -9,6 +9,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { SUPPORTED_CLIENT_DEFINITIONS } from "../../../src/application/SupportedClients.js";
import { CLI_COMMAND_NAMES } from "../../../src/cliCommandNames.js";
import { createCli } from "../../../src/cli.js";
import { FRIDA_PROVIDER_IDENTITY } from "../../../src/frida/FridaInstrumentationManager.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import {
HOPPER_OPERATIONS,
@@ -78,6 +79,14 @@ describe("canonical product catalog", () => {
catalog.providers.find(({ id }) => id === GHIDRA_PROVIDER_IDENTITY.id)
?.capabilities,
).toEqual([...GHIDRA_OPERATIONS].sort());
expect(
catalog.providers.find(({ id }) => id === FRIDA_PROVIDER_IDENTITY.id)
?.capabilities,
).toEqual(
TOOL_CONTRACTS.filter(({ name }) => name.includes("frida"))
.map(({ name }) => name)
.sort(),
);
expect(
JSON.parse(await readFile("docs/public/product-catalog.json", "utf8")),
).toEqual(catalog);
+415
View File
@@ -0,0 +1,415 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import type { AnySchema } from "ajv";
import { expect, it, onTestFinished } from "vitest";
import type { FridaInstrumentationPort } from "../../../src/application/frida/FridaInstrumentationPort.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { FridaInstrumentationManager } from "../../../src/frida/FridaInstrumentationManager.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
const createFridaTestProvider = (
overrides: Partial<FridaInstrumentationPort> = {},
): FridaInstrumentationPort => ({
async listDevices() {
return {
ok: true,
value: {
devices: [
{ deviceId: "remote-device", name: "target", type: "remote" },
],
cleanupError: null,
},
};
},
async listProcesses() {
return {
ok: true,
value: { deviceId: "remote-device", processes: [], cleanupError: null },
};
},
async startSession(input) {
return {
ok: true,
value: {
sessionId: "00000000-0000-4000-8000-000000000001",
deviceId: "remote-device",
target: String(input.mode),
pid: 10,
mode: input.mode,
state: input.mode === "spawn" ? "paused" : "running",
},
};
},
async loadScript() {
return {
ok: true,
value: {
scriptId: "00000000-0000-4000-8000-000000000002",
sourceKind: "inline",
sourcePath: null,
sourceSha256: "a".repeat(64),
messages: [],
messagesTruncated: false,
},
};
},
async resumeSession() {
return { ok: true, value: null };
},
async unloadScript() {
return { ok: true, value: null };
},
status(sessionId) {
return {
sessionId,
deviceId: "remote-device",
target: "fixture",
pid: 10,
mode: "attach",
state: "running",
targetResumeObserved: false,
scripts: [],
messages: [],
messagesTruncated: false,
};
},
async closeSession() {
return { ok: true, value: { targetResumeObserved: false } };
},
async closeAll() {},
...overrides,
});
const expectFridaToolsAvailable = async (client: Client) => {
const inventory = await client.callTool({
name: "binary_session",
arguments: {},
});
const parsedInventory = toolContract("binary_session").outputSchema.safeParse(
inventory.structuredContent,
);
if (!parsedInventory.success)
throw new Error("Invalid binary session output");
const toolAvailability = expandToolAvailability(
parsedInventory.data.result.tool_availability,
);
expect(toolAvailability).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "list_frida_devices",
available: true,
reason: "available",
}),
expect.objectContaining({
name: "instrument_with_frida",
available: true,
reason: "available",
}),
]),
);
};
it("advertises Frida MCP schemas and keeps remote credentials out of results", async () => {
const session = createTestBinarySession(() => {
throw new Error("Binary provider must not start");
});
const server = createServer(
{ kind: "session", session },
{
fridaInstrumentation: createFridaTestProvider(),
},
);
const client = new Client({ name: "frida-contract", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const tools = (await client.listTools()).tools;
const advertised = tools.find((tool) => tool.name === "list_frida_devices");
if (
advertised?.inputSchema === undefined ||
advertised.outputSchema === undefined
)
throw new Error("Missing advertised Frida schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const response = await client.callTool({
name: "list_frida_devices",
arguments: {
remote: { address: "127.0.0.1:27042", token: "synthetic-secret-token" },
},
});
expect(response.isError).not.toBe(true);
expect(JSON.stringify(response.structuredContent)).not.toContain(
"synthetic-secret-token",
);
expect(ajv.validate(outputSchema, response.structuredContent)).toBe(true);
expect(toolContract("start_frida_session").effects.mutatesTarget).toBe(true);
const processes = await client.callTool({
name: "list_frida_processes",
arguments: { device_id: "remote-device" },
});
expect(processes.isError).not.toBe(true);
const started = await client.callTool({
name: "start_frida_session",
arguments: {
mode: "attach",
pid: 10,
remote: { address: "127.0.0.1:27042", token: "synthetic-secret-token" },
},
});
expect(started.isError).not.toBe(true);
expect(JSON.stringify(started.structuredContent)).not.toContain(
"synthetic-secret-token",
);
const loaded = await client.callTool({
name: "load_frida_script",
arguments: {
session_id: "00000000-0000-4000-8000-000000000001",
source_kind: "inline",
source: "send('loaded');",
},
});
expect(loaded.isError).not.toBe(true);
expect(JSON.stringify(loaded.structuredContent)).not.toContain(
"synthetic-secret-token",
);
const loadedValue = loaded.structuredContent;
if (
loadedValue === undefined ||
typeof loadedValue !== "object" ||
loadedValue === null ||
!("evidence_id" in loadedValue) ||
typeof loadedValue.evidence_id !== "string"
)
throw new Error("Expected inline Frida Evidence");
const retainedEvidence = session.evidenceById(loadedValue.evidence_id);
expect(JSON.stringify(retainedEvidence)).not.toContain(
"synthetic-secret-token",
);
for (const [name, args] of [
[
"resume_frida_session",
{ session_id: "00000000-0000-4000-8000-000000000001" },
],
[
"unload_frida_script",
{
session_id: "00000000-0000-4000-8000-000000000001",
script_id: "00000000-0000-4000-8000-000000000002",
},
],
[
"frida_session_status",
{ session_id: "00000000-0000-4000-8000-000000000001" },
],
[
"close_frida_session",
{ session_id: "00000000-0000-4000-8000-000000000001" },
],
] as const) {
const result = await client.callTool({ name, arguments: args });
expect(
result.isError,
`${name}: ${JSON.stringify(result.structuredContent)}`,
).not.toBe(true);
}
const invalidAddress = await client.callTool({
name: "list_frida_devices",
arguments: {
remote: { address: "tcp://127.0.0.1:27042?token=synthetic-secret-token" },
},
});
expect(invalidAddress.isError).toBe(true);
const oneShot = await client.callTool({
name: "instrument_with_frida",
arguments: {
mode: "attach",
pid: 10,
source_kind: "inline",
source: "send('one-shot');",
duration_ms: 0,
},
});
expect(oneShot.isError).not.toBe(true);
const oneShotContract = tools.find(
(tool) => tool.name === "instrument_with_frida",
);
if (oneShotContract?.outputSchema === undefined)
throw new Error("Missing one-shot Frida output schema");
const validateOneShot = ajv.compile(
oneShotContract.outputSchema as AnySchema,
);
expect(validateOneShot(oneShot.structuredContent)).toBe(true);
await expectFridaToolsAvailable(client);
});
it("reports Frida tools as unavailable after the optional binding fails to load", async () => {
const session = createTestBinarySession(() => {
throw new Error("Binary provider must not start");
});
const provider = new FridaInstrumentationManager({
deviceManagerLoader: async () => {
throw new Error("Cannot find package 'frida'");
},
});
const server = createServer(
{ kind: "session", session },
{ fridaInstrumentation: provider },
);
const client = new Client({ name: "frida-optional-binding", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const missing = await client.callTool({
name: "list_frida_devices",
arguments: {},
});
expect(missing.isError).toBe(true);
const inventory = await client.callTool({
name: "binary_session",
arguments: {},
});
const parsedInventory = toolContract("binary_session").outputSchema.safeParse(
inventory.structuredContent,
);
if (!parsedInventory.success)
throw new Error("Invalid binary session output");
expect(
expandToolAvailability(parsedInventory.data.result.tool_availability),
).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "list_frida_devices",
available: false,
reason: "provider_unavailable",
remediation: expect.stringContaining("Cannot find package 'frida'"),
}),
]),
);
});
it("retains cancellation Evidence after the MCP client stops waiting", async () => {
const session = createTestBinarySession(() => {
throw new Error("Binary provider must not start");
});
let finishLoad: (() => void) | undefined;
const loadGate = new Promise<void>((resolve) => {
finishLoad = resolve;
});
let markLoadStarted: (() => void) | undefined;
const loadStarted = new Promise<void>((resolve) => {
markLoadStarted = resolve;
});
let markSessionClosed: (() => void) | undefined;
const sessionClosed = new Promise<void>((resolve) => {
markSessionClosed = resolve;
});
const provider = createFridaTestProvider({
async loadScript() {
markLoadStarted?.();
await loadGate;
return {
ok: true,
value: {
scriptId: "00000000-0000-4000-8000-000000000002",
sourceKind: "inline",
sourcePath: null,
sourceSha256: "a".repeat(64),
messages: [{ type: "send", payload: "cancel-observed" }],
messagesTruncated: false,
},
};
},
status(sessionId) {
return {
sessionId,
deviceId: "remote-device",
target: "fixture",
pid: 10,
mode: "attach",
state: "running",
targetResumeObserved: false,
scripts: [],
messages: [{ type: "send", payload: "cancel-observed" }],
messagesTruncated: false,
};
},
async closeSession() {
markSessionClosed?.();
return { ok: true, value: { targetResumeObserved: false } };
},
});
const server = createServer(
{ kind: "session", session },
{ fridaInstrumentation: provider },
);
const client = new Client({ name: "frida-cancellation", version: "1" });
const controller = new AbortController();
onTestFinished(async () => {
finishLoad?.();
controller.abort();
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const call = client.callTool(
{
name: "instrument_with_frida",
arguments: {
mode: "attach",
pid: 10,
source_kind: "inline",
source: "send('cancel-observed');",
duration_ms: 1_000,
},
},
{ signal: controller.signal },
);
await loadStarted;
controller.abort(new Error("cancel Frida observation"));
finishLoad?.();
await expect(call).rejects.toThrow("cancel Frida observation");
await sessionClosed;
await client.ping();
const bundle = await client.callTool({
name: "get_evidence_bundle",
arguments: {},
});
expect(JSON.stringify(bundle.structuredContent)).toContain("cancel-observed");
expect(JSON.stringify(bundle.structuredContent)).toContain(
"instrument_with_frida",
);
});
+42
View File
@@ -141,3 +141,45 @@ it("preserves JEB provider failure reasons through the MCP boundary", async () =
expect(text).toContain("ECONNREFUSED");
expect(text).toContain("REA_JEB_MCP_URL");
});
it("keeps the MCP server usable when REA_JEB_MCP_URL is invalid", async () => {
const session = createTestBinarySession(() => {
throw new Error("deep provider must not start");
});
const server = createServer(
{ kind: "session", session },
{ environment: { REA_JEB_MCP_URL: "http://localhost:8425/mcp" } },
);
const client = new Client({ name: "jeb-invalid-endpoint", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
expect((await client.listTools()).tools.length).toBeGreaterThan(0);
const failed = await client.callTool({
name: "inspect_jeb_client",
arguments: {},
});
expect(failed.isError).toBe(true);
const text = (failed.content ?? [])
.map((block) => (block.type === "text" ? block.text : ""))
.join("");
expect(JSON.parse(text)).toMatchObject({
error: {
code: "configuration_invalid",
details: {
settings: [
{
setting: "REA_JEB_MCP_URL",
constraint: expect.stringContaining("loopback"),
},
],
},
},
});
});
+143 -1
View File
@@ -6,6 +6,7 @@ import { join } from "node:path";
import { WasmArtifactService } from "../../../src/application/wasm/WasmArtifactService.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { wasmArtifactSummaryViewResultSchema } from "../../../src/domain/analysisView/analysisView.js";
import { createHash } from "node:crypto";
import { z } from "zod";
import { createServer } from "../../../src/server/createServer.js";
@@ -33,6 +34,63 @@ const wasmToolSchemas = async (client: Client) => {
return { name: advertised.name, ajv, inputSchema, outputSchema };
};
const assertFirstSummaryDelivery = async (
harness: Awaited<ReturnType<typeof createApplicationMcpHarness>>,
value: ReturnType<typeof wasmArtifactFixture>,
inspect: WasmArtifactService["provider"]["inspect"],
) => {
const {
ajv: wasmAjv,
inputSchema,
outputSchema,
} = await wasmToolSchemas(harness.client);
const summaryInput = { path: value.artifact.path, detail: "summary" };
expect(wasmAjv.validate(inputSchema, summaryInput)).toBe(true);
expect(
wasmAjv.validate(inputSchema, { ...summaryInput, detail: "brief" }),
).toBe(false);
const directSummary = await harness.client.callTool({
name: "inspect_wasm_artifact",
arguments: summaryInput,
});
expect(directSummary.isError).not.toBe(true);
expect(
wasmAjv.validate(outputSchema, directSummary.structuredContent),
JSON.stringify(wasmAjv.errors),
).toBe(true);
const summaryEvidence = parseEvidence(directSummary.structuredContent);
const summary = wasmArtifactSummaryViewResultSchema.parse(
summaryEvidence.normalized_result,
);
expect(summaryEvidence.confidence).toBe("derived");
expect(summaryEvidence.evidence_links).toEqual([summary.parent_evidence_id]);
expect(summary.summary.wat).toMatchObject({
sha256: value.wat.sha256,
code_units: value.wat.text.length,
});
expect(summary.summary.wat).not.toHaveProperty("text");
const retained = harness.session.evidenceById(summary.parent_evidence_id);
if (retained === undefined) throw new Error("Summary lost original Evidence");
expect(retained.normalized_result).toEqual(value);
expect(retained.parameters).toEqual({
path: value.artifact.path,
glue_paths: [],
candidate_paths: [],
});
expect(inspect).toHaveBeenCalledTimes(1);
expect(inspect).toHaveBeenLastCalledWith(
retained.parameters,
expect.objectContaining({ signal: expect.any(AbortSignal) }),
);
expect(
wasmAjv.validate(outputSchema, {
...summaryEvidence,
normalized_result: { ...summary, parent_operation: "inventory_artifact" },
}),
).toBe(false);
return { summary, retained };
};
it("directs rejected native WASM opening to the advertised static tool while preserving missing-WABT diagnostics", async () => {
const directory = await createTestTempDirectory("rea-wasm-recovery-");
const path = join(
@@ -84,6 +142,16 @@ it("directs rejected native WASM opening to the advertised static tool while pre
},
},
});
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(
@@ -157,14 +225,22 @@ it("reads an oversized completed WASM result through its reported retained refer
representation: "decoded-wat" as const,
},
};
const inspect = vi.fn(() =>
Promise.resolve(ok(wasmArtifactExecution(value))),
);
const service = new WasmArtifactService({
close: () => Promise.resolve(),
inspect: () => Promise.resolve(ok(wasmArtifactExecution(value))),
inspect,
});
const harness = await createApplicationMcpHarness({
serverOptions: { wasmArtifact: service },
});
onTestFinished(harness.close);
const { summary, retained } = await assertFirstSummaryDelivery(
harness,
value,
inspect,
);
const reply = await harness.client.callTool({
name: "inspect_wasm_artifact",
arguments: { path: value.artifact.path },
@@ -182,6 +258,17 @@ it("reads an oversized completed WASM result through its reported retained refer
})
.parse(parseMcpToolError(reply).error).details
.reported_limits.evidence_reference;
expect(reference.evidence_id).toBe(summary.parent_evidence_id);
const explicitComplete = await harness.client.callTool({
name: "inspect_wasm_artifact",
arguments: { path: value.artifact.path, detail: "complete" },
});
expect(parseMcpToolError(explicitComplete)).toMatchObject({
error: {
code: "resource_constraint",
details: { reported_limits: { evidence_reference: reference } },
},
});
const catalog = await harness.client.listTools();
const advertised = catalog.tools.find(
(tool) => tool.name === "inspect_analysis_view",
@@ -244,6 +331,17 @@ it("reads an oversized completed WASM result through its reported retained refer
}
const original = harness.session.evidenceById(reference.evidence_id);
expect(original?.normalized_result).toEqual(value);
expect(original).toEqual(retained);
expect(inspect).toHaveBeenCalledTimes(3);
await harness.client.ping();
});
it("rejects inconsistent decoded-WAT digests in portable Evidence without a provider run", async () => {
const value = wasmArtifactFixture();
const harness = await createApplicationMcpHarness({
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const inconsistent = createEvidence(
{
path: value.artifact.path,
@@ -325,6 +423,50 @@ it("rejects absent or inconsistent WASM source identity before deriving portable
await harness.client.ping();
});
it("requires retention for WASM summary delivery while keeping fixed-server complete delivery", async () => {
const value = wasmArtifactFixture();
const service = new WasmArtifactService({
close: () => Promise.resolve(),
inspect: () => Promise.resolve(ok(wasmArtifactExecution(value))),
});
const session = createTestBinarySession(() => {
throw new Error("No deep provider");
});
const server = createServer(
{ kind: "fixed", analysis: session },
{ wasmArtifact: service },
);
const client = new Client({ name: "wasm-fixed-delivery", version: "1" });
const [a, b] = InMemoryTransport.createLinkedPair();
try {
await server.connect(b);
await client.connect(a);
const summary = await client.callTool({
name: "inspect_wasm_artifact",
arguments: { path: value.artifact.path, detail: "summary" },
});
expect(parseMcpToolError(summary)).toMatchObject({
error: {
code: "capability_unavailable",
message: expect.stringContaining("does not retain Evidence"),
},
});
const complete = await client.callTool({
name: "inspect_wasm_artifact",
arguments: { path: value.artifact.path },
});
expect(complete.isError).not.toBe(true);
expect(parseEvidence(complete.structuredContent).normalized_result).toEqual(
value,
);
await client.ping();
} finally {
await client.close();
await server.close();
await session.close();
}
});
it("retries cleanup of the injected WASM module after server shutdown fails", async () => {
const close = vi
.fn()
@@ -0,0 +1,61 @@
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
import { expect, it, vi } from "vitest";
import type { BrowserScenarioCapturePort } from "../../../src/application/BrowserScenarioCapturePort.js";
import { silentLogger } from "../../../src/logger.js";
import { startMcpTransport } from "../../../src/main/transport.js";
import type { RuntimeDependencies } from "../../../src/main/types.js";
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
it("keeps the shared browser scenario provider open when the SDK discards its discovery probe", async () => {
const session = createTestBinarySession(() => {
throw new Error("Unexpected deep provider");
});
const close = vi.fn(async () => undefined);
const browserScenarioCapture: BrowserScenarioCapturePort = {
identity: () => ({
id: "fake-browser",
name: "Fake browser",
version: "1",
}),
captureScenario: async () => {
throw new Error("Unexpected scenario capture");
},
close,
};
const factories: Parameters<RuntimeDependencies["serve"]>[0][] = [];
const runtime: RuntimeDependencies = {
env: {},
serve: (factory) => {
factories.push(factory);
return { close: async () => undefined };
},
writeStderr: () => undefined,
setExitCode: () => undefined,
registerShutdown: () => () => undefined,
};
const transport = await startMcpTransport(runtime, session, {
logger: silentLogger,
serverLogger: silentLogger,
environment: runtime.env,
delivery: new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE),
loadOptionalProviders: async () => ({ browserScenarioCapture }),
});
if (!transport.ok) throw new Error("Transport failed");
const factory = factories[0];
if (factory === undefined) throw new Error("Missing SDK server factory");
try {
const probe = await factory({ era: "modern" });
await probe.close();
const replacement = await factory({ era: "legacy" });
await replacement.close();
expect(close).not.toHaveBeenCalled();
await transport.closeOptionalProviders();
expect(close).toHaveBeenCalledTimes(1);
} finally {
await transport.closeAndroid();
await session.close();
}
});
@@ -70,4 +70,5 @@ const universalTarget = (path: string): BinaryTarget => ({
format: "mach-o-universal",
architecture: "arm64",
availableArchitectures: ["arm64"],
universalSlice: { offset: 0, size: 32 },
});