feat(mcp): add typed bounded analysis tools

This commit is contained in:
morluto
2026-07-12 18:59:53 +08:00
parent 7e4ae21d78
commit 893d2e2d05
16 changed files with 509 additions and 100 deletions
+20 -20
View File
@@ -1,4 +1,3 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { z } from "zod";
@@ -8,27 +7,28 @@ import {
SESSION_TOOL_CONTRACTS,
} from "../src/contracts/toolContracts.js";
const ORIGINAL_39_SHA256 =
"43ffddd91b775a3e00fb736c6b1a644210e5917a1e1f02745d0283ac6ab99db4";
describe("original tool contract snapshot", () => {
it("preserves every original name, description, kind, and complete JSON schema", () => {
const projection = [
...OFFICIAL_TOOL_CONTRACTS,
...ENHANCED_TOOL_CONTRACTS,
].map((contract) => ({
name: contract.name,
description: contract.description,
kind: contract.kind,
inputSchema: z.toJSONSchema(contract.inputSchema, {
describe("tool contract surface", () => {
it("advertises complete typed schemas and annotations for all analysis tools", () => {
const contracts = [...OFFICIAL_TOOL_CONTRACTS, ...ENHANCED_TOOL_CONTRACTS];
expect(contracts).toHaveLength(40);
for (const contract of contracts) {
const inputSchema = z.toJSONSchema(contract.inputSchema, {
target: "draft-07",
unrepresentable: "any",
}),
}));
expect(projection).toHaveLength(39);
expect(
createHash("sha256").update(JSON.stringify(projection)).digest("hex"),
).toBe(ORIGINAL_39_SHA256);
});
const outputSchema = z.toJSONSchema(contract.outputSchema, {
target: "draft-07",
unrepresentable: "any",
});
expect(inputSchema.type).toBe("object");
expect(outputSchema.type).toBe("object");
expect(contract.annotations).toMatchObject({
idempotentHint: true,
openWorldHint: false,
});
expect(typeof contract.annotations.readOnlyHint).toBe("boolean");
expect(typeof contract.annotations.destructiveHint).toBe("boolean");
}
});
it("keeps exactly three additive session contracts", () => {
+66 -10
View File
@@ -17,18 +17,29 @@ const PROCEDURES = {
"0x6": "prefix_TtOther",
};
const page = (values: Readonly<Record<string, string>>) => ({
items: Object.entries(values).map(([address, value]) => ({ address, value })),
offset: 0,
limit: 100,
total: Object.keys(values).length,
next_offset: null,
has_more: false,
});
const fixturePort = (): HopperToolPort => ({
callTool: (name, arguments_) => {
switch (name) {
case "list_procedures":
return Promise.resolve(ok(PROCEDURES));
return Promise.resolve(ok(page(PROCEDURES)));
case "list_names":
return Promise.resolve(
ok([
{ address: "0x10", name: "_OBJC_CLASS_$_Fixture" },
{ address: "0x11", name: "_OBJC_CLASS_$_Fixture" },
{ address: "0x12", name: "_OBJC_PROTOCOL_$_FixtureDelegate" },
]),
ok(
page({
"0x10": "_OBJC_CLASS_$_Fixture",
"0x11": "_OBJC_CLASS_$_Fixture",
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
}),
),
);
case "procedure_pseudo_code": {
const procedure = arguments_.procedure;
@@ -63,7 +74,7 @@ const fixturePort = (): HopperToolPort => ({
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(ok([{ address: "0x30", value: "hello" }]));
return Promise.resolve(ok(page({ "0x30": "hello" })));
default:
return Promise.resolve(ok(null));
}
@@ -90,6 +101,19 @@ const connect = async (hopper: HopperToolPort = fixturePort()) => {
};
const jsonResult = (result: CallToolResult): JsonValue => {
if (result.structuredContent === undefined)
throw new Error("Tool result omitted structured content");
const structured = jsonValueSchema.safeParse(result.structuredContent);
if (!structured.success)
throw new Error("Tool structured result was not JSON");
if (
typeof structured.data === "object" &&
structured.data !== null &&
!Array.isArray(structured.data) &&
"result" in structured.data
) {
return structured.data.result ?? null;
}
const text = result.content.find((item) => item.type === "text");
if (text?.type !== "text")
throw new Error("Tool result omitted text content");
@@ -100,10 +124,10 @@ const jsonResult = (result: CallToolResult): JsonValue => {
};
describe("enhanced MCP tools", () => {
it("lists the complete 31 plus 8 surface", async () => {
it("lists the complete 31 plus 9 surface", async () => {
const client = await connect();
const listed = await client.listTools();
expect(listed.tools).toHaveLength(39);
expect(listed.tools).toHaveLength(40);
expect(
listed.tools
.map(({ name }) => name)
@@ -114,7 +138,7 @@ describe("enhanced MCP tools", () => {
).toEqual(ENHANCED_TOOL_CONTRACTS.map(({ name }) => name).sort());
});
it("executes all eight tools through production registration", async () => {
it("executes all nine tools through production registration", async () => {
const client = await connect();
const calls = [
["swift_classes", { pattern: "Fixture" }],
@@ -125,6 +149,7 @@ describe("enhanced MCP tools", () => {
["analyze_swift_types", {}],
["find_xrefs_to_name", { name: "entry" }],
["binary_overview", {}],
["analyze_function", { procedure: "0x1" }],
] as const;
const results = [];
for (const [name, arguments_] of calls) {
@@ -152,6 +177,7 @@ describe("enhanced MCP tools", () => {
procedure_count: 6,
string_count: 1,
});
expect(results[8]).toBeNull();
});
it("bounds batch concurrency at the parsed maximum of 20", async () => {
@@ -181,6 +207,36 @@ describe("enhanced MCP tools", () => {
expect(maximum).toBe(20);
});
it("follows procedure pagination for whole-binary workflows", async () => {
const offsets: number[] = [];
const client = await connect({
callTool: (_name, arguments_) => {
const offset = arguments_.offset;
offsets.push(typeof offset === "number" ? offset : 0);
return Promise.resolve(
ok({
items: [
{
address: offset === 500 ? "0x2" : "0x1",
value: offset === 500 ? "_TtC4Last" : "_TtC5First",
},
],
offset: typeof offset === "number" ? offset : 0,
limit: 500,
total: 2,
next_offset: offset === 500 ? null : 500,
has_more: offset !== 500,
}),
);
},
});
const result = jsonResult(
await client.callTool({ name: "swift_classes", arguments: {} }),
);
expect(offsets).toEqual([0, 500]);
expect(result).toMatchObject({ count: 2 });
});
it("returns a typed tool error for malformed Hopper boundary values", async () => {
const client = await connect({
callTool: () => Promise.resolve(ok(["not", "a", "procedure", "map"])),
+50 -10
View File
@@ -39,6 +39,15 @@ const text = (result: CallToolResult): string => {
return content.text;
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
)
throw new Error("missing structured result");
return Object.fromEntries(Object.entries(result.structuredContent));
};
describe("full MCP integration with multi-tool sequences", () => {
it("executes a realistic workflow: list methods, decompile selected, get xrefs", async () => {
const client = await connect({
@@ -46,7 +55,17 @@ describe("full MCP integration with multi-tool sequences", () => {
switch (name) {
case "list_procedures":
return Promise.resolve(
ok({ "0x1000": "main", "0x2000": "helper" }),
ok({
items: [
{ address: "0x1000", value: "main" },
{ address: "0x2000", value: "helper" },
],
offset: 0,
limit: 100,
total: 2,
next_offset: null,
has_more: false,
}),
);
case "procedure_pseudo_code":
return Promise.resolve(
@@ -65,23 +84,31 @@ describe("full MCP integration with multi-tool sequences", () => {
arguments: {},
});
expect(listResult.isError).not.toBe(true);
const procedures = JSON.parse(text(listResult));
expect(procedures).toEqual({ "0x1000": "main", "0x2000": "helper" });
expect(structured(listResult)).toMatchObject({
items: [
{ address: "0x1000", value: "main" },
{ address: "0x2000", value: "helper" },
],
total: 2,
has_more: false,
});
const decompileResult = await client.callTool({
name: "procedure_pseudo_code",
arguments: { procedure: "0x1000" },
});
expect(text(decompileResult)).toBe("pseudo for 0x1000");
expect(structured(decompileResult)).toEqual({
result: "pseudo for 0x1000",
});
const xrefResult = await client.callTool({
name: "xrefs",
arguments: {},
});
expect(JSON.parse(text(xrefResult))).toEqual(["0x1000"]);
expect(structured(xrefResult)).toEqual({ result: ["0x1000"] });
});
it("preserves the complete 42-tool inventory with a session", async () => {
it("preserves the complete 43-tool inventory with a session", async () => {
const session = new BinarySession(
(_path) =>
({
@@ -104,7 +131,7 @@ describe("full MCP integration with multi-tool sequences", () => {
await client.connect(clientTransport);
const listed = await client.listTools();
expect(listed.tools).toHaveLength(42);
expect(listed.tools).toHaveLength(43);
const names = listed.tools.map((t) => t.name);
expect(names).toContain("open_binary");
expect(names).toContain("close_binary");
@@ -113,12 +140,12 @@ describe("full MCP integration with multi-tool sequences", () => {
expect(names).toContain("batch_decompile");
});
it("preserves the 39-tool inventory without a session", async () => {
it("preserves the 40-tool inventory without a session", async () => {
const client = await connect({
callTool: () => Promise.resolve(ok(null)),
});
const listed = await client.listTools();
expect(listed.tools).toHaveLength(39);
expect(listed.tools).toHaveLength(40);
const names = listed.tools.map((t) => t.name);
expect(names).toContain("binary_overview");
expect(names).toContain("batch_decompile");
@@ -145,7 +172,20 @@ describe("full MCP integration with multi-tool sequences", () => {
const client = await connect({
callTool: (name) => {
invocations.push(name);
return Promise.resolve(ok({ handled: name }));
return Promise.resolve(
ok(
["list_procedures", "list_strings"].includes(name)
? {
items: [],
offset: 0,
limit: 100,
total: 0,
next_offset: null,
has_more: false,
}
: { handled: name },
),
);
},
});
+16 -1
View File
@@ -68,6 +68,15 @@ const connect = async (hopper: HopperToolPort) => {
return client;
};
const page: JsonValue = {
items: [],
offset: 0,
limit: 100,
total: 0,
next_offset: null,
has_more: false,
};
describe("official Hopper proxy tools", () => {
it("lists exactly the 31 official contracts", async () => {
const client = await connect({
@@ -90,7 +99,13 @@ describe("official Hopper proxy tools", () => {
const client = await connect({
callTool: (name, arguments_) => {
invocations.push({ name, arguments_ });
return Promise.resolve(ok({ name, arguments: arguments_ }));
return Promise.resolve(
ok(
["list_procedures", "list_names", "list_strings"].includes(name)
? page
: { name, arguments: arguments_ },
),
);
},
});
+3 -3
View File
@@ -10,7 +10,7 @@ const fixturePath = fileURLToPath(
);
describe("production stdio runtime", () => {
it("starts the built entrypoint, lists 42 tools, calls one, and shuts down", async () => {
it("starts the built entrypoint, lists 43 tools, calls one, and shuts down", async () => {
const transport = new StdioClientTransport({
command: process.execPath,
args: [mainPath],
@@ -32,7 +32,7 @@ describe("production stdio runtime", () => {
try {
await client.connect(transport);
const tools = await client.listTools();
expect(tools.tools).toHaveLength(42);
expect(tools.tools).toHaveLength(43);
const result = await client.callTool({
name: "current_document",
arguments: {},
@@ -78,7 +78,7 @@ describe("production stdio runtime", () => {
try {
await client.connect(transport);
expect((await client.listTools()).tools).toHaveLength(42);
expect((await client.listTools()).tools).toHaveLength(43);
} finally {
await client.close();
await transport.close();
+1 -1
View File
@@ -44,7 +44,7 @@ describe("target-free MCP lifecycle", () => {
});
expect(before.isError).toBe(true);
expect(text(before)).toContain("NoBinaryOpenError");
expect((await mcp.listTools()).tools).toHaveLength(42);
expect((await mcp.listTools()).tools).toHaveLength(43);
expect(
(await mcp.callTool({ name: "open_binary", arguments: { path: first } }))
.isError,
+4 -4
View File
@@ -8,16 +8,16 @@ import {
} from "../src/contracts/toolContracts.js";
describe("tool contract inventory", () => {
it("preserves the original 39 contracts and adds three session tools", () => {
it("publishes 40 analysis contracts and three session tools", () => {
expect(OFFICIAL_TOOL_CONTRACTS).toHaveLength(31);
expect(ENHANCED_TOOL_CONTRACTS).toHaveLength(8);
expect(ENHANCED_TOOL_CONTRACTS).toHaveLength(9);
expect(SESSION_TOOL_CONTRACTS.map(({ name }) => name)).toEqual([
"open_binary",
"close_binary",
"binary_session",
]);
expect(TOOL_CONTRACTS).toHaveLength(42);
expect(new Set(TOOL_CONTRACTS.map(({ name }) => name)).size).toBe(42);
expect(TOOL_CONTRACTS).toHaveLength(43);
expect(new Set(TOOL_CONTRACTS.map(({ name }) => name)).size).toBe(43);
});
it("retains documented enhanced-tool limits at the input boundary", () => {