chore: merge main into feat/dylib-resolution
Resolve conflicts against main: - README.md: take main's simplified English README, which no longer has the tool-family table. - README_ja.md: take main's reworded table and count trace_dylib_resolution in the artifact graph row (5 -> 6). - Skill: the references gain the trace_dylib_resolution paragraph, so the version moves to 29 (main already uses 28). - Regenerate the product catalog, conformance manifest, skill digest and package metadata (135 tools). The MCP tool catalog is now built rather than committed (#997), so it is removed here. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { expect, it as test, onTestFinished } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { access } from "node:fs/promises";
|
||||
import { ANDROID_TOOL_CONTRACTS } from "../../../src/contracts/android/androidToolContracts.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
@@ -92,8 +94,15 @@ it("publishes and executes all APK contracts with inline Evidence and no active
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const advertised = await client.listTools();
|
||||
const wireTools = new Map(advertised.tools.map((tool) => [tool.name, tool]));
|
||||
for (const contract of ANDROID_TOOL_CONTRACTS) {
|
||||
const wire = advertised.tools.find((tool) => tool.name === contract.name);
|
||||
const wire = wireTools.get(contract.name);
|
||||
if (wire === undefined || wire.outputSchema === undefined)
|
||||
throw new Error(`Missing advertised output schema for ${contract.name}`);
|
||||
const validateOutput = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
}).compile(z.record(z.string(), z.unknown()).parse(wire.outputSchema));
|
||||
expect(wire?.annotations).toMatchObject(contract.annotations);
|
||||
expect(contract.effects).toMatchObject({
|
||||
mutatesTarget: false,
|
||||
@@ -120,6 +129,7 @@ it("publishes and executes all APK contracts with inline Evidence and no active
|
||||
arguments: input,
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
expect(validateOutput(response.structuredContent)).toBe(true);
|
||||
const result = contract.outputSchema.parse(response.structuredContent);
|
||||
const evidence = parseEvidence(result.evidence);
|
||||
expect(result.result).toEqual(evidence.normalized_result);
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import { createBinarySession } from "../../../src/composition/binary.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { artifactInspectionResultSchema } from "../../../src/domain/artifactInspection.js";
|
||||
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
|
||||
import {
|
||||
artifactParentPaths,
|
||||
writeOrderedZip,
|
||||
} from "../../fixtures/artifactEntryOrder.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it("returns correct child-first ZIP containment through MCP inspection", async () => {
|
||||
const root = await createTestTempDirectory("rea-entry-order-mcp-");
|
||||
const archive = join(root, "child-first.zip");
|
||||
await writeOrderedZip(archive, ["pkg/sub/data.txt", "pkg/sub/", "pkg/"]);
|
||||
const configured = parseConfig({});
|
||||
if (!configured.ok) throw configured.error;
|
||||
const session = createBinarySession(configured.value);
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "entry-order-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: archive },
|
||||
})
|
||||
).isError,
|
||||
).not.toBe(true);
|
||||
const called = await client.callTool({
|
||||
name: "inspect_artifact",
|
||||
arguments: {},
|
||||
});
|
||||
expect(called.isError, JSON.stringify(called.structuredContent)).not.toBe(
|
||||
true,
|
||||
);
|
||||
const inspection = artifactInspectionResultSchema.parse(
|
||||
z.object({ result: z.unknown() }).parse(called.structuredContent).result,
|
||||
);
|
||||
const substep = inspection.substeps[0];
|
||||
if (substep === undefined) throw new Error("Missing inventory Evidence");
|
||||
const inventory = artifactInventoryResultSchema.parse(
|
||||
substep.evidence.normalized_result,
|
||||
);
|
||||
expect(artifactParentPaths(inventory)).toEqual({
|
||||
".": null,
|
||||
pkg: ".",
|
||||
"pkg/sub": "pkg",
|
||||
"pkg/sub/data.txt": "pkg/sub",
|
||||
});
|
||||
expect(inspection.coverage.status).toBe("complete-within-substeps");
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
@@ -5,8 +5,6 @@ import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import { createBinarySession } from "../../../src/composition/binary.js";
|
||||
import { keyedArchiveResultSchema } from "../../../src/domain/apple/keyedArchive.js";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
@@ -71,25 +69,19 @@ it("inspects a standalone keyed archive through MCP with original object identit
|
||||
}
|
||||
});
|
||||
|
||||
it("returns every artifact occurrence in one MCP call", async () => {
|
||||
it("returns all 520 ZIP file occurrences in one inspect_artifact MCP result", async () => {
|
||||
const directory = await createTestTempDirectory("rea-artifact-inline-");
|
||||
const archive = join(directory, "many.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
const fileCount = 520;
|
||||
for (let index = 0; index < fileCount; index += 1) {
|
||||
for (let index = 0; index < fileCount; index += 1)
|
||||
await writer.add(
|
||||
`files/${String(index)}.txt`,
|
||||
new TextReader(`file-${String(index)}`),
|
||||
);
|
||||
}
|
||||
await writeFile(archive, await writer.close());
|
||||
|
||||
const configured = parseConfig({
|
||||
HOPPER_LAUNCHER_PATH: "/rea-unconfigured-deep-provider/hopper",
|
||||
});
|
||||
expect(configured.ok).toBe(true);
|
||||
if (!configured.ok) throw configured.error;
|
||||
const session = createBinarySession(configured.value);
|
||||
const session = createTestBinarySession(new ArtifactProvider());
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "artifact-inline-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
@@ -102,43 +94,6 @@ it("returns every artifact occurrence in one MCP call", async () => {
|
||||
arguments: { path: archive },
|
||||
});
|
||||
expect(opened.isError).not.toBe(true);
|
||||
const names = (await client.listTools()).tools.map(({ name }) => name);
|
||||
expect(names).toContain("inspect_artifact");
|
||||
expect(names).toContain("inspect_asset_catalog");
|
||||
expect(names).not.toContain("inventory_artifact");
|
||||
const status = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {},
|
||||
});
|
||||
expect(status.isError).not.toBe(true);
|
||||
const capabilities = z
|
||||
.object({
|
||||
result: z.object({
|
||||
capabilities: z.array(
|
||||
z.object({
|
||||
operation: z.string(),
|
||||
available: z.boolean(),
|
||||
reason: z.string().nullable(),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
})
|
||||
.parse(status.structuredContent).result.capabilities;
|
||||
expect(capabilities.map(({ operation }) => operation)).not.toContain(
|
||||
"inventory_artifact",
|
||||
);
|
||||
expect(
|
||||
capabilities.find(
|
||||
({ operation }) => operation === "inspect_asset_catalog",
|
||||
),
|
||||
).toMatchObject(
|
||||
process.platform === "darwin"
|
||||
? { available: true, reason: null }
|
||||
: {
|
||||
available: false,
|
||||
reason: "Apple asset catalogs require macOS assetutil.",
|
||||
},
|
||||
);
|
||||
const result = await client.callTool({
|
||||
name: "inspect_artifact",
|
||||
arguments: {},
|
||||
@@ -157,23 +112,14 @@ it("returns every artifact occurrence in one MCP call", async () => {
|
||||
}),
|
||||
}),
|
||||
),
|
||||
observations: z.array(z.unknown()),
|
||||
derived_relationships: z.array(z.unknown()),
|
||||
hypotheses: z.array(z.unknown()),
|
||||
unexplored_branches: z.array(z.unknown()),
|
||||
next_probes: z.array(z.unknown()),
|
||||
})
|
||||
.parse(
|
||||
z.object({ result: z.unknown() }).parse(result.structuredContent)
|
||||
.result,
|
||||
);
|
||||
const occurrences =
|
||||
inspection.substeps[0]?.evidence.normalized_result.occurrences;
|
||||
if (occurrences === undefined)
|
||||
throw new Error("inspection omitted the artifact inventory");
|
||||
expect(occurrences).toHaveLength(fileCount + 1);
|
||||
expect(inspection.observations.length).toBeGreaterThan(0);
|
||||
expect(inspection.derived_relationships.length).toBeGreaterThan(0);
|
||||
expect(
|
||||
inspection.substeps[0]?.evidence.normalized_result.occurrences,
|
||||
).toHaveLength(fileCount + 1);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { z } from "zod";
|
||||
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { webPageInspectionSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "../../../src/contracts/javascript/javascriptRuntimeReconciliationExample.js";
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
@@ -190,6 +191,40 @@ const verifySessionAndComparisonTools = async (
|
||||
expect(compared.structuredContent).toMatchObject({
|
||||
result: { overall_status: "unknown" },
|
||||
});
|
||||
const parsedCapture = webPageInspectionSchema.parse(capture);
|
||||
const socket = parsedCapture.network.websocket_events.find(
|
||||
(event) => event.payload_shape?.json_shape != null,
|
||||
);
|
||||
const payload = socket?.payload_shape;
|
||||
if (socket === undefined || payload == null || payload.json_shape === null)
|
||||
throw new Error("Missing deep WebSocket JSON shape fixture");
|
||||
const malformedCapture = {
|
||||
...parsedCapture,
|
||||
network: {
|
||||
...parsedCapture.network,
|
||||
websocket_events: [
|
||||
{
|
||||
...socket,
|
||||
payload_shape: {
|
||||
...payload,
|
||||
json_shape: {
|
||||
...payload.json_shape,
|
||||
properties: [{ path: "/event", types: [42], observations: 1 }],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const malformedComparison = await connected.client.callTool({
|
||||
name: "compare_web_captures",
|
||||
arguments: {
|
||||
before: { inspection: malformedCapture },
|
||||
after: { inspection: capture },
|
||||
},
|
||||
});
|
||||
expect(malformedComparison.isError).toBe(true);
|
||||
expect(JSON.stringify(malformedComparison.content)).toContain("types");
|
||||
const incompleteComparison = await connected.client.callTool({
|
||||
name: "compare_web_captures",
|
||||
arguments: { before: { inspection: capture } },
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { describe, expect } 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", () => {
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import type { ElectronActiveObservationPort } from "../../../src/application/javascript/ElectronActiveObservationPort.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
|
||||
import { CdpElectronProvider } from "../../../src/browser/CdpElectronProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
@@ -270,12 +271,18 @@ it("exposes the target-free static JavaScript application workflow", async () =>
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const analyzed = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: { input_path: root },
|
||||
});
|
||||
const progress: number[] = [];
|
||||
const analyzed = await client.callTool(
|
||||
{
|
||||
name: "analyze_javascript_application",
|
||||
arguments: { input_path: root },
|
||||
},
|
||||
{ onprogress: (update) => progress.push(update.progress) },
|
||||
);
|
||||
|
||||
expect(analyzed.isError).not.toBe(true);
|
||||
expect(progress[0]).toBe(0);
|
||||
expect(progress.at(-1)).toBe(1);
|
||||
const projected = z
|
||||
.object({
|
||||
evidence_id: z.string(),
|
||||
@@ -314,6 +321,9 @@ it("exposes the target-free static JavaScript application workflow", async () =>
|
||||
expect(projected.result.graph.nodes.length).toBeGreaterThan(0);
|
||||
expect(projected.result.semantic_graph.nodes.length).toBeGreaterThan(0);
|
||||
expect(projected.evidence.operation).toBe("analyze_javascript_application");
|
||||
const direct = await analyzeJavaScriptApplication({ input_path: root });
|
||||
if (!direct.ok) throw direct.error;
|
||||
expect(projected.evidence_id).toBe(direct.value.evidence_id);
|
||||
});
|
||||
|
||||
const evidenceFor = (value: unknown) => {
|
||||
|
||||
+33
-144
@@ -1,123 +1,18 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { PROCEDURES, inventory } from "./enhancedToolsHarness.js";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { functionDossierSchema } from "../../../src/domain/hopperValues.js";
|
||||
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { closeEnhancedToolResources, connect } from "./enhancedToolsHarness.js";
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(inventory(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
inventory({
|
||||
"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(inventory({ "0x30": "hello" })));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
procedure: {
|
||||
address: "0x1",
|
||||
name: "entry",
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: "return 0;",
|
||||
assembly: [],
|
||||
comments: [],
|
||||
callers: [],
|
||||
callees: [],
|
||||
incoming_references: [],
|
||||
outgoing_references: [],
|
||||
referenced_strings: [],
|
||||
referenced_names: [],
|
||||
basic_blocks: [],
|
||||
}),
|
||||
);
|
||||
default:
|
||||
return Promise.resolve(ok(null));
|
||||
}
|
||||
},
|
||||
});
|
||||
afterEach(closeEnhancedToolResources);
|
||||
|
||||
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 () => {
|
||||
describe("analyze_function MCP producer validation", () => {
|
||||
it("rejects an incomplete function dossier", async () => {
|
||||
const client = await connect({
|
||||
execute: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
observed({
|
||||
procedure: { address: "0x1", name: "entry" },
|
||||
pseudocode: { text: "plausible but incomplete" },
|
||||
}),
|
||||
@@ -127,46 +22,40 @@ describe("enhanced MCP tools", () => {
|
||||
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),
|
||||
);
|
||||
expect(result.content).toContainEqual({
|
||||
type: "text",
|
||||
text: JSON.stringify(result.structuredContent),
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects deceptive function dossier collection metadata", async () => {
|
||||
const malformedPort = fixturePort();
|
||||
it("rejects a malformed collection in an otherwise complete dossier", async () => {
|
||||
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
|
||||
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,
|
||||
},
|
||||
});
|
||||
},
|
||||
execute: () =>
|
||||
Promise.resolve(
|
||||
observed({
|
||||
...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),
|
||||
);
|
||||
expect(result.content).toContainEqual({
|
||||
type: "text",
|
||||
text: JSON.stringify(result.structuredContent),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,7 +12,18 @@ afterEach(closeEnhancedToolResources);
|
||||
|
||||
describe("enhanced MCP tools", () => {
|
||||
it("returns Evidence IDs and a complete call path", async () => {
|
||||
const client = await connect();
|
||||
const client = await connect({
|
||||
execute: async (_name, arguments_) => {
|
||||
const procedure = arguments_.procedure;
|
||||
return ok(
|
||||
procedure === "0x1"
|
||||
? ["0x2", "0x3"]
|
||||
: procedure === "0x2"
|
||||
? ["0x1"]
|
||||
: [],
|
||||
);
|
||||
},
|
||||
});
|
||||
const result = await client.callTool({
|
||||
name: "trace_call_path",
|
||||
arguments: {
|
||||
|
||||
@@ -1,136 +1,13 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { PROCEDURES, emptyBounded, inventory } from "./enhancedToolsHarness.js";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { closeEnhancedToolResources, connect } from "./enhancedToolsHarness.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(inventory(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
inventory({
|
||||
"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(inventory({ "0x30": "hello" })));
|
||||
case "search_strings":
|
||||
case "search_procedures":
|
||||
return Promise.resolve(ok(inventory({ "0x1": "needle" })));
|
||||
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 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;
|
||||
};
|
||||
afterEach(closeEnhancedToolResources);
|
||||
|
||||
describe("enhanced MCP input validation", () => {
|
||||
it("lets the SDK reject misspelled tool inputs", async () => {
|
||||
const client = await connect();
|
||||
const client = await connect({ execute: () => Promise.resolve(ok([])) });
|
||||
const valid = await client.callTool({
|
||||
name: "trace_feature",
|
||||
arguments: { query: "needle" },
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
export const PROCEDURES = {
|
||||
"0x1": "_TtC7Fixture5Class",
|
||||
@@ -20,119 +19,9 @@ export const PROCEDURES = {
|
||||
export const inventory = (values: Readonly<Record<string, string>>) =>
|
||||
Object.entries(values).map(([address, value]) => ({ address, value }));
|
||||
|
||||
export const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(inventory(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
inventory({
|
||||
"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(inventory({ "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));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
export const emptyBounded = () => ({
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
});
|
||||
|
||||
export const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
export const connect = async (
|
||||
analysis: AnalysisOperationPort = fixturePort(),
|
||||
) => {
|
||||
export const connect = async (analysis: AnalysisOperationPort) => {
|
||||
const server = createServer(analysis);
|
||||
const client = new Client({ name: "enhanced-test", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
|
||||
@@ -124,28 +124,6 @@ describe("MCP runtime errors", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("starts the core transport when optional providers fail to load", async () => {
|
||||
const output: string[] = [];
|
||||
let serveCalls = 0;
|
||||
expect(
|
||||
await run(
|
||||
dependencies({
|
||||
serve: () => {
|
||||
serveCalls += 1;
|
||||
return { close: () => Promise.resolve() };
|
||||
},
|
||||
output,
|
||||
shutdown: [],
|
||||
exitCodes: [],
|
||||
loadOptionalProviders: () =>
|
||||
Promise.reject(new Error("synthetic optional import failure")),
|
||||
}),
|
||||
),
|
||||
).toBe(0);
|
||||
expect(serveCalls).toBe(1);
|
||||
expect(output).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports shutdown failure and sets a failing exit code", async () => {
|
||||
const output: string[] = [];
|
||||
const shutdown: Array<() => void> = [];
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { RuntimeDependencies } from "../../../src/main/types.js";
|
||||
import { createRuntimeState } from "../../../src/main/state.js";
|
||||
|
||||
describe("runtime configuration reload", () => {
|
||||
it("applies a valid configuration reload", () => {
|
||||
it("applies valid reloads and keeps the last valid config after an invalid reload", () => {
|
||||
const env: NodeJS.ProcessEnv = { REA_LOG_LEVEL: "info" };
|
||||
const runtime = setupReload(env);
|
||||
|
||||
@@ -16,16 +16,11 @@ describe("runtime configuration reload", () => {
|
||||
runtime.reload();
|
||||
|
||||
expect(runtime.state.currentConfig.logLevel).toBe("debug");
|
||||
});
|
||||
|
||||
it("retains the last valid configuration after an invalid reload", () => {
|
||||
const env: NodeJS.ProcessEnv = { REA_LOG_LEVEL: "info" };
|
||||
const runtime = setupReload(env);
|
||||
|
||||
env.REA_LOG_LEVEL = "invalid";
|
||||
runtime.reload();
|
||||
|
||||
expect(runtime.state.currentConfig.logLevel).toBe("info");
|
||||
expect(runtime.state.currentConfig.logLevel).toBe("debug");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -14,16 +15,21 @@ import type { BinarySession } from "../../../src/application/binary/BinarySessio
|
||||
import type { BinaryTarget } from "../../../src/domain/binaryTarget.js";
|
||||
import { SessionProviderRouter } from "../../../src/application/binary/SessionProviderRouter.js";
|
||||
import { MANAGED_NATIVE_VERIFICATION_EXAMPLE } from "../../../src/contracts/managed/managedWorkflowExamples.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { ManagedStaticProvider } from "../../../src/dotnet/ManagedStaticProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { buildManagedPeFixture } from "../../../src/dotnet/ManagedPe.fixture.js";
|
||||
|
||||
type ManagedOutputAssertion = Awaited<ReturnType<typeof createOutputAssertion>>;
|
||||
|
||||
it("runs every managed static inspection independently of an active native target", async () => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-managed-independent-mcp-",
|
||||
);
|
||||
const path = join(directory, "fixture.dll");
|
||||
const otherPath = join(directory, "other-fixture.dll");
|
||||
await writeFile(path, buildManagedPeFixture());
|
||||
await writeFile(otherPath, buildManagedPeFixture({ methodName: "Other" }));
|
||||
const session = composeBinarySession(
|
||||
SessionProviderRouter.selectable(new AnalysisProviderRegistry([]), [
|
||||
new ManagedStaticProvider(),
|
||||
@@ -50,6 +56,12 @@ it("runs every managed static inspection independently of an active native targe
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const managedMembersTool = (await client.listTools()).tools.find(
|
||||
({ name }) => name === "inspect_managed_members",
|
||||
);
|
||||
expect(managedMembersTool?.inputSchema).toMatchObject({
|
||||
additionalProperties: false,
|
||||
});
|
||||
const artifact = structured(
|
||||
await client.callTool({
|
||||
name: "inspect_managed_artifact",
|
||||
@@ -63,6 +75,11 @@ it("runs every managed static inspection independently of an active native targe
|
||||
subject: { local_path: path, format: "pe" },
|
||||
},
|
||||
});
|
||||
const misspelledPath = await client.callTool({
|
||||
name: "inspect_managed_members",
|
||||
arguments: { pth: otherPath },
|
||||
});
|
||||
expect(misspelledPath.isError).toBe(true);
|
||||
const invalidSelection = await client.callTool({
|
||||
name: "inspect_managed_artifact",
|
||||
arguments: { path: join(directory, "missing.dll") },
|
||||
@@ -78,6 +95,24 @@ it("runs every managed static inspection independently of an active native targe
|
||||
subject: { local_path: path, format: "pe" },
|
||||
},
|
||||
});
|
||||
const otherArtifact = structured(
|
||||
await client.callTool({
|
||||
name: "inspect_managed_artifact",
|
||||
arguments: { path: otherPath },
|
||||
}),
|
||||
);
|
||||
expect(otherArtifact).toMatchObject({
|
||||
evidence: { subject: { local_path: otherPath, format: "pe" } },
|
||||
});
|
||||
const reusedOtherTarget = structured(
|
||||
await client.callTool({ name: "inspect_managed_members", arguments: {} }),
|
||||
);
|
||||
expect(reusedOtherTarget).toMatchObject({
|
||||
evidence: {
|
||||
operation: "inspect_managed_members",
|
||||
subject: { local_path: otherPath, format: "pe" },
|
||||
},
|
||||
});
|
||||
const boundaries = structured(
|
||||
await client.callTool({
|
||||
name: "inspect_managed_native_boundaries",
|
||||
@@ -126,9 +161,19 @@ it("opens a managed PE and executes the managed static provider through MCP", as
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
await verifyManagedCatalogAndNativeWorkflow(client, session);
|
||||
const members = await inspectManagedStaticWorkflow(client, path);
|
||||
await verifyManagedComparisonAndReconstruction(client, members, rightPath);
|
||||
const assertOutput = await createOutputAssertion(client);
|
||||
await verifyManagedCatalogAndNativeWorkflow(client, session, assertOutput);
|
||||
const members = await inspectManagedStaticWorkflow(
|
||||
client,
|
||||
path,
|
||||
assertOutput,
|
||||
);
|
||||
await verifyManagedComparisonAndReconstruction(
|
||||
client,
|
||||
members,
|
||||
rightPath,
|
||||
assertOutput,
|
||||
);
|
||||
} finally {
|
||||
await Promise.all([client.close(), server.close()]);
|
||||
await session.close();
|
||||
@@ -138,9 +183,9 @@ it("opens a managed PE and executes the managed static provider through MCP", as
|
||||
const verifyManagedCatalogAndNativeWorkflow = async (
|
||||
client: Client,
|
||||
session: BinarySession,
|
||||
outputAssertion: ManagedOutputAssertion,
|
||||
): Promise<void> => {
|
||||
const names = (await client.listTools()).tools.map(({ name }) => name);
|
||||
expect(names).toEqual(
|
||||
expect(outputAssertion.names).toEqual(
|
||||
expect.arrayContaining([
|
||||
"inspect_managed_artifact",
|
||||
"inspect_managed_members",
|
||||
@@ -166,6 +211,7 @@ const verifyManagedCatalogAndNativeWorkflow = async (
|
||||
},
|
||||
}),
|
||||
);
|
||||
await outputAssertion.assert("verify_managed_native_boundaries", verified);
|
||||
expect(verified).toMatchObject({
|
||||
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
|
||||
result: {
|
||||
@@ -195,6 +241,7 @@ const verifyManagedCatalogAndNativeWorkflow = async (
|
||||
const inspectManagedStaticWorkflow = async (
|
||||
client: Client,
|
||||
path: string,
|
||||
outputAssertion: ManagedOutputAssertion,
|
||||
): Promise<Record<string, unknown>> => {
|
||||
const inspected = structured(
|
||||
await client.callTool({
|
||||
@@ -202,6 +249,7 @@ const inspectManagedStaticWorkflow = async (
|
||||
arguments: { path },
|
||||
}),
|
||||
);
|
||||
await outputAssertion.assert("inspect_managed_artifact", inspected);
|
||||
expect(inspected).toMatchObject({
|
||||
result: {
|
||||
classification: { status: "managed", runtime_family: "modern-dotnet" },
|
||||
@@ -221,6 +269,11 @@ const inspectManagedStaticWorkflow = async (
|
||||
}),
|
||||
),
|
||||
);
|
||||
await outputAssertion.assert("inspect_managed_members", {
|
||||
result: members.normalized_result,
|
||||
evidence_id: members.evidence_id,
|
||||
evidence: members,
|
||||
});
|
||||
expect(members).toMatchObject({
|
||||
operation: "inspect_managed_members",
|
||||
provider: { id: "rea-dotnet-static" },
|
||||
@@ -242,6 +295,7 @@ const inspectManagedStaticWorkflow = async (
|
||||
arguments: { path },
|
||||
}),
|
||||
);
|
||||
await outputAssertion.assert("inspect_managed_native_boundaries", boundaries);
|
||||
expect(boundaries).toMatchObject({
|
||||
result: {
|
||||
identity_scope: { token_identity: "build-local" },
|
||||
@@ -292,6 +346,7 @@ const verifyManagedComparisonAndReconstruction = async (
|
||||
client: Client,
|
||||
members: Record<string, unknown>,
|
||||
rightPath: string,
|
||||
outputAssertion: ManagedOutputAssertion,
|
||||
): Promise<void> => {
|
||||
await client.callTool({
|
||||
name: "open_binary",
|
||||
@@ -316,6 +371,11 @@ const verifyManagedComparisonAndReconstruction = async (
|
||||
}),
|
||||
),
|
||||
);
|
||||
await outputAssertion.assert("compare_managed_members", {
|
||||
result: compared.normalized_result,
|
||||
evidence_id: compared.evidence_id,
|
||||
evidence: compared,
|
||||
});
|
||||
expect(compared).toMatchObject({
|
||||
operation: "compare_managed_members",
|
||||
provider: { id: "rea-dotnet-workflows" },
|
||||
@@ -394,6 +454,31 @@ const structured = (result: CallToolResult): Record<string, unknown> => {
|
||||
return z.record(z.string(), z.unknown()).parse(result.structuredContent);
|
||||
};
|
||||
|
||||
const createOutputAssertion = async (client: Client) => {
|
||||
const tools = (await client.listTools()).tools;
|
||||
const ajv = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
});
|
||||
return {
|
||||
names: tools.map(({ name }) => name),
|
||||
assert: (
|
||||
name: Parameters<typeof toolContract>[0],
|
||||
output: Record<string, unknown>,
|
||||
): void => {
|
||||
const contract = toolContract(name);
|
||||
const wire = tools.find((tool) => tool.name === name);
|
||||
if (wire?.outputSchema === undefined)
|
||||
throw new Error(`Missing advertised output schema for ${name}`);
|
||||
const valid = ajv.compile(
|
||||
z.record(z.string(), z.unknown()).parse(wire.outputSchema),
|
||||
);
|
||||
expect(valid(output), `${name} advertised output`).toBe(true);
|
||||
expect(contract.outputSchema.safeParse(output).success).toBe(true);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const inlineEvidence = (
|
||||
value: Readonly<Record<string, unknown>>,
|
||||
): Record<string, unknown> => {
|
||||
|
||||
@@ -1,25 +1,11 @@
|
||||
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.doctorDeadlineMs).toBeGreaterThanOrEqual(
|
||||
codexTimeoutMs,
|
||||
);
|
||||
});
|
||||
|
||||
it("parses Linux resident memory without accepting other fields", () => {
|
||||
expect(
|
||||
parseLinuxVmRssBytes("Name:\tnode\nVmRSS:\t 12345 kB\nThreads:\t7\n"),
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "../../../src/contracts/native/nativeToolContracts.js";
|
||||
import type { JsonValue } from "../../../src/domain/jsonValue.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
|
||||
const provider = {
|
||||
id: "fixture-native",
|
||||
name: "Fixture native provider",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
const plistResult = {
|
||||
format: "xml",
|
||||
value: {},
|
||||
bundle: {
|
||||
identifier: null,
|
||||
executable: null,
|
||||
name: null,
|
||||
version: null,
|
||||
short_version: null,
|
||||
},
|
||||
source_path: "/Applications/Fixture.app/Contents/Info.plist",
|
||||
provenance: [],
|
||||
limitations: [],
|
||||
};
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
const connect = async (
|
||||
execute: AnalysisOperationPort["execute"],
|
||||
): Promise<Client> => {
|
||||
const server = createServer({ execute });
|
||||
const client = new Client({ name: "native-contract-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return client;
|
||||
};
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
);
|
||||
});
|
||||
|
||||
describe("native MCP input contracts", () => {
|
||||
it("rejects a misspelled plist path before dispatch and preserves omission", async () => {
|
||||
const calls: Array<{
|
||||
readonly operation: string;
|
||||
readonly parameters: Readonly<Record<string, JsonValue>>;
|
||||
}> = [];
|
||||
const client = await connect((operation, parameters) => {
|
||||
calls.push({ operation, parameters });
|
||||
return Promise.resolve(
|
||||
ok(createAnalysisExecution(plistResult, provider)),
|
||||
);
|
||||
});
|
||||
|
||||
const tools = new Map(
|
||||
(await client.listTools()).tools.map((tool) => [tool.name, tool]),
|
||||
);
|
||||
for (const nativeContract of NATIVE_TOOL_CONTRACTS)
|
||||
expect(tools.get(nativeContract.name)?.inputSchema).toHaveProperty(
|
||||
"additionalProperties",
|
||||
false,
|
||||
);
|
||||
|
||||
const contract = NATIVE_TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "inspect_plist",
|
||||
);
|
||||
const advertised = tools.get("inspect_plist");
|
||||
if (contract === undefined || advertised === undefined)
|
||||
throw new Error("inspect_plist was not registered");
|
||||
|
||||
const validate = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
}).compile(advertised.inputSchema);
|
||||
const typoInput = { pth: "/tmp/Other.plist" };
|
||||
expect(validate(typoInput)).toBe(false);
|
||||
expect(contract.inputSchema.safeParse(typoInput).success).toBe(false);
|
||||
expect(validate({})).toBe(true);
|
||||
expect(contract.inputSchema.safeParse({}).success).toBe(true);
|
||||
|
||||
const defaulted = await client.callTool({
|
||||
name: "inspect_plist",
|
||||
arguments: {},
|
||||
});
|
||||
expect(defaulted.isError).not.toBe(true);
|
||||
expect(calls[0]).toEqual({ operation: "inspect_plist", parameters: {} });
|
||||
|
||||
const selectedPath = "/tmp/Other.plist";
|
||||
const explicit = await client.callTool({
|
||||
name: "inspect_plist",
|
||||
arguments: { path: selectedPath },
|
||||
});
|
||||
expect(explicit.isError).not.toBe(true);
|
||||
expect(calls[1]).toEqual({
|
||||
operation: "inspect_plist",
|
||||
parameters: { path: selectedPath },
|
||||
});
|
||||
|
||||
const beforeTypo = calls.length;
|
||||
const rejected = await client.callTool({
|
||||
name: "inspect_plist",
|
||||
arguments: typoInput,
|
||||
});
|
||||
expect(rejected.isError).toBe(true);
|
||||
expect(calls).toHaveLength(beforeTypo);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import { functionDossierSchema } from "../../../src/domain/hopperValues.js";
|
||||
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
@@ -11,52 +10,6 @@ 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>>>
|
||||
> = {
|
||||
annotate_native_function: { procedure: "0x1000", name: "entry" },
|
||||
inspect_native_load_image: {},
|
||||
address_name: {},
|
||||
inspect_native_instruction: { address: "0x1000" },
|
||||
resolve_native_call_targets: { address: "0x1000" },
|
||||
inspect_native_data_type: { type: "/Missing" },
|
||||
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>>;
|
||||
@@ -128,204 +81,54 @@ const connect = async (analysis: AnalysisOperationPort) => {
|
||||
return client;
|
||||
};
|
||||
|
||||
const inventory: JsonValue = [];
|
||||
|
||||
const outputFor = (name: string): JsonValue => {
|
||||
if (name === "annotate_native_function") {
|
||||
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
|
||||
return {
|
||||
annotations: {
|
||||
address: dossier.procedure.address,
|
||||
name: dossier.procedure.name,
|
||||
comment: null,
|
||||
inline_comment: null,
|
||||
},
|
||||
dossier,
|
||||
effects: {
|
||||
scope: "session-analysis-database",
|
||||
source_bytes_modified: false,
|
||||
persists_after_close: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (name === "inspect_native_load_image")
|
||||
return {
|
||||
status: "unsupported",
|
||||
reason: "Fixture provider has no load-image verifier",
|
||||
observations: {
|
||||
executable_format: "ELF",
|
||||
language_id: "x86:LE:64:default",
|
||||
compiler_spec_id: "gcc",
|
||||
image_base: "0x0",
|
||||
default_address_space: "ram",
|
||||
source_files: [],
|
||||
mappings: [],
|
||||
relocations: [],
|
||||
entry_context: [],
|
||||
entry_points: [],
|
||||
},
|
||||
limitations: ["Transport fixture only"],
|
||||
};
|
||||
if (name === "inspect_native_instruction")
|
||||
return {
|
||||
address: "0x1000",
|
||||
status: "decoded",
|
||||
procedure: "0x1000",
|
||||
architecture: "x86:LE:64:default",
|
||||
mode: "default",
|
||||
bytes: "c3",
|
||||
length: 1,
|
||||
mnemonic: "RET",
|
||||
raw_disassembly: "RET",
|
||||
operands: [],
|
||||
flow: {
|
||||
kind: "terminal",
|
||||
conditional: false,
|
||||
computed: false,
|
||||
direct_destinations: [],
|
||||
},
|
||||
references: [],
|
||||
limitations: ["Provider decoder observation"],
|
||||
};
|
||||
if (name === "resolve_native_call_targets")
|
||||
return {
|
||||
call_site: "0x1000",
|
||||
procedure: "0x1000",
|
||||
status: "not-call",
|
||||
mechanism: "unavailable",
|
||||
targets: [],
|
||||
limitations: [],
|
||||
};
|
||||
if (name === "inspect_native_data_type")
|
||||
return {
|
||||
status: "unavailable",
|
||||
reason: "Type absent",
|
||||
id: null,
|
||||
name: null,
|
||||
kind: "unavailable",
|
||||
source: "analysis-database",
|
||||
source_archive: null,
|
||||
address: null,
|
||||
size_bytes: null,
|
||||
alignment_bytes: null,
|
||||
packing_enabled: null,
|
||||
referenced_type: null,
|
||||
array_count: null,
|
||||
array_stride_bytes: null,
|
||||
fields: [],
|
||||
members: [],
|
||||
total_fields: 0,
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
};
|
||||
if (["list_procedures", "list_names", "list_strings"].includes(name))
|
||||
return inventory;
|
||||
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 inventory;
|
||||
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: ["0x1000: ret"],
|
||||
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: [],
|
||||
};
|
||||
return name.includes("address") ? "0x1000" : "fixture";
|
||||
};
|
||||
|
||||
describe("official Hopper proxy tools", () => {
|
||||
it("executes every handler and projects omitted Python optionals to null", async () => {
|
||||
describe("official tool input contracts", () => {
|
||||
it("rejects misspelled top-level inputs before dispatch and keeps record keys open", async () => {
|
||||
const invocations: Invocation[] = [];
|
||||
const client = await connect({
|
||||
execute: (name, arguments_) => {
|
||||
invocations.push({ name, arguments_ });
|
||||
return Promise.resolve(ok(outputFor(name)));
|
||||
return Promise.resolve(ok(null));
|
||||
},
|
||||
});
|
||||
|
||||
const { tools } = await client.listTools();
|
||||
const advertisedByName = new Map(tools.map((tool) => [tool.name, tool]));
|
||||
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(advertisedByName.get(contract.name)?.inputSchema).toHaveProperty(
|
||||
"additionalProperties",
|
||||
false,
|
||||
);
|
||||
}
|
||||
const advertised = tools.find(({ name }) => name === "address_name");
|
||||
const recordTool = tools.find(({ name }) => name === "set_addresses_names");
|
||||
if (advertised === undefined || recordTool === undefined)
|
||||
throw new Error("Official tools were not advertised");
|
||||
|
||||
expect(
|
||||
invocations.find(({ name }) => name === "annotate_native_function")
|
||||
?.arguments_,
|
||||
).toEqual({ procedure: "0x1000", name: "entry" });
|
||||
expect(invocations.map(({ name }) => name)).toEqual(
|
||||
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
const validateAddressName = ajv.compile(advertised.inputSchema);
|
||||
const validateRecordInput = ajv.compile(recordTool.inputSchema);
|
||||
const typoInput = { adress: "0x1234" };
|
||||
expect(advertised.inputSchema).toHaveProperty(
|
||||
"additionalProperties",
|
||||
false,
|
||||
);
|
||||
expect(validateAddressName(typoInput)).toBe(false);
|
||||
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,
|
||||
document: null,
|
||||
});
|
||||
expect(
|
||||
invocations.find(({ name }) => name === "search_strings")?.arguments_,
|
||||
).toEqual({
|
||||
pattern: "hello",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
document: null,
|
||||
});
|
||||
});
|
||||
OFFICIAL_TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "address_name",
|
||||
)?.inputSchema.safeParse(typoInput).success,
|
||||
).toBe(false);
|
||||
expect(validateRecordInput({ names: { "0x1000": "entry" } })).toBe(true);
|
||||
|
||||
const result = await client.callTool({
|
||||
name: "address_name",
|
||||
arguments: typoInput,
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(invocations).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("official Hopper proxy tools", () => {
|
||||
it("returns stable safe MCP error content", async () => {
|
||||
const client = await connect({
|
||||
execute: () => Promise.resolve(err(new HopperRemoteError(-1, "denied"))),
|
||||
@@ -341,7 +144,7 @@ describe("official Hopper proxy tools", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("returns every procedure inline without caller-authored page calls", async () => {
|
||||
it("binds list_procedures and projects its omitted Python document option", async () => {
|
||||
const invocations: Invocation[] = [];
|
||||
const client = await connect({
|
||||
execute: (name, arguments_) => {
|
||||
@@ -367,6 +170,7 @@ describe("official Hopper proxy tools", () => {
|
||||
],
|
||||
});
|
||||
expect(invocations).toHaveLength(1);
|
||||
expect(invocations[0]?.name).toBe("list_procedures");
|
||||
expect(invocations[0]?.arguments_).toEqual({ document: null });
|
||||
expect(
|
||||
(await client.listTools()).tools.find(
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { MANAGED_NATIVE_VERIFICATION_EXAMPLE } from "../../../src/contracts/managed/managedWorkflowExamples.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/domain/process/processCaptureExample.js";
|
||||
import {
|
||||
managedNativeVerificationInputSchema,
|
||||
managedNativeVerificationResultSchema,
|
||||
verifyManagedNativeBoundaries,
|
||||
} from "../../../src/domain/managed/managedNativeVerification.js";
|
||||
import { nativeUiResultSchema } from "../../../src/domain/native/nativeUiObservation.js";
|
||||
import { processCaptureSchema } from "../../../src/domain/process/processCapture.js";
|
||||
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
|
||||
|
||||
const record = (value: unknown): Record<string, unknown> => {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
throw new Error("Expected a schema object");
|
||||
return value as Record<string, unknown>;
|
||||
};
|
||||
|
||||
it("advertises semantic output invariants and keeps producers aligned with Zod", async () => {
|
||||
const contracts = [
|
||||
toolContract("capture_native_ui_scenario"),
|
||||
toolContract("capture_process_scenario"),
|
||||
toolContract("verify_managed_native_boundaries"),
|
||||
];
|
||||
const server = new McpServer({
|
||||
name: "output-schema-semantics",
|
||||
version: "1",
|
||||
});
|
||||
const client = new Client({ name: "output-schema-semantics", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
for (const contract of contracts)
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
async () => ({ content: [] }),
|
||||
);
|
||||
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const advertised = new Map(
|
||||
(await client.listTools()).tools.map((tool) => [tool.name, tool]),
|
||||
);
|
||||
const outputResultSchema = (name: (typeof contracts)[number]["name"]) => {
|
||||
const tool = advertised.get(name);
|
||||
if (tool?.outputSchema === undefined)
|
||||
throw new Error(`${name} output schema missing`);
|
||||
const outputSchema = record(tool.outputSchema);
|
||||
const result = record(record(outputSchema.properties).result);
|
||||
const standaloneResultSchema = z.record(z.string(), z.unknown()).parse({
|
||||
...result,
|
||||
...(typeof outputSchema.$schema === "string"
|
||||
? { $schema: outputSchema.$schema }
|
||||
: {}),
|
||||
...(outputSchema.$defs === undefined
|
||||
? {}
|
||||
: { $defs: outputSchema.$defs }),
|
||||
});
|
||||
return {
|
||||
result,
|
||||
validate: new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
}).compile(standaloneResultSchema),
|
||||
};
|
||||
};
|
||||
|
||||
const native = outputResultSchema("capture_native_ui_scenario");
|
||||
const initial = record(record(native.result.properties).initial);
|
||||
const screenshotUnion = record(record(initial.properties).screenshot);
|
||||
const screenshotVariants = screenshotUnion.anyOf;
|
||||
if (!Array.isArray(screenshotVariants))
|
||||
throw new Error("Expected nullable screenshot schema");
|
||||
const screenshotProperties = record(
|
||||
record(screenshotVariants[0]).properties,
|
||||
);
|
||||
expect(record(screenshotProperties.base64).description).toContain(
|
||||
"PNG signature",
|
||||
);
|
||||
expect(record(screenshotProperties.sha256).description).toContain(
|
||||
"decoded PNG bytes",
|
||||
);
|
||||
const pngBytes = Buffer.from("not a PNG");
|
||||
const invalidScreenshot = {
|
||||
target_sha256: "a".repeat(64),
|
||||
initial: {
|
||||
window: {
|
||||
pid: 1,
|
||||
window_id: 1,
|
||||
executable: "app",
|
||||
launch_time: 0,
|
||||
title: "",
|
||||
},
|
||||
nodes: [],
|
||||
truncated: false,
|
||||
screenshot: {
|
||||
mime_type: "image/png",
|
||||
base64: pngBytes.toString("base64"),
|
||||
sha256: createHash("sha256").update(pngBytes).digest("hex"),
|
||||
width: 1,
|
||||
height: 1,
|
||||
},
|
||||
gaps: [],
|
||||
},
|
||||
steps: [],
|
||||
restore: "leave-as-is",
|
||||
limitations: [],
|
||||
};
|
||||
expect(native.validate(invalidScreenshot)).toBe(true);
|
||||
expect(nativeUiResultSchema.safeParse(invalidScreenshot).success).toBe(
|
||||
false,
|
||||
);
|
||||
|
||||
const process = outputResultSchema("capture_process_scenario");
|
||||
expect(process.result.description).toContain("canonical scenario");
|
||||
expect(process.result.description).toContain(
|
||||
"older input without an event journal",
|
||||
);
|
||||
const validCapture = processCaptureSchema.parse(
|
||||
EMPTY_PROCESS_CAPTURE_EXAMPLE,
|
||||
);
|
||||
expect(validCapture.event_journal).toEqual([]);
|
||||
expect(process.validate(validCapture)).toBe(true);
|
||||
expect(
|
||||
processCaptureSchema.safeParse(EMPTY_PROCESS_CAPTURE_EXAMPLE).success,
|
||||
).toBe(true);
|
||||
const invalidCapture = {
|
||||
...validCapture,
|
||||
manifest: {
|
||||
...validCapture.manifest,
|
||||
full_scenario_sha256: "0".repeat(64),
|
||||
},
|
||||
};
|
||||
expect(process.validate(invalidCapture)).toBe(true);
|
||||
expect(processCaptureSchema.safeParse(invalidCapture).success).toBe(false);
|
||||
|
||||
const managed = outputResultSchema("verify_managed_native_boundaries");
|
||||
expect(managed.result.description).toContain(
|
||||
"accepted plus unsupported equals total",
|
||||
);
|
||||
const validVerification = verifyManagedNativeBoundaries(
|
||||
managedNativeVerificationInputSchema.parse(
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE,
|
||||
),
|
||||
);
|
||||
expect(managed.validate(validVerification)).toBe(true);
|
||||
const invalidVerification = structuredClone(validVerification);
|
||||
invalidVerification.summary.verified += 1;
|
||||
expect(managed.validate(invalidVerification)).toBe(true);
|
||||
expect(
|
||||
managedNativeVerificationResultSchema.safeParse(invalidVerification)
|
||||
.success,
|
||||
).toBe(false);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
@@ -5,14 +5,14 @@ import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { compareProcessEvidenceFiles } from "../../../src/application/ProcessCli.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/application/ProcessEvidence.js";
|
||||
import { compareProcessEvidenceFiles } from "../../../src/application/process/ProcessCli.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/application/process/ProcessEvidence.js";
|
||||
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
|
||||
import {
|
||||
FUNCTION_COMPARISON_EVIDENCE,
|
||||
INVESTIGATION_EXAMPLES,
|
||||
} from "../../../src/contracts/investigationExamples.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/process/processCaptureExample.js";
|
||||
import { findChangedBehavior } from "../../../src/domain/changedBehavior.js";
|
||||
import {
|
||||
createEvidence,
|
||||
|
||||
@@ -6,12 +6,12 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.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 { compareProcessEvidenceFiles } from "../../../src/application/process/ProcessCli.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/application/process/ProcessEvidence.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/process/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 type { ProcessTraceSpecification } from "../../../src/domain/process/processTraceComparison.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { AnalysisClient } from "../../../src/application/AnalysisProvider.j
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { ARTIFACT_COMPARISON_EXAMPLE } from "../../../src/contracts/artifactComparisonExample.js";
|
||||
import { PROCESS_CAPTURE_REFERENCE } from "../../../src/contracts/investigationExamples.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/domain/process/processCaptureExample.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createArtifactInspection } from "../../../src/domain/artifactInspection.js";
|
||||
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
|
||||
@@ -57,6 +58,36 @@ describe("guided prompt completion from live analysis", () => {
|
||||
});
|
||||
|
||||
describe("guided prompt completion from investigation records", () => {
|
||||
it("completes process captures imported in the original v3 format", async () => {
|
||||
const session = createTestBinarySession(() => client([]));
|
||||
const {
|
||||
selected_executable_sha256: _selectedDigest,
|
||||
executable_identity: _identity,
|
||||
executable_sha256,
|
||||
...legacyManifest
|
||||
} = EMPTY_PROCESS_CAPTURE_EXAMPLE.manifest;
|
||||
const legacyCapture = {
|
||||
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
|
||||
manifest: { ...legacyManifest, executable_sha256 },
|
||||
};
|
||||
const evidence = createEvidence(undefined, fixtureProvider, {
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: legacyCapture,
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
environment: fixtureEnvironment,
|
||||
});
|
||||
expect(session.recordEvidence(evidence).ok).toBe(true);
|
||||
const completion = createPromptCompletionSource(session, session);
|
||||
|
||||
expect(
|
||||
await completion.complete("capture", evidence.evidence_id.slice(0, 8)),
|
||||
).toEqual([evidence.evidence_id]);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("projects only validated typed identifiers from the evidence ledger", async () => {
|
||||
const session = createTestBinarySession(() => client([]));
|
||||
const invalidCapture = createEvidence(undefined, fixtureProvider, {
|
||||
|
||||
@@ -15,8 +15,8 @@ import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { parseEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { processCaptureSchema } from "../../../src/domain/processCapture.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
|
||||
import { processCaptureSchema } from "../../../src/domain/process/processCapture.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/process/processCaptureExample.js";
|
||||
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
|
||||
import { PROCESS_PROVIDER } from "../../../src/server/sessionToolPolicies.js";
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -14,9 +15,10 @@ import type {
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import { probeProcessCaptureCapability } from "../../../src/application/ProcessHarness.js";
|
||||
import { probeProcessCaptureCapability } from "../../../src/process/capture/ProcessHarness.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
|
||||
import { ok as resultOk } from "../../../src/domain/result.js";
|
||||
@@ -227,6 +229,37 @@ describe("target-free MCP workflow", () => {
|
||||
}, 10_000);
|
||||
});
|
||||
|
||||
describe("session filesystem path boundaries over MCP", () => {
|
||||
it("rejects relative snapshot and export paths with an absolute-path error", async () => {
|
||||
directory = await createTestTempDirectory("rea-mcp-path-boundary-");
|
||||
const { mcp, first } = await createSessionMcpHarness(
|
||||
directory,
|
||||
provider,
|
||||
resources,
|
||||
);
|
||||
|
||||
const exported = await mcp.callTool({
|
||||
name: "export_evidence_bundle",
|
||||
arguments: { path: "relative-bundle.json" },
|
||||
});
|
||||
expect(exported.isError, JSON.stringify(exported.content)).toBe(true);
|
||||
expect(JSON.stringify(exported.content)).toContain("absolute");
|
||||
|
||||
const opened = await mcp.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: first },
|
||||
});
|
||||
expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true);
|
||||
const closed = await mcp.callTool({
|
||||
name: "close_binary",
|
||||
arguments: { snapshot_path: "relative-analysis.json" },
|
||||
});
|
||||
expect(closed.isError, JSON.stringify(closed.content)).toBe(true);
|
||||
expect(JSON.stringify(closed.content)).toContain("absolute");
|
||||
await mcp.callTool({ name: "close_binary", arguments: {} });
|
||||
}, 10_000);
|
||||
});
|
||||
|
||||
describe("process residuals over MCP", () => {
|
||||
it("records process residuals linked to capture Evidence", async () => {
|
||||
if (!(await probeProcessCaptureCapability()).available) return;
|
||||
@@ -249,6 +282,21 @@ describe("process residuals over MCP", () => {
|
||||
},
|
||||
});
|
||||
expect(captured.isError, text(captured)).not.toBe(true);
|
||||
const contract = toolContract("capture_process_scenario");
|
||||
const wire = (await mcp.listTools()).tools.find(
|
||||
({ name }) => name === contract.name,
|
||||
);
|
||||
if (wire?.outputSchema === undefined)
|
||||
throw new Error("Missing process capture output schema");
|
||||
expect(
|
||||
new Ajv2020({ strict: false, validateFormats: false }).validate(
|
||||
z.record(z.string(), z.unknown()).parse(wire.outputSchema),
|
||||
captured.structuredContent,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
contract.outputSchema.safeParse(captured.structuredContent).success,
|
||||
).toBe(true);
|
||||
const listedUnknowns = await mcp.callTool({
|
||||
name: "list_unknowns",
|
||||
arguments: {},
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { GENERATED_MCP_TOOL_CATALOG } from "../../../src/generatedMcpToolCatalog.js";
|
||||
import { annotationsFromEffects } from "../../../src/contracts/toolEffects.js";
|
||||
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
|
||||
|
||||
describe("tool registration options", () => {
|
||||
it("generates the checked-in catalog from the SDK wire projection", async () => {
|
||||
const server = new McpServer({ name: "catalog-test", version: "0" });
|
||||
for (const contract of TOOL_CONTRACTS)
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
async () => ({
|
||||
content: [{ type: "text" as const, text: "catalog-only" }],
|
||||
isError: true as const,
|
||||
}),
|
||||
);
|
||||
const client = new Client({ name: "catalog-test", version: "0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const advertised = (await client.listTools()).tools.map((tool) => ({
|
||||
name: tool.name,
|
||||
title: tool.title,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema,
|
||||
outputSchema: tool.outputSchema,
|
||||
annotations: tool.annotations,
|
||||
}));
|
||||
for (const contract of TOOL_CONTRACTS) {
|
||||
const tool = advertised.find(({ name }) => name === contract.name);
|
||||
expect(tool, contract.name).toBeDefined();
|
||||
expect(describesObject(tool?.inputSchema), contract.name).toBe(true);
|
||||
expect(describesObject(tool?.outputSchema), contract.name).toBe(true);
|
||||
expect(tool?.title?.trim().length, contract.name).toBeGreaterThan(0);
|
||||
expect(tool?.description?.trim().length, contract.name).toBeGreaterThan(
|
||||
0,
|
||||
);
|
||||
expect(JSON.stringify(tool?.outputSchema), contract.name).not.toContain(
|
||||
'"result":{}',
|
||||
);
|
||||
expect(tool?.annotations, contract.name).toEqual(
|
||||
annotationsFromEffects(contract.effects),
|
||||
);
|
||||
expect(contract.examples.length, contract.name).toBeGreaterThan(0);
|
||||
for (const example of contract.examples) {
|
||||
expect(example.title.trim().length, contract.name).toBeGreaterThan(0);
|
||||
expect(
|
||||
contract.inputSchema.safeParse(example.input).success,
|
||||
`${contract.name}: ${example.title}`,
|
||||
).toBe(true);
|
||||
}
|
||||
|
||||
expect(tool?.inputSchema.examples, contract.name).toEqual(
|
||||
contract.examples.map(({ input }) => input),
|
||||
);
|
||||
expect(
|
||||
missingPropertyDescriptions(tool?.inputSchema),
|
||||
contract.name,
|
||||
).toEqual([]);
|
||||
}
|
||||
expect(advertised).toEqual(
|
||||
GENERATED_MCP_TOOL_CATALOG.map((tool) => ({
|
||||
name: tool.name,
|
||||
title: tool.title,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema,
|
||||
outputSchema: tool.outputSchema,
|
||||
annotations: tool.annotations,
|
||||
})),
|
||||
);
|
||||
for (const [name, expected] of [
|
||||
["binary_session", { readOnlyHint: true, openWorldHint: false }],
|
||||
["read_bytes", { readOnlyHint: false, destructiveHint: false }],
|
||||
["set_comment", { readOnlyHint: false }],
|
||||
["unset_bookmark", { destructiveHint: true }],
|
||||
[
|
||||
"capture_process_scenario",
|
||||
{ readOnlyHint: false, openWorldHint: true },
|
||||
],
|
||||
["inspect_artifact", { readOnlyHint: false, openWorldHint: true }],
|
||||
["extract_artifact", { readOnlyHint: false, idempotentHint: false }],
|
||||
["compare_web_captures", { readOnlyHint: false, openWorldHint: false }],
|
||||
[
|
||||
"compare_web_screenshots",
|
||||
{ readOnlyHint: false, openWorldHint: false },
|
||||
],
|
||||
] as const) {
|
||||
expect(
|
||||
advertised.find((tool) => tool.name === name)?.annotations,
|
||||
name,
|
||||
).toMatchObject(expected);
|
||||
}
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const missingPropertyDescriptions = (
|
||||
value: unknown,
|
||||
path = "inputSchema",
|
||||
): string[] => {
|
||||
if (Array.isArray(value))
|
||||
return value.flatMap((child, index) =>
|
||||
missingPropertyDescriptions(child, `${path}[${index}]`),
|
||||
);
|
||||
if (!isObject(value)) return [];
|
||||
|
||||
const missing: string[] = [];
|
||||
if (isObject(value.properties))
|
||||
for (const [property, schema] of Object.entries(value.properties)) {
|
||||
const propertyPath = `${path}.properties.${property}`;
|
||||
if (!isObject(schema) || typeof schema.description !== "string")
|
||||
missing.push(propertyPath);
|
||||
missing.push(...missingPropertyDescriptions(schema, propertyPath));
|
||||
}
|
||||
for (const [key, child] of Object.entries(value))
|
||||
if (
|
||||
key !== "properties" &&
|
||||
key !== "examples" &&
|
||||
key !== "default" &&
|
||||
key !== "const" &&
|
||||
key !== "enum"
|
||||
)
|
||||
missing.push(...missingPropertyDescriptions(child, `${path}.${key}`));
|
||||
return missing;
|
||||
};
|
||||
|
||||
const isObject = (value: unknown): value is Readonly<Record<string, unknown>> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
const describesObject = (schema: unknown): boolean => {
|
||||
if (!isObject(schema)) return false;
|
||||
return (
|
||||
schema.type === "object" ||
|
||||
[schema.oneOf, schema.anyOf].some(
|
||||
(variants) =>
|
||||
Array.isArray(variants) &&
|
||||
variants.length > 0 &&
|
||||
variants.every(
|
||||
(variant: unknown) => isObject(variant) && variant.type === "object",
|
||||
),
|
||||
)
|
||||
);
|
||||
};
|
||||
@@ -1,14 +1,24 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { ToolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { ProcessCaptureError } from "../../../src/process/capture/ProcessCaptureError.js";
|
||||
import { resolveProcessResult } from "../../../src/process/capture/ProcessCaptureLifecycle.js";
|
||||
import {
|
||||
toolContract,
|
||||
type ToolContract,
|
||||
} from "../../../src/contracts/toolContracts.js";
|
||||
import { err, ok } from "../../../src/domain/result.js";
|
||||
import { HopperProcessError } from "../../../src/domain/hopperErrors.js";
|
||||
import type { IncompleteProcessCaptureObservations } from "../../../src/domain/process/processCapture.js";
|
||||
import { processScenarioSchema } from "../../../src/domain/process/processScenario.js";
|
||||
import { toCallToolResult } from "../../../src/server/toolResult.js";
|
||||
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { emptyProcessCapture } from "../../../src/domain/process/processCapture.fixture.js";
|
||||
import type { JsonValue } from "../../../src/domain/jsonValue.js";
|
||||
import { evidenceResultOf } from "../../../src/contracts/toolOutputSchemas.js";
|
||||
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
|
||||
|
||||
const contract: ToolContract = {
|
||||
name: "provider_neutral_fixture",
|
||||
@@ -36,6 +46,215 @@ const contract: ToolContract = {
|
||||
examples: [{ title: "Example fixture request", input: {} }],
|
||||
};
|
||||
|
||||
describe("completed partial process capture MCP projection", () => {
|
||||
it("preserves partial capture details over the MCP SDK transport", async () => {
|
||||
const executionFailure = new Error("capture ended after a fixture error");
|
||||
const cleanup = {
|
||||
owned_process_group: {
|
||||
state: "unverified" as const,
|
||||
reason: "process ownership token could not be read",
|
||||
},
|
||||
terminal_renderer: { state: "cleaned" as const, reason: null },
|
||||
temporary_root: { state: "cleaned" as const, reason: null },
|
||||
};
|
||||
const capture = {
|
||||
...emptyProcessCapture(),
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "observed output" }],
|
||||
event_journal: [],
|
||||
};
|
||||
|
||||
let failure: ProcessCaptureError | undefined;
|
||||
try {
|
||||
resolveProcessResult(capture, executionFailure, cleanup);
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof ProcessCaptureError)) throw cause;
|
||||
failure = cause;
|
||||
}
|
||||
expect(failure).toBeDefined();
|
||||
if (failure === undefined)
|
||||
throw new Error("expected cleanup-incomplete result");
|
||||
|
||||
const captureContract = toolContract("capture_process_scenario");
|
||||
const server = new McpServer({
|
||||
name: "process-partial-error",
|
||||
version: "1",
|
||||
});
|
||||
server.registerTool(
|
||||
captureContract.name,
|
||||
toolRegistrationOptions(captureContract),
|
||||
async () => toCallToolResult(err(failure), captureContract),
|
||||
);
|
||||
const client = new Client({
|
||||
name: "process-partial-error-client",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: captureContract.name,
|
||||
arguments: captureContract.examples[0]?.input ?? {},
|
||||
});
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
error: {
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
cleanup_report: cleanup,
|
||||
execution_failure: "capture ended after a fixture error",
|
||||
partial_observation: {
|
||||
capture: {
|
||||
frames: [{ data: "observed output" }],
|
||||
settlement: { cleanup_outcome: "failed" },
|
||||
},
|
||||
execution_failure: "capture ended after a fixture error",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const textContent = result.content.find((block) => block.type === "text");
|
||||
expect(textContent?.type === "text" ? textContent.text : undefined).toBe(
|
||||
JSON.stringify(result.structuredContent),
|
||||
);
|
||||
} finally {
|
||||
await Promise.all([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("incomplete partial process observations MCP projection", () => {
|
||||
it("preserves normalized raw observations over the MCP SDK transport", async () => {
|
||||
const captureContract = toolContract("capture_process_scenario");
|
||||
const example = captureContract.examples[0];
|
||||
if (example === undefined)
|
||||
throw new Error("missing process scenario example");
|
||||
const scenario = processScenarioSchema.parse({
|
||||
...example.input,
|
||||
normalization: { pids: false },
|
||||
});
|
||||
const rootPid = 45678;
|
||||
const cleanup = {
|
||||
owned_process_group: {
|
||||
state: "unverified" as const,
|
||||
reason: "process ownership token could not be read",
|
||||
},
|
||||
terminal_renderer: { state: "cleaned" as const, reason: null },
|
||||
temporary_root: { state: "cleaned" as const, reason: null },
|
||||
};
|
||||
const observations: IncompleteProcessCaptureObservations = {
|
||||
target_pid: { state: "available", value: rootPid },
|
||||
frames: {
|
||||
state: "available",
|
||||
value: [{ sequence: 0, at_ms: 0, data: "partial output" }],
|
||||
},
|
||||
rendered_frames: {
|
||||
state: "unavailable",
|
||||
reason: "fixture renderer observation unavailable",
|
||||
},
|
||||
interaction_events: { state: "available", value: [] },
|
||||
exit: {
|
||||
state: "unavailable",
|
||||
reason: "fixture terminal exit unavailable",
|
||||
},
|
||||
settlement: {
|
||||
state: "unavailable",
|
||||
reason: "fixture process settlement unavailable",
|
||||
},
|
||||
process_samples: {
|
||||
state: "available",
|
||||
value: [
|
||||
{
|
||||
at_ms: 1,
|
||||
pid: rootPid,
|
||||
parent_pid: 1,
|
||||
command: `fixture ${String(rootPid)}`,
|
||||
process_group_id: rootPid,
|
||||
session_id: rootPid,
|
||||
},
|
||||
],
|
||||
},
|
||||
filesystem_snapshots: {
|
||||
before: { state: "available", value: { files: [], truncated: false } },
|
||||
after: {
|
||||
state: "unavailable",
|
||||
reason: "fixture final snapshot unavailable",
|
||||
},
|
||||
},
|
||||
event_journal: { state: "available", value: [] },
|
||||
manifest: {
|
||||
state: "unavailable",
|
||||
reason: "fixture capture manifest unavailable",
|
||||
},
|
||||
};
|
||||
|
||||
let failure: ProcessCaptureError | undefined;
|
||||
try {
|
||||
resolveProcessResult(
|
||||
undefined,
|
||||
new Error("capture failed before completion"),
|
||||
cleanup,
|
||||
observations,
|
||||
{ scenario, rootPid },
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof ProcessCaptureError)) throw cause;
|
||||
failure = cause;
|
||||
}
|
||||
if (failure === undefined)
|
||||
throw new Error("expected cleanup-incomplete result");
|
||||
|
||||
const server = new McpServer({
|
||||
name: "process-partial-observations",
|
||||
version: "1",
|
||||
});
|
||||
server.registerTool(
|
||||
captureContract.name,
|
||||
toolRegistrationOptions(captureContract),
|
||||
async () => toCallToolResult(err(failure), captureContract),
|
||||
);
|
||||
const client = new Client({
|
||||
name: "process-partial-observations-client",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: captureContract.name,
|
||||
arguments: example.input,
|
||||
});
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
error: {
|
||||
details: {
|
||||
partial_observation: {
|
||||
observations: {
|
||||
target_pid: { state: "available", value: rootPid },
|
||||
frames: {
|
||||
state: "available",
|
||||
value: [{ data: "partial output" }],
|
||||
},
|
||||
process_samples: {
|
||||
state: "available",
|
||||
value: [{ pid: rootPid }],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await Promise.all([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("tool result projection", () => {
|
||||
it("exposes an actionable adapter code to MCP callers", () => {
|
||||
const result = toCallToolResult(err(new HopperProcessError(76)), contract);
|
||||
|
||||
@@ -6,7 +6,7 @@ import { z } from "zod";
|
||||
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { emptyArraySchema } from "../../../src/domain/emptyArraySchema.js";
|
||||
import { processScenarioSchema } from "../../../src/domain/processScenario.js";
|
||||
import { processScenarioSchema } from "../../../src/domain/process/processScenario.js";
|
||||
import { GENERATED_MCP_TOOL_CATALOG } from "../../../src/generatedMcpToolCatalog.js";
|
||||
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
|
||||
|
||||
@@ -14,6 +14,7 @@ interface ToolSchemas {
|
||||
readonly name: string;
|
||||
readonly inputSchema: Record<string, unknown>;
|
||||
readonly outputSchema?: Record<string, unknown> | undefined;
|
||||
readonly annotations?: Record<string, unknown> | undefined;
|
||||
}
|
||||
|
||||
function schemaErrors(tools: readonly ToolSchemas[]): string[] {
|
||||
@@ -28,6 +29,155 @@ function schemaErrors(tools: readonly ToolSchemas[]): string[] {
|
||||
);
|
||||
}
|
||||
|
||||
function expectStrictInputSchemaParity(
|
||||
tools: readonly ToolSchemas[],
|
||||
ajv: Ajv2020,
|
||||
): void {
|
||||
const advertised = new Map(tools.map((tool) => [tool.name, tool]));
|
||||
const names = [
|
||||
"inspect_managed_artifact",
|
||||
"inspect_managed_members",
|
||||
"inspect_managed_native_boundaries",
|
||||
"list_browser_targets",
|
||||
"open_binary",
|
||||
"close_binary",
|
||||
"binary_session",
|
||||
"find_changed_behavior",
|
||||
"build_call_path",
|
||||
"record_unknown",
|
||||
"update_unknown",
|
||||
];
|
||||
for (const name of names) {
|
||||
const contract = TOOL_CONTRACTS.find(
|
||||
({ name: toolName }) => toolName === name,
|
||||
);
|
||||
const tool = advertised.get(name);
|
||||
const example = contract?.examples[0];
|
||||
if (contract === undefined || tool === undefined || example === undefined)
|
||||
throw new Error(`${name} did not have an advertised example`);
|
||||
const malformed = { ...example.input, __unexpected_root_key__: true };
|
||||
expect(contract.inputSchema.safeParse(malformed).success, name).toBe(false);
|
||||
expect(ajv.compile(tool.inputSchema)(malformed), name).toBe(false);
|
||||
}
|
||||
}
|
||||
|
||||
function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
|
||||
const advertised = new Map(tools.map((tool) => [tool.name, tool]));
|
||||
const expected = {
|
||||
read_bytes: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
},
|
||||
annotate_native_function: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: true,
|
||||
},
|
||||
unset_bookmark: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: true,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
},
|
||||
open_binary: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: true,
|
||||
},
|
||||
close_binary: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: true,
|
||||
idempotentHint: false,
|
||||
openWorldHint: false,
|
||||
},
|
||||
} as const;
|
||||
|
||||
for (const [name, annotations] of Object.entries(expected))
|
||||
expect(advertised.get(name), name).toMatchObject({ annotations });
|
||||
}
|
||||
|
||||
function expectRecursivePropertyDescriptions(
|
||||
schema: unknown,
|
||||
path: string,
|
||||
): void {
|
||||
if (!isRecord(schema)) return;
|
||||
if (isRecord(schema.properties)) {
|
||||
for (const [property, child] of Object.entries(schema.properties)) {
|
||||
expect(child, `${path}.${property}`).toMatchObject({
|
||||
description: expect.any(String),
|
||||
});
|
||||
expectRecursivePropertyDescriptions(child, `${path}.${property}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const key of ["items", "additionalProperties"])
|
||||
if (schema[key] !== undefined)
|
||||
expectRecursivePropertyDescriptions(schema[key], path);
|
||||
for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"]) {
|
||||
const children = schema[key];
|
||||
if (Array.isArray(children))
|
||||
children.forEach((child: unknown, index: number) =>
|
||||
expectRecursivePropertyDescriptions(child, `${path}.${key}[${index}]`),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
function resolveReference(schema: unknown, reference: string): unknown {
|
||||
if (reference === "#") return schema;
|
||||
if (!reference.startsWith("#/")) return undefined;
|
||||
let value = schema;
|
||||
for (const token of reference.slice(2).split("/")) {
|
||||
const key = token.replaceAll("~1", "/").replaceAll("~0", "~");
|
||||
if (
|
||||
typeof value !== "object" ||
|
||||
value === null ||
|
||||
!Object.hasOwn(value, key)
|
||||
)
|
||||
return undefined;
|
||||
value = Reflect.get(value, key);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function recursiveReferences(tools: readonly ToolSchemas[]): string[] {
|
||||
return tools.flatMap((tool) =>
|
||||
(["inputSchema", "outputSchema"] as const).flatMap((kind) => {
|
||||
const schema = tool[kind];
|
||||
const found = new Set<string>();
|
||||
const visit = (node: unknown, active: readonly string[]): void => {
|
||||
if (typeof node !== "object" || node === null) return;
|
||||
for (const [key, child] of Object.entries(node)) {
|
||||
if (
|
||||
[
|
||||
"$defs",
|
||||
"definitions",
|
||||
"examples",
|
||||
"default",
|
||||
"const",
|
||||
"enum",
|
||||
].includes(key)
|
||||
)
|
||||
continue;
|
||||
if (key !== "$ref" || typeof child !== "string") visit(child, active);
|
||||
else if (active.includes(child)) found.add(child);
|
||||
else visit(resolveReference(schema, child), [...active, child]);
|
||||
}
|
||||
};
|
||||
visit(schema, []);
|
||||
return [...found].map(
|
||||
(reference) => `${tool.name}.${kind}: ${reference}`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const advertiseAndEnforceProcessEnvironmentKeyConstraint =
|
||||
async (): Promise<void> => {
|
||||
const contract = TOOL_CONTRACTS.find(
|
||||
@@ -118,15 +268,6 @@ describe("MCP JSON Schema validity", () => {
|
||||
expect(validate(value)).toBe(false);
|
||||
});
|
||||
|
||||
it("uses an oracle that rejects empty prefixItems under Draft 2020-12", () => {
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
expect(ajv.defaultMeta()).toBe(
|
||||
"https://json-schema.org/draft/2020-12/schema",
|
||||
);
|
||||
expect(ajv.validateSchema({ type: "array", prefixItems: [] })).toBe(false);
|
||||
expect(ajv.validateSchema({ type: "array", maxItems: 0 })).toBe(true);
|
||||
});
|
||||
|
||||
it("advertises valid input and output schemas for every canonical tool", async () => {
|
||||
const server = new McpServer({ name: "schema-validation", version: "0" });
|
||||
const client = new Client({ name: "schema-validation", version: "0" });
|
||||
@@ -148,6 +289,41 @@ describe("MCP JSON Schema validity", () => {
|
||||
TOOL_CONTRACTS.map(({ name }) => name).sort(),
|
||||
);
|
||||
expect(schemaErrors(tools)).toEqual([]);
|
||||
expect(recursiveReferences(tools)).toEqual([]);
|
||||
expectKnownAuthorityHints(tools);
|
||||
const byName = new Map(tools.map((tool) => [tool.name, tool]));
|
||||
const catalogProjection = tools.map((tool) => ({
|
||||
name: tool.name,
|
||||
title: tool.title,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema,
|
||||
outputSchema: tool.outputSchema,
|
||||
annotations: tool.annotations,
|
||||
}));
|
||||
expect(catalogProjection).toEqual(
|
||||
GENERATED_MCP_TOOL_CATALOG.map((tool) => ({
|
||||
name: tool.name,
|
||||
title: tool.title,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema,
|
||||
outputSchema: tool.outputSchema,
|
||||
annotations: tool.annotations,
|
||||
})),
|
||||
);
|
||||
for (const contract of TOOL_CONTRACTS) {
|
||||
const tool = byName.get(contract.name);
|
||||
expect(tool?.title?.trim(), contract.name).toBeTruthy();
|
||||
expect(tool?.description?.trim(), contract.name).toBeTruthy();
|
||||
expect(tool?.inputSchema.examples, contract.name).toEqual(
|
||||
contract.examples.map(({ input }) => input),
|
||||
);
|
||||
for (const example of contract.examples)
|
||||
expect(
|
||||
contract.inputSchema.safeParse(example.input).success,
|
||||
`${contract.name}: ${example.title}`,
|
||||
).toBe(true);
|
||||
expectRecursivePropertyDescriptions(tool?.inputSchema, contract.name);
|
||||
}
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
@@ -190,6 +366,8 @@ describe("MCP JSON Schema validity", () => {
|
||||
).toBe(true);
|
||||
}
|
||||
|
||||
expectStrictInputSchemaParity(tools, ajv);
|
||||
|
||||
const nativeObservation = TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "observe_native_ui",
|
||||
);
|
||||
@@ -220,13 +398,98 @@ describe("MCP JSON Schema validity", () => {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
|
||||
it("ships valid input and output schemas in the generated catalog", () => {
|
||||
expect(schemaErrors(GENERATED_MCP_TOOL_CATALOG)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it(
|
||||
"advertises and enforces the process-owned environment key constraint",
|
||||
advertiseAndEnforceProcessEnvironmentKeyConstraint,
|
||||
);
|
||||
|
||||
describe("MCP process input JSON Schema", () => {
|
||||
it("advertises process strings without weakening terminal input", async () => {
|
||||
const server = new McpServer({
|
||||
name: "process-schema-validation",
|
||||
version: "0",
|
||||
});
|
||||
const client = new Client({
|
||||
name: "process-schema-validation",
|
||||
version: "0",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
for (const contract of TOOL_CONTRACTS)
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
async () => ({ content: [] }),
|
||||
);
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const processContract = TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "capture_process_scenario",
|
||||
);
|
||||
const processTool = (await client.listTools()).tools.find(
|
||||
({ name }) => name === "capture_process_scenario",
|
||||
);
|
||||
if (processContract === undefined || processTool === undefined)
|
||||
throw new Error("Process scenario tool was not advertised");
|
||||
const validate = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
}).compile(processTool.inputSchema);
|
||||
const base = { executable: "/usr/bin/true" };
|
||||
for (const input of [
|
||||
{ ...base, executable: "/usr/bin/true\0" },
|
||||
{ ...base, arguments: ["\0"] },
|
||||
{ ...base, working_directory: "/tmp\0" },
|
||||
{ ...base, environment: { KEY: "value\0" } },
|
||||
{ ...base, filesystem_observation_paths: ["/tmp\0"] },
|
||||
]) {
|
||||
expect(processContract.inputSchema.safeParse(input).success).toBe(
|
||||
false,
|
||||
);
|
||||
expect(validate(input)).toBe(false);
|
||||
}
|
||||
const terminalInput = {
|
||||
...base,
|
||||
events: [{ type: "input", at_ms: 0, data: "\0" }],
|
||||
};
|
||||
expect(processContract.inputSchema.safeParse(terminalInput).success).toBe(
|
||||
true,
|
||||
);
|
||||
expect(validate(terminalInput)).toBe(true);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("ships nonrecursive input and output schemas in the generated catalog", () => {
|
||||
expect(schemaErrors(GENERATED_MCP_TOOL_CATALOG)).toEqual([]);
|
||||
expect(recursiveReferences(GENERATED_MCP_TOOL_CATALOG)).toEqual([]);
|
||||
});
|
||||
|
||||
it("distinguishes recursive references from shared definitions", () => {
|
||||
const diamond = {
|
||||
type: "object",
|
||||
properties: {
|
||||
left: { $ref: "#/$defs/shared" },
|
||||
right: { $ref: "#/$defs/shared" },
|
||||
},
|
||||
$defs: { shared: { type: "string" } },
|
||||
};
|
||||
expect(
|
||||
recursiveReferences([{ name: "diamond", inputSchema: diamond }]),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
recursiveReferences([{ name: "root", inputSchema: { $ref: "#" } }]),
|
||||
).toEqual(["root.inputSchema: #"]);
|
||||
const escaped = {
|
||||
$ref: "#/$defs/a~1b",
|
||||
$defs: { "a/b": { $ref: "#/$defs/a~1b" } },
|
||||
};
|
||||
expect(
|
||||
recursiveReferences([{ name: "escaped", inputSchema: escaped }]),
|
||||
).toEqual(["escaped.inputSchema: #/$defs/a~1b"]);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { WebNetworkCaptureService } from "../../../src/application/WebNetworkCaptureService.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";
|
||||
|
||||
it("publishes valid SDK schemas and retains historical inline Evidence with the supplied session", async () => {
|
||||
const service = new WebNetworkCaptureService({
|
||||
inspect: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
artifact: { path: "/capture.har", sha256: "a".repeat(64), bytes: 10 },
|
||||
format: "har",
|
||||
decoder: { id: "test-capture-port", name: "test port", version: "1" },
|
||||
container: {
|
||||
reported: { creator: "fixture" },
|
||||
numeric_literals: [],
|
||||
redactions: [],
|
||||
records_pointer: "/log/entries",
|
||||
},
|
||||
total_records: 0,
|
||||
records: [],
|
||||
runtime_attribution: "unknown",
|
||||
limitations: ["synthetic application port, no real decoder claim"],
|
||||
}),
|
||||
),
|
||||
});
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Binary provider must not start");
|
||||
});
|
||||
const server = createServer(session, session, { webNetworkCapture: service });
|
||||
const client = new Client({
|
||||
name: "historical-capture-contract",
|
||||
version: "1",
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const advertised = (await client.listTools()).tools.find(
|
||||
(tool) => tool.name === "inspect_web_network_capture",
|
||||
);
|
||||
if (advertised?.outputSchema === undefined)
|
||||
throw new Error("Capture inspection must advertise 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 args = { capture_path: "/capture.har", format: "har" };
|
||||
expect(ajv.validate(inputSchema, args)).toBe(true);
|
||||
const response = await client.callTool({
|
||||
name: "inspect_web_network_capture",
|
||||
arguments: args,
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
expect(
|
||||
ajv.validate(outputSchema, response.structuredContent),
|
||||
JSON.stringify(ajv.errors),
|
||||
).toBe(true);
|
||||
const parsed = toolContract("inspect_web_network_capture").outputSchema.parse(
|
||||
response.structuredContent,
|
||||
);
|
||||
const evidence = parseEvidence(parsed.evidence);
|
||||
expect(parsed.result).toEqual(evidence.normalized_result);
|
||||
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
|
||||
const invalid = await client.callTool({
|
||||
name: "inspect_web_network_capture",
|
||||
arguments: { ...args, capture_path: "relative.har" },
|
||||
});
|
||||
expect(invalid.isError).toBe(true);
|
||||
const invalidSensitive = await client.callTool({
|
||||
name: "inspect_web_network_capture",
|
||||
arguments: { ...args, sensitive_values: ["secret"], mysecret: true },
|
||||
});
|
||||
expect(invalidSensitive.isError).toBe(true);
|
||||
expect(invalidSensitive.structuredContent).toMatchObject({
|
||||
error: { code: "invalid_request", details: { issues: [{ path: [] }] } },
|
||||
});
|
||||
expect(JSON.stringify(invalidSensitive)).not.toContain("secret");
|
||||
expect(ajv.validate(inputSchema, { ...args, mysecret: true })).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,240 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { browserCaptureComparisonInputSchema } from "../../../src/domain/browserCaptureComparison.js";
|
||||
import { webPageInspectionSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { GENERATED_MCP_TOOL_CATALOG } from "../../../src/generatedMcpToolCatalog.js";
|
||||
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
function resolveLocalReference(root: unknown, reference: string): unknown {
|
||||
if (reference === "#") return root;
|
||||
if (!reference.startsWith("#/")) return undefined;
|
||||
let current = root;
|
||||
for (const part of reference.slice(2).split("/")) {
|
||||
const key = part.replaceAll("~1", "/").replaceAll("~0", "~");
|
||||
if (!isRecord(current) || !Object.hasOwn(current, key)) return undefined;
|
||||
current = current[key];
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
// Count object/array and composition levels, following references per path.
|
||||
// Definitions, property maps, and literal example/default data are not levels.
|
||||
function inputDepth(
|
||||
schema: unknown,
|
||||
root: unknown = schema,
|
||||
activeReferences: readonly string[] = [],
|
||||
): number {
|
||||
if (!isRecord(schema)) return 0;
|
||||
let referenceDepth = 0;
|
||||
if (typeof schema.$ref === "string") {
|
||||
if (activeReferences.includes(schema.$ref)) return Number.POSITIVE_INFINITY;
|
||||
const target = resolveLocalReference(root, schema.$ref);
|
||||
if (target === undefined) return Number.POSITIVE_INFINITY;
|
||||
referenceDepth = inputDepth(target, root, [
|
||||
...activeReferences,
|
||||
schema.$ref,
|
||||
]);
|
||||
}
|
||||
const childDepths: number[] = [];
|
||||
for (const key of ["properties", "patternProperties", "dependentSchemas"]) {
|
||||
const group = schema[key];
|
||||
if (isRecord(group))
|
||||
for (const child of Object.values(group))
|
||||
childDepths.push(inputDepth(child, root, activeReferences));
|
||||
}
|
||||
for (const key of [
|
||||
"items",
|
||||
"additionalProperties",
|
||||
"contains",
|
||||
"not",
|
||||
"if",
|
||||
"then",
|
||||
"else",
|
||||
"propertyNames",
|
||||
"unevaluatedProperties",
|
||||
"unevaluatedItems",
|
||||
])
|
||||
childDepths.push(inputDepth(schema[key], root, activeReferences));
|
||||
for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"]) {
|
||||
const children = schema[key];
|
||||
if (Array.isArray(children))
|
||||
for (const child of children)
|
||||
childDepths.push(inputDepth(child, root, activeReferences));
|
||||
}
|
||||
const types = Array.isArray(schema.type) ? schema.type : [schema.type];
|
||||
const container = types.includes("object") || types.includes("array") ? 1 : 0;
|
||||
const composition = ["anyOf", "oneOf", "allOf"].some((key) =>
|
||||
Array.isArray(schema[key]),
|
||||
)
|
||||
? 1
|
||||
: 0;
|
||||
return Math.max(
|
||||
referenceDepth,
|
||||
container + composition + Math.max(0, ...childDepths),
|
||||
);
|
||||
}
|
||||
|
||||
function inputDepthViolations(
|
||||
tools: readonly { name: string; inputSchema: unknown }[],
|
||||
) {
|
||||
return tools.flatMap(({ name, inputSchema }) => {
|
||||
const depth = inputDepth(inputSchema);
|
||||
return depth > 10 ? [{ name, depth }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
async function withCatalog(
|
||||
verify: (client: Client, calls: ReadonlyMap<string, number>) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const server = new McpServer({ name: "wire-limits", version: "0" });
|
||||
const calls = new Map<string, number>();
|
||||
for (const contract of TOOL_CONTRACTS)
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
async () => {
|
||||
calls.set(contract.name, (calls.get(contract.name) ?? 0) + 1);
|
||||
return { content: [], isError: true };
|
||||
},
|
||||
);
|
||||
const client = new Client({ name: "wire-limits", version: "0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
await verify(client, calls);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
}
|
||||
|
||||
describe("complete catalog input compatibility profile (#919)", () => {
|
||||
it("follows shared and escaped references without treating data as schemas", () => {
|
||||
const diamond = {
|
||||
type: "object",
|
||||
properties: {
|
||||
left: { $ref: "#/$defs/a~1b~0c" },
|
||||
right: { $ref: "#/$defs/a~1b~0c" },
|
||||
},
|
||||
$defs: {
|
||||
"a/b~c": { type: "object", properties: { id: { type: "string" } } },
|
||||
unused: { $ref: "#/$defs/unused" },
|
||||
},
|
||||
examples: [{ $ref: "#" }],
|
||||
default: { $ref: "#" },
|
||||
};
|
||||
expect(inputDepth(diamond)).toBe(2);
|
||||
expect(
|
||||
inputDepth({ type: "object", properties: { child: { $ref: "#" } } }),
|
||||
).toBe(Number.POSITIVE_INFINITY);
|
||||
expect(
|
||||
inputDepth({
|
||||
type: "object",
|
||||
properties: {
|
||||
values: {
|
||||
anyOf: [
|
||||
{ type: "array", items: { type: "object" } },
|
||||
{ type: "null" },
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toBe(4);
|
||||
});
|
||||
|
||||
it("keeps every live and generated input within ten structural levels", async () => {
|
||||
await withCatalog(async (client) => {
|
||||
const { tools } = await client.listTools();
|
||||
expect(tools.map(({ name }) => name).sort()).toEqual(
|
||||
TOOL_CONTRACTS.map(({ name }) => name).sort(),
|
||||
);
|
||||
expect(inputDepthViolations(tools)).toEqual([]);
|
||||
expect(inputDepthViolations(GENERATED_MCP_TOOL_CATALOG)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it("describes capture round trips without altering domain or scenario schemas", () => {
|
||||
const contract = TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "compare_web_captures",
|
||||
);
|
||||
if (contract === undefined)
|
||||
throw new Error("Missing capture comparison contract");
|
||||
const original = z.toJSONSchema(browserCaptureComparisonInputSchema, {
|
||||
io: "input",
|
||||
});
|
||||
const projected = z.toJSONSchema(contract.inputSchema, { io: "input" });
|
||||
expect(inputDepth(original)).toBeGreaterThan(10);
|
||||
expect(inputDepth(projected)).toBeLessThanOrEqual(10);
|
||||
expect(isRecord(original.properties)).toBe(true);
|
||||
expect(isRecord(projected.properties)).toBe(true);
|
||||
if (!isRecord(original.properties) || !isRecord(projected.properties))
|
||||
throw new Error("Missing comparison properties");
|
||||
for (const key of ["normalization"])
|
||||
expect(projected.properties[key], key).toEqual(original.properties[key]);
|
||||
expect(z.toJSONSchema(webPageInspectionSchema).properties).toHaveProperty(
|
||||
"network",
|
||||
);
|
||||
for (const example of contract.examples)
|
||||
expect(contract.inputSchema.parse(example.input)).toEqual(
|
||||
browserCaptureComparisonInputSchema.parse(example.input),
|
||||
);
|
||||
const example = contract.examples[0];
|
||||
if (example === undefined) throw new Error("Missing scenario example");
|
||||
for (const malformed of [
|
||||
{ before_scenario: {}, after_scenario: {} },
|
||||
{
|
||||
...example.input,
|
||||
before: { inspection: {} },
|
||||
after: { inspection: {} },
|
||||
},
|
||||
{ ...example.input, __unexpected_root_key__: true },
|
||||
]) {
|
||||
const originalResult =
|
||||
browserCaptureComparisonInputSchema.safeParse(malformed);
|
||||
const projectedResult = contract.inputSchema.safeParse(malformed);
|
||||
expect(originalResult.success).toBe(false);
|
||||
expect(projectedResult.success).toBe(false);
|
||||
if (!originalResult.success && !projectedResult.success)
|
||||
expect(projectedResult.error.issues).toEqual(
|
||||
originalResult.error.issues,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects incomplete round-trip payloads before invoking the handler", async () => {
|
||||
await withCatalog(async (client, calls) => {
|
||||
const tool = (await client.listTools()).tools.find(
|
||||
({ name }) => name === "compare_web_captures",
|
||||
);
|
||||
if (tool === undefined)
|
||||
throw new Error("Missing advertised comparison tool");
|
||||
const incomplete = {
|
||||
before: { inspection: {} },
|
||||
after: { inspection: {} },
|
||||
};
|
||||
const validate = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
}).compile(tool.inputSchema);
|
||||
expect(validate(incomplete)).toBe(true);
|
||||
expect(
|
||||
browserCaptureComparisonInputSchema.safeParse(incomplete).success,
|
||||
).toBe(false);
|
||||
const result = await client.callTool({
|
||||
name: tool.name,
|
||||
arguments: incomplete,
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(calls.get(tool.name) ?? 0).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user