test(mcp): consolidate SDK schema checks and scenario ports

This commit is contained in:
morluto
2026-10-08 04:03:24 +08:00
parent 26829045d0
commit 9c3479ed95
13 changed files with 163 additions and 987 deletions
@@ -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()]);
}
-22
View File
@@ -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");
});
});
@@ -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" },
+1 -112
View File
@@ -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] =
-22
View File
@@ -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> = [];
+2 -7
View File
@@ -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");
});
});
@@ -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"),
+3 -247
View File
@@ -1,5 +1,3 @@
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";
@@ -12,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>>;
@@ -129,162 +81,13 @@ 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 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();
@@ -326,54 +129,6 @@ describe("official tool input contracts", () => {
});
describe("official Hopper proxy tools", () => {
it("executes every handler and projects omitted Python optionals to null", async () => {
const invocations: Invocation[] = [];
const client = await connect({
execute: (name, arguments_) => {
invocations.push({ name, arguments_ });
return Promise.resolve(ok(outputFor(name)));
},
});
for (const contract of OFFICIAL_TOOL_CONTRACTS) {
const result = await client.callTool({
name: contract.name,
arguments: VALID_INPUTS[contract.name],
});
expect(result.isError).not.toBe(true);
}
expect(
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),
);
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,
});
});
it("returns stable safe MCP error content", async () => {
const client = await connect({
execute: () => Promise.resolve(err(new HopperRemoteError(-1, "denied"))),
@@ -389,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_) => {
@@ -415,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(
@@ -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 build 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",
),
)
);
};
+103 -13
View File
@@ -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[] {
@@ -60,6 +61,74 @@ function expectStrictInputSchemaParity(
}
}
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);
const advertiseAndEnforceProcessEnvironmentKeyConstraint =
async (): Promise<void> => {
const contract = TOOL_CONTRACTS.find(
@@ -150,15 +219,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" });
@@ -180,6 +240,40 @@ describe("MCP JSON Schema validity", () => {
TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
expect(schemaErrors(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()]);
}
@@ -254,10 +348,6 @@ 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(