feat: evolve REA analysis platform

This commit is contained in:
morluto
2026-07-12 19:32:13 +08:00
parent 1f235cb52f
commit 4f18e26ee5
47 changed files with 1841 additions and 334 deletions
+43 -18
View File
@@ -3,10 +3,9 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
BinarySession,
type BinaryClient,
} from "../src/application/BinarySession.js";
import { BinarySession } from "../src/application/BinarySession.js";
import type { AnalysisClient } from "../src/application/AnalysisProvider.js";
import type { AnalysisProvider } from "../src/application/AnalysisProvider.js";
import { HopperStartError } from "../src/domain/errors.js";
import { err, ok } from "../src/domain/result.js";
@@ -18,9 +17,35 @@ afterEach(async () => {
});
describe("binary session", () => {
it("runs through a non-Hopper analysis provider", async () => {
const [first] = await targets();
const operations: string[] = [];
const provider: AnalysisProvider = {
identity: () => ({ id: "fixture", name: "Fixture", version: "1" }),
capabilities: () => ["fixture-analysis"],
createClient: () => ({
execute: (operation) => {
operations.push(operation);
return Promise.resolve(ok(operation));
},
close: () => Promise.resolve(),
}),
};
const session = new BinarySession(provider);
expect((await session.open(first)).ok).toBe(true);
expect(await session.execute("fixture_operation", {})).toEqual({
ok: true,
value: "fixture_operation",
});
expect(provider.identity().id).toBe("fixture");
expect(provider.capabilities()).toEqual(["fixture-analysis"]);
expect(operations).toEqual(["health", "fixture_operation"]);
await session.close();
});
it("requires an open binary and closes idempotently", async () => {
const session = new BinarySession(() => client());
expect((await session.callTool("binary_overview", {})).ok).toBe(false);
expect((await session.execute("binary_overview", {})).ok).toBe(false);
expect(await session.close()).toEqual({ ok: true, value: null });
});
@@ -34,7 +59,12 @@ describe("binary session", () => {
const session = new BinarySession(() => client(created++ === 1));
expect((await session.open(first)).ok).toBe(true);
expect((await session.open(second)).ok).toBe(false);
expect(session.status()).toMatchObject({ open: true });
expect(session.status()).toMatchObject({
open: true,
sha256:
"7692c3ad3540bb803c020b3aee66cd8887123234ea0c6e7143c0add73ff431ed",
architecture: null,
});
expect(JSON.stringify(session.status())).toContain("first.hop");
expect(created).toBe(3);
});
@@ -70,7 +100,7 @@ describe("binary session", () => {
return value;
});
await session.open(first);
const call = session.callTool("long", {});
const call = session.execute("long", {});
const switching = session.open(second);
await Promise.resolve();
expect(clients[0]?.closed).toBe(0);
@@ -106,11 +136,7 @@ describe("binary session", () => {
const session = new BinarySession(() => new TestClient(health.promise));
const opening = session.open(first);
const controller = new AbortController();
const call = session.callTool(
"overview",
{},
{ signal: controller.signal },
);
const call = session.execute("overview", {}, { signal: controller.signal });
controller.abort();
const result = await call;
expect(result.ok).toBe(false);
@@ -143,7 +169,7 @@ describe("binary session", () => {
let liveClients = 0;
let overlapped = false;
const session = new BinarySession(() => ({
callTool: () => {
execute: () => {
if (liveClients > 0) overlapped = true;
liveClients += 1;
return Promise.resolve(ok(null));
@@ -160,20 +186,19 @@ describe("binary session", () => {
});
});
const client = (fail = false): BinaryClient => ({
callTool: () =>
Promise.resolve(fail ? err(new HopperStartError()) : ok(null)),
const client = (fail = false): AnalysisClient => ({
execute: () => Promise.resolve(fail ? err(new HopperStartError()) : ok(null)),
close: () => Promise.resolve(),
});
class TestClient implements BinaryClient {
class TestClient implements AnalysisClient {
closed = 0;
constructor(
readonly pendingHealth?: Promise<ReturnType<typeof ok<null>>>,
readonly failHealth = false,
readonly pendingCall?: Promise<ReturnType<typeof ok<null>>>,
) {}
callTool(name: string) {
execute(name: string) {
if (name === "health")
return this.failHealth
? Promise.resolve(err(new HopperStartError()))
+4 -1
View File
@@ -77,7 +77,10 @@ describe("binary target I/O", () => {
directory = await mkdtemp(join(tmpdir(), "rea-target-"));
await writeFile(join(directory, "sample.hop"), "database");
await writeFile(join(directory, "text"), "hello");
expect((await parseBinaryTarget("sample.hop", directory)).ok).toBe(true);
const database = await parseBinaryTarget("sample.hop", directory);
expect(database.ok && database.value.sha256).toBe(
"3549b0028b75d981cdda2e573e9cb49dedc200185876df299f912b79f69dabd8",
);
expect((await parseBinaryTarget("text", directory)).ok).toBe(false);
expect((await parseBinaryTarget("missing", directory)).ok).toBe(false);
});
+32
View File
@@ -0,0 +1,32 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
const bridgeSource = await readFile(
new URL("../bridge/hopper_bridge.py", import.meta.url),
"utf8",
);
describe("Hopper bridge truthfulness", () => {
it("marks unavailable CFG successors instead of returning deceptive empty arrays", () => {
expect(bridgeSource).toContain('"successors": _unavailable(');
expect(bridgeSource).not.toContain('"successors": []');
});
it("does not fabricate non-writable and non-executable segment permissions", () => {
expect(bridgeSource).toContain('"writable": None');
expect(bridgeSource).toContain('"executable": None');
expect(bridgeSource).toContain('"permissions": _unavailable(');
expect(bridgeSource).not.toContain('"writable": False');
expect(bridgeSource).not.toContain('"executable": False');
});
it("uses Hopper containment and raw-reference APIs without inferring kinds", () => {
expect(bridgeSource).toContain("segment.getProcedureAtAddress(address)");
expect(bridgeSource).toContain("segment.getReferencesFromAddress(address)");
expect(bridgeSource).toContain("segment.getReferencesOfAddress(address)");
expect(bridgeSource).toContain(
"Hopper's public Python API does not classify reference kinds",
);
});
});
+32 -1
View File
@@ -6,11 +6,16 @@ import {
OFFICIAL_TOOL_CONTRACTS,
SESSION_TOOL_CONTRACTS,
} from "../src/contracts/toolContracts.js";
import {
enhancedOutputSchemas,
officialOutputSchemas,
sessionOutputSchemas,
} from "../src/contracts/toolOutputSchemas.js";
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);
expect(contracts).toHaveLength(43);
for (const contract of contracts) {
const inputSchema = z.toJSONSchema(contract.inputSchema, {
target: "draft-07",
@@ -40,4 +45,30 @@ describe("tool contract surface", () => {
{ name: "binary_session", kind: "session" },
]);
});
it("publishes a dedicated output schema and agent guidance for every tool", () => {
expect(Object.keys(officialOutputSchemas).sort()).toEqual(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
expect(Object.keys(enhancedOutputSchemas).sort()).toEqual(
ENHANCED_TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
expect(Object.keys(sessionOutputSchemas).sort()).toEqual(
SESSION_TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
for (const contract of [
...OFFICIAL_TOOL_CONTRACTS,
...ENHANCED_TOOL_CONTRACTS,
...SESSION_TOOL_CONTRACTS,
]) {
const schema = z.toJSONSchema(contract.outputSchema, {
target: "draft-07",
unrepresentable: "any",
});
expect(JSON.stringify(schema)).not.toContain('"result":{}');
expect(contract.description.length).toBeGreaterThan(100);
expect(contract.description).toMatch(/[.;]/u);
}
});
});
+4 -4
View File
@@ -4,17 +4,17 @@ import { describe, expect, it } from "vitest";
import { ok } from "../src/domain/result.js";
import { createServer } from "../src/server/createServer.js";
const hopper = {
callTool: () => Promise.resolve(ok(null)),
const analysis = {
execute: () => Promise.resolve(ok(null)),
};
describe("beta.3 server composition", () => {
it("constructs independent MCP server instances", () => {
expect(createServer(hopper)).not.toBe(createServer(hopper));
expect(createServer(analysis)).not.toBe(createServer(analysis));
});
it("does not advertise unavailable session tools", async () => {
const server = createServer(hopper);
const server = createServer(analysis);
const client = new Client({ name: "composition-test", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
+239 -15
View File
@@ -2,10 +2,10 @@ import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, describe, expect, it } from "vitest";
import type { HopperToolPort } from "../src/application/HopperToolPort.js";
import type { AnalysisOperationPort } from "../src/application/AnalysisProvider.js";
import { ENHANCED_TOOL_CONTRACTS } from "../src/contracts/toolContracts.js";
import { ok } from "../src/domain/result.js";
import { jsonValueSchema, type JsonValue } from "../src/hopper/protocol.js";
import { jsonValueSchema, type JsonValue } from "../src/domain/jsonValue.js";
import { createServer } from "../src/server/createServer.js";
const PROCEDURES = {
@@ -26,8 +26,8 @@ const page = (values: Readonly<Record<string, string>>) => ({
has_more: false,
});
const fixturePort = (): HopperToolPort => ({
callTool: (name, arguments_) => {
const fixturePort = (): AnalysisOperationPort => ({
execute: (name, arguments_) => {
switch (name) {
case "list_procedures":
return Promise.resolve(ok(page(PROCEDURES)));
@@ -67,6 +67,18 @@ const fixturePort = (): HopperToolPort => ({
);
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" }]),
@@ -75,12 +87,52 @@ const fixturePort = (): HopperToolPort => ({
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(ok(page({ "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(),
referenced_strings: { available: false, reason: "unsupported" },
referenced_names: { available: false, reason: "unsupported" },
basic_blocks: emptyBounded(),
}),
);
default:
return Promise.resolve(ok(null));
}
},
});
const emptyBounded = () => ({
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
});
const resources: Array<{ close(): Promise<void> }> = [];
afterEach(async () => {
@@ -89,8 +141,8 @@ afterEach(async () => {
);
});
const connect = async (hopper: HopperToolPort = fixturePort()) => {
const server = createServer(hopper);
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();
@@ -124,10 +176,10 @@ const jsonResult = (result: CallToolResult): JsonValue => {
};
describe("enhanced MCP tools", () => {
it("lists the complete 31 plus 9 surface", async () => {
it("lists the complete 33 plus 10 surface", async () => {
const client = await connect();
const listed = await client.listTools();
expect(listed.tools).toHaveLength(40);
expect(listed.tools).toHaveLength(43);
expect(
listed.tools
.map(({ name }) => name)
@@ -138,7 +190,7 @@ describe("enhanced MCP tools", () => {
).toEqual(ENHANCED_TOOL_CONTRACTS.map(({ name }) => name).sort());
});
it("executes all nine tools through production registration", async () => {
it("executes all ten tools through production registration", async () => {
const client = await connect();
const calls = [
["swift_classes", { pattern: "Fixture" }],
@@ -150,6 +202,7 @@ describe("enhanced MCP tools", () => {
["find_xrefs_to_name", { name: "entry" }],
["binary_overview", {}],
["analyze_function", { procedure: "0x1" }],
["trace_feature", { query: "hello", max_operations: 10 }],
] as const;
const results = [];
for (const [name, arguments_] of calls) {
@@ -177,14 +230,26 @@ describe("enhanced MCP tools", () => {
procedure_count: 6,
string_count: 1,
});
expect(results[8]).toBeNull();
expect(results[8]).toMatchObject({
procedure: { address: "0x1", name: "entry" },
pseudocode: { text: "return 0;" },
});
expect(results[9]).toMatchObject({
query: "hello",
search_mode: "literal",
truncated: false,
references: [
{ target_address: "0x30", source_address: "0x20" },
{ target_address: "0x30", source_address: "0x21" },
],
});
});
it("bounds batch concurrency at the parsed maximum of 20", async () => {
let active = 0;
let maximum = 0;
const hopper: HopperToolPort = {
callTool: async (name) => {
const analysis: AnalysisOperationPort = {
execute: async (name) => {
if (name !== "procedure_pseudo_code") return ok(null);
active += 1;
maximum = Math.max(maximum, active);
@@ -193,7 +258,7 @@ describe("enhanced MCP tools", () => {
return ok("pseudo");
},
};
const client = await connect(hopper);
const client = await connect(analysis);
const result = await client.callTool({
name: "batch_decompile",
arguments: {
@@ -210,7 +275,7 @@ describe("enhanced MCP tools", () => {
it("follows procedure pagination for whole-binary workflows", async () => {
const offsets: number[] = [];
const client = await connect({
callTool: (_name, arguments_) => {
execute: (_name, arguments_) => {
const offset = arguments_.offset;
offsets.push(typeof offset === "number" ? offset : 0);
return Promise.resolve(
@@ -237,9 +302,168 @@ describe("enhanced MCP tools", () => {
expect(result).toMatchObject({ count: 2 });
});
it("follows name pagination for exhaustive Objective-C discovery", async () => {
const offsets: number[] = [];
const client = await connect({
execute: (name, arguments_) => {
expect(name).toBe("list_names");
const offset =
typeof arguments_.offset === "number" ? arguments_.offset : 0;
offsets.push(offset);
return Promise.resolve(
ok({
items: [
{
address: offset === 500 ? "0x2" : "0x1",
value:
offset === 500 ? "_OBJC_CLASS_$_Last" : "_OBJC_CLASS_$_First",
},
],
offset,
limit: 500,
total: 2,
next_offset: offset === 500 ? null : 500,
has_more: offset !== 500,
}),
);
},
});
const result = jsonResult(
await client.callTool({ name: "get_objc_classes", arguments: {} }),
);
expect(offsets).toEqual([0, 500]);
expect(result).toMatchObject({ count: 2 });
});
it("honors overview detail and limit while reporting exhaustive totals", async () => {
const procedureOffsets: number[] = [];
const client = await connect({
execute: (name, arguments_) => {
switch (name) {
case "list_segments":
return Promise.resolve(
ok([
{ name: "__TEXT", start: "0x1000", end: "0x1800" },
{ name: "__DATA", start: "0x1800", end: "0x2000" },
]),
);
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
return Promise.resolve(
ok({
items: [{ address: "0x30", value: "first page only" }],
offset: 0,
limit: 100,
total: 700,
next_offset: 100,
has_more: true,
}),
);
case "list_procedures": {
const offset =
typeof arguments_.offset === "number" ? arguments_.offset : 0;
procedureOffsets.push(offset);
return Promise.resolve(
ok({
items: [
{
address: offset === 500 ? "0x2" : "0x1",
value: offset === 500 ? "last" : "first",
},
],
offset,
limit: 500,
total: 2,
next_offset: offset === 500 ? null : 500,
has_more: offset !== 500,
}),
);
}
default:
return Promise.resolve(ok(null));
}
},
});
const result = jsonResult(
await client.callTool({
name: "binary_overview",
arguments: { detail: "detailed", limit: 1 },
}),
);
expect(procedureOffsets).toEqual([0, 500]);
expect(result).toEqual({
document: "fixture",
detail: "detailed",
segments: [
{ name: "__TEXT", start: "0x1000", end: "0x1800", length: 2048 },
],
segment_count: 2,
procedure_count: 2,
string_count: 700,
});
});
it("rejects non-advancing pagination metadata", async () => {
const client = await connect({
execute: () =>
Promise.resolve(
ok({
items: [{ address: "0x1", value: "_TtC5First" }],
offset: 0,
limit: 500,
total: 2,
next_offset: 0,
has_more: true,
}),
),
});
const result = await client.callTool({
name: "swift_classes",
arguments: {},
});
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
expect(text?.type === "text" ? text.text : "").toContain(
"non-advancing pagination offset",
);
});
it("stops trace_feature at its explicit operation budget", async () => {
let operations = 0;
const client = await connect({
execute: () => {
operations += 1;
return Promise.resolve(
ok({
items: [{ address: "0x1", value: "needle" }],
offset: 0,
limit: 500,
total: 2,
next_offset: 1,
has_more: true,
}),
);
},
});
const result = jsonResult(
await client.callTool({
name: "trace_feature",
arguments: { query: "needle", max_operations: 1 },
}),
);
expect(operations).toBe(1);
expect(result).toMatchObject({
operations_used: 1,
operation_budget: 1,
truncated: true,
});
expect(JSON.stringify(result)).toContain("operation budget");
});
it("returns a typed tool error for malformed Hopper boundary values", async () => {
const client = await connect({
callTool: () => Promise.resolve(ok(["not", "a", "procedure", "map"])),
execute: () => Promise.resolve(ok(["not", "a", "procedure", "map"])),
});
const result = await client.callTool({
name: "swift_classes",
+56
View File
@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import type { BinaryTarget } from "../src/domain/binaryTarget.js";
import { createEvidence, evidenceSchema } from "../src/domain/evidence.js";
import { jsonValueSchema } from "../src/hopper/protocol.js";
const TARGET: BinaryTarget = {
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format: "mach-o",
architecture: "arm64",
availableArchitectures: ["arm64"],
loaderArgs: ["-l", "Mach-O", "--aarch64"],
};
describe("analysis evidence", () => {
it("preserves strict JSON inputs and results without timestamps", () => {
const evidence = createEvidence(TARGET, {
operation: "procedure_info",
parameters: { procedure: "0x1000", document: null },
result: { name: "main" },
});
expect(evidenceSchema.parse(evidence)).toEqual(evidence);
expect(jsonValueSchema.parse(evidence)).toEqual(evidence);
expect(evidence).toMatchObject({
schema_version: 1,
artifact: {
path: "/tmp/fixture",
sha256: "a".repeat(64),
architecture: "arm64",
},
provider: { id: "hopper", version: null },
operation: "procedure_info",
confidence: "observed",
limitations: [],
});
expect(evidence).not.toHaveProperty("timestamp");
expect(evidence).not.toHaveProperty("evidence_id");
});
it("marks missing fixed-target identity as unavailable", () => {
expect(
createEvidence(undefined, {
operation: "health",
parameters: {},
result: null,
}),
).toMatchObject({
artifact: null,
limitations: [
"Artifact identity is unavailable for this fixed-target adapter.",
],
});
});
});
+28
View File
@@ -44,6 +44,34 @@ const server = createServer((socket) => {
id: request.id,
error: { code: -32001, message: "safe fake failure" },
});
} else if (request.method === "current_document") {
send({ id: request.id, result: "fixture" });
} else if (request.method === "resolve_containing_procedure") {
send({
id: request.id,
result: {
query_address: request.params.address,
found: true,
procedure: { address: "0x1000", name: "fixture" },
},
});
} else if (request.method === "procedure_references") {
send({
id: request.id,
result: {
procedure: { address: "0x1000", name: "fixture" },
direction: request.params.direction ?? "outgoing",
references: {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
},
instructions_scanned: 1,
instruction_scan_truncated: false,
},
});
} else {
const delay = request.params?.delay ?? 0;
setTimeout(
+1 -1
View File
@@ -102,7 +102,7 @@ describe("HopperClient", () => {
const results = await Promise.all(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => client.callTool(name, {})),
);
expect(results).toHaveLength(31);
expect(results).toHaveLength(33);
expect(results.every((result) => result.ok)).toBe(true);
});
+37 -27
View File
@@ -2,11 +2,11 @@ import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, describe, expect, it } from "vitest";
import {
BinarySession,
type BinaryClient,
} from "../../src/application/BinarySession.js";
import type { HopperToolPort } from "../../src/application/HopperToolPort.js";
import { BinarySession } from "../../src/application/BinarySession.js";
import type {
AnalysisClient,
AnalysisOperationPort,
} from "../../src/application/AnalysisProvider.js";
import { HopperRemoteError } from "../../src/domain/errors.js";
import { err, ok } from "../../src/domain/result.js";
import { createServer } from "../../src/server/createServer.js";
@@ -19,8 +19,8 @@ afterEach(async () => {
);
});
const connect = async (hopper: HopperToolPort) => {
const server = createServer(hopper);
const connect = async (analysis: AnalysisOperationPort) => {
const server = createServer(analysis);
const client = new Client({
name: "integration-test",
version: "1.0.0",
@@ -51,7 +51,7 @@ const structured = (result: CallToolResult): Record<string, unknown> => {
describe("full MCP integration with multi-tool sequences", () => {
it("executes a realistic workflow: list methods, decompile selected, get xrefs", async () => {
const client = await connect({
callTool: (name, args) => {
execute: (name, args) => {
switch (name) {
case "list_procedures":
return Promise.resolve(
@@ -85,19 +85,26 @@ describe("full MCP integration with multi-tool sequences", () => {
});
expect(listResult.isError).not.toBe(true);
expect(structured(listResult)).toMatchObject({
items: [
{ address: "0x1000", value: "main" },
{ address: "0x2000", value: "helper" },
],
total: 2,
has_more: false,
artifact: null,
operation: "list_procedures",
provider: { id: "hopper", version: null },
result: {
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(structured(decompileResult)).toEqual({
expect(structured(decompileResult)).toMatchObject({
operation: "procedure_pseudo_code",
parameters: { document: null, procedure: "0x1000" },
result: "pseudo for 0x1000",
});
@@ -105,19 +112,22 @@ describe("full MCP integration with multi-tool sequences", () => {
name: "xrefs",
arguments: {},
});
expect(structured(xrefResult)).toEqual({ result: ["0x1000"] });
expect(structured(xrefResult)).toMatchObject({
operation: "xrefs",
result: ["0x1000"],
});
});
it("preserves the complete 43-tool inventory with a session", async () => {
it("preserves the complete 46-tool inventory with a session", async () => {
const session = new BinarySession(
(_path) =>
({
callTool: () => Promise.resolve(ok(null)),
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(),
}) satisfies BinaryClient,
}) satisfies AnalysisClient,
);
const server = createServer(
{ callTool: () => Promise.resolve(ok(null)) },
{ execute: () => Promise.resolve(ok(null)) },
session,
);
const client = new Client({
@@ -131,7 +141,7 @@ describe("full MCP integration with multi-tool sequences", () => {
await client.connect(clientTransport);
const listed = await client.listTools();
expect(listed.tools).toHaveLength(43);
expect(listed.tools).toHaveLength(46);
const names = listed.tools.map((t) => t.name);
expect(names).toContain("open_binary");
expect(names).toContain("close_binary");
@@ -140,12 +150,12 @@ describe("full MCP integration with multi-tool sequences", () => {
expect(names).toContain("batch_decompile");
});
it("preserves the 40-tool inventory without a session", async () => {
it("preserves the 43-tool inventory without a session", async () => {
const client = await connect({
callTool: () => Promise.resolve(ok(null)),
execute: () => Promise.resolve(ok(null)),
});
const listed = await client.listTools();
expect(listed.tools).toHaveLength(40);
expect(listed.tools).toHaveLength(43);
const names = listed.tools.map((t) => t.name);
expect(names).toContain("binary_overview");
expect(names).toContain("batch_decompile");
@@ -154,7 +164,7 @@ describe("full MCP integration with multi-tool sequences", () => {
it("propagates remote Hopper errors with structured content", async () => {
const client = await connect({
callTool: () =>
execute: () =>
Promise.resolve(err(new HopperRemoteError(-32000, "bridge timeout"))),
});
@@ -170,7 +180,7 @@ describe("full MCP integration with multi-tool sequences", () => {
it("handles concurrent tool calls without corruption", async () => {
const invocations: string[] = [];
const client = await connect({
callTool: (name) => {
execute: (name) => {
invocations.push(name);
return Promise.resolve(
ok(
@@ -183,7 +193,7 @@ describe("full MCP integration with multi-tool sequences", () => {
next_offset: null,
has_more: false,
}
: { handled: name },
: [],
),
);
},
+63 -15
View File
@@ -1,11 +1,11 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, describe, expect, it } from "vitest";
import type { HopperToolPort } from "../src/application/HopperToolPort.js";
import type { AnalysisOperationPort } from "../src/application/AnalysisProvider.js";
import { OFFICIAL_TOOL_CONTRACTS } from "../src/contracts/toolContracts.js";
import { HopperRemoteError } from "../src/domain/errors.js";
import { err, ok } from "../src/domain/result.js";
import type { JsonValue } from "../src/hopper/protocol.js";
import type { JsonValue } from "../src/domain/jsonValue.js";
import { createServer } from "../src/server/createServer.js";
const VALID_INPUTS: Readonly<
@@ -31,7 +31,9 @@ const VALID_INPUTS: Readonly<
procedure_callees: { procedure: "main" },
procedure_callers: { procedure: "main" },
procedure_info: { procedure: "main" },
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" },
@@ -57,8 +59,8 @@ afterEach(async () => {
);
});
const connect = async (hopper: HopperToolPort) => {
const server = createServer(hopper);
const connect = async (analysis: AnalysisOperationPort) => {
const server = createServer(analysis);
const client = new Client({ name: "contract-test", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
@@ -77,10 +79,62 @@ const page: JsonValue = {
has_more: false,
};
const outputFor = (name: string): JsonValue => {
if (["list_procedures", "list_names", "list_strings"].includes(name))
return page;
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 {};
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 === "procedure_references")
return {
procedure: { address: "0x1000", name: "main" },
direction: "outgoing",
references: {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
},
instructions_scanned: 1,
instruction_scan_truncated: false,
};
return name.includes("address") ? "0x1000" : "fixture";
};
describe("official Hopper proxy tools", () => {
it("lists exactly the 31 official contracts", async () => {
it("lists every official contract", async () => {
const client = await connect({
callTool: () => Promise.resolve(ok(null)),
execute: () => Promise.resolve(ok(null)),
});
const listed = await client.listTools();
const officialNames = new Set(
@@ -97,15 +151,9 @@ describe("official Hopper proxy tools", () => {
it("executes every handler and projects omitted Python optionals to null", async () => {
const invocations: Invocation[] = [];
const client = await connect({
callTool: (name, arguments_) => {
execute: (name, arguments_) => {
invocations.push({ name, arguments_ });
return Promise.resolve(
ok(
["list_procedures", "list_names", "list_strings"].includes(name)
? page
: { name, arguments: arguments_ },
),
);
return Promise.resolve(ok(outputFor(name)));
},
});
@@ -137,7 +185,7 @@ describe("official Hopper proxy tools", () => {
it("returns stable safe MCP error content", async () => {
const client = await connect({
callTool: () => Promise.resolve(err(new HopperRemoteError(-1, "denied"))),
execute: () => Promise.resolve(err(new HopperRemoteError(-1, "denied"))),
});
const result = await client.callTool({
name: "list_documents",
+40
View File
@@ -0,0 +1,40 @@
import { readdir, readFile } from "node:fs/promises";
import { join, relative } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
const sourceRoot = new URL("../src/", import.meta.url);
describe("provider-neutral architecture", () => {
it("keeps Hopper imports behind its adapter and composition root", async () => {
const forbiddenRoots = ["domain", "contracts", "server", "application"];
const violations: string[] = [];
for (const root of forbiddenRoots) {
for (const file of await typescriptFiles(
fileURLToPath(new URL(`${root}/`, sourceRoot)),
)) {
if (root === "application" && file.endsWith("/runtime.ts")) continue;
const source = await readFile(file, "utf8");
if (/from\s+["'][^"']*\/hopper\//u.test(source)) {
violations.push(relative(fileURLToPath(sourceRoot), file));
}
}
}
expect(violations).toEqual([]);
});
});
const typescriptFiles = async (
directory: string,
): Promise<readonly string[]> => {
const entries = await readdir(directory, { withFileTypes: true });
const nested = await Promise.all(
entries.map(async (entry) => {
const path = join(directory, entry.name);
if (entry.isDirectory()) return typescriptFiles(path);
return entry.isFile() && entry.name.endsWith(".ts") ? [path] : [];
}),
);
return nested.flat();
};
+3 -3
View File
@@ -22,9 +22,9 @@ describe("localized README product facts", () => {
expect(content).toContain('"args": ["-y", "@morluto/rea", "mcp"]');
expect(content).toContain("Node.js 22");
expect(content).toContain("macOS 12");
expect(content).toMatch(/\b43\b/u);
expect(content).toMatch(/\b31\b/u);
expect(content).toMatch(/\b9\b/u);
expect(content).toMatch(/\b46\b/u);
expect(content).toMatch(/\b33\b/u);
expect(content).toMatch(/\b10\b/u);
expect(content).toMatch(/\b3\b/u);
},
);
+3 -3
View File
@@ -10,7 +10,7 @@ const fixturePath = fileURLToPath(
);
describe("production stdio runtime", () => {
it("starts the built entrypoint, lists 43 tools, calls one, and shuts down", async () => {
it("starts the built entrypoint, lists 46 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(43);
expect(tools.tools).toHaveLength(46);
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(43);
expect((await client.listTools()).tools).toHaveLength(46);
} finally {
await client.close();
await transport.close();
+8 -8
View File
@@ -5,10 +5,8 @@ import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, describe, expect, it } from "vitest";
import {
BinarySession,
type BinaryClient,
} from "../src/application/BinarySession.js";
import { BinarySession } from "../src/application/BinarySession.js";
import type { AnalysisClient } from "../src/application/AnalysisProvider.js";
import { ok } from "../src/domain/result.js";
import { createServer } from "../src/server/createServer.js";
@@ -44,7 +42,7 @@ describe("target-free MCP lifecycle", () => {
});
expect(before.isError).toBe(true);
expect(text(before)).toContain("NoBinaryOpenError");
expect((await mcp.listTools()).tools).toHaveLength(43);
expect((await mcp.listTools()).tools).toHaveLength(46);
expect(
(await mcp.callTool({ name: "open_binary", arguments: { path: first } }))
.isError,
@@ -64,9 +62,11 @@ describe("target-free MCP lifecycle", () => {
});
});
const client = (path: string, closed: string[]): BinaryClient => ({
callTool: (name) =>
Promise.resolve(ok(name === "health" ? null : { path, name })),
const client = (path: string, closed: string[]): AnalysisClient => ({
execute: (name) =>
Promise.resolve(
ok(name === "health" ? null : name === "current_document" ? path : null),
),
close: () => {
closed.push(path);
return Promise.resolve();
+5 -5
View File
@@ -8,16 +8,16 @@ import {
} from "../src/contracts/toolContracts.js";
describe("tool contract inventory", () => {
it("publishes 40 analysis contracts and three session tools", () => {
expect(OFFICIAL_TOOL_CONTRACTS).toHaveLength(31);
expect(ENHANCED_TOOL_CONTRACTS).toHaveLength(9);
it("publishes 43 analysis contracts and three session tools", () => {
expect(OFFICIAL_TOOL_CONTRACTS).toHaveLength(33);
expect(ENHANCED_TOOL_CONTRACTS).toHaveLength(10);
expect(SESSION_TOOL_CONTRACTS.map(({ name }) => name)).toEqual([
"open_binary",
"close_binary",
"binary_session",
]);
expect(TOOL_CONTRACTS).toHaveLength(43);
expect(new Set(TOOL_CONTRACTS.map(({ name }) => name)).size).toBe(43);
expect(TOOL_CONTRACTS).toHaveLength(46);
expect(new Set(TOOL_CONTRACTS.map(({ name }) => name)).size).toBe(46);
});
it("retains documented enhanced-tool limits at the input boundary", () => {