feat(ida): add read-only GUI and headless MCP providers (#754)

This commit is contained in:
N0zoM1z0
2026-10-07 01:47:05 +08:00
committed by GitHub
parent c8e66c704a
commit 8238232485
50 changed files with 3770 additions and 43 deletions
@@ -37,6 +37,7 @@ import {
GHIDRA_PROVIDER_TOOL_CONTRACTS,
} from "../../../src/ghidra/GhidraProvider.js";
import { NATIVE_MACOS_PROVIDER_IDENTITY } from "../../../src/native/NativeMacOSProvider.js";
import { IDA_PROVIDER_IDENTITY } from "../../../src/ida/IdaProvider.js";
import {
assertDocumentationFacts,
documentationFactIssues,
@@ -101,6 +102,7 @@ describe("canonical product catalog", () => {
BINWALK_PROVIDER_IDENTITY,
UNBLOB_PROVIDER_IDENTITY,
GHIDRA_PROVIDER_IDENTITY,
IDA_PROVIDER_IDENTITY,
NATIVE_MACOS_PROVIDER_IDENTITY,
ARTIFACT_GRAPH_PROVIDER,
MANAGED_STATIC_PROVIDER,
@@ -49,7 +49,7 @@ describe("direct analysis snapshot files", () => {
details: {
selection_reason: "unknown_provider",
requested_provider_id: "request-provider",
candidate_ids: ["ghidra", "hopper"],
candidate_ids: ["ghidra", "hopper", "ida"],
},
});
});
+7 -4
View File
@@ -97,7 +97,7 @@ describe("Ghidra MCP evidence parity", () => {
);
expect(analyzed).toMatchObject({
operation: "analyze_function",
provider: { id: "rea-workflow", version: "1" },
provider: { id: "ghidra", version: "12.1.4" },
normalized_result: {
procedure: {
address: "0x401000",
@@ -121,9 +121,12 @@ describe("Ghidra MCP evidence parity", () => {
),
]),
},
limitations: [
"Derived by an REA workflow from one or more provider observations.",
],
limitations: expect.arrayContaining([
expect.stringContaining("default auto-analysis complete"),
expect.stringContaining(
"original executable bytes are never written",
),
]),
});
const directAnalyzed = await new EnhancedTools(session).execute(
"analyze_function",
+137
View File
@@ -0,0 +1,137 @@
import { createServer } from "node:http";
import { afterEach, expect, it } from "vitest";
import { z } from "zod";
import { createIdaMcpConnection } from "../../../src/ida/IdaMcpConnection.js";
import type { IdaMcpConnection } from "../../../src/ida/IdaMcpConnection.js";
const cleanups: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
});
const requestSchema = z.object({
id: z.union([z.string(), z.number()]).optional(),
method: z.string(),
params: z
.object({
protocolVersion: z.string().optional(),
cursor: z.string().optional(),
})
.passthrough()
.optional(),
});
const fixture = async (redirectUrl?: string, cycle = false) => {
const methods: string[] = [];
const headers: (string | undefined)[] = [];
const server = createServer(async (request, response) => {
if (redirectUrl !== undefined) {
response.writeHead(307, { Location: redirectUrl });
response.end();
return;
}
if (request.method !== "POST") {
response.writeHead(405);
response.end();
return;
}
let body = "";
for await (const chunk of request) body += String(chunk);
const input = requestSchema.parse(JSON.parse(body));
methods.push(input.method);
headers.push(request.headers.authorization);
if (input.id === undefined) {
response.writeHead(202);
response.end();
return;
}
const result =
input.method === "initialize"
? {
protocolVersion: input.params?.protocolVersion,
capabilities: { tools: {} },
serverInfo: {
name: "ida-transport-fixture",
version: "observed-server-version",
},
}
: input.method === "tools/list"
? {
tools: [
{
name: input.params?.cursor === undefined ? "first" : "second",
inputSchema: { type: "object", properties: {} },
},
],
...(input.params?.cursor === undefined
? { nextCursor: "next-page" }
: cycle
? {
nextCursor:
input.params.cursor === "next-page"
? "other-page"
: "next-page",
}
: {}),
}
: { content: [], structuredContent: { observed: true } };
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify({ jsonrpc: "2.0", id: input.id, result }));
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
cleanups.push(
() =>
new Promise<void>((resolve, reject) => {
server.close((error) =>
error === undefined ? resolve() : reject(error),
);
server.closeAllConnections();
}),
);
const address = server.address();
if (address === null || typeof address === "string")
throw new Error("Missing HTTP fixture address");
const connection: IdaMcpConnection = createIdaMcpConnection({
url: `http://127.0.0.1:${address.port}/mcp`,
headers: { Authorization: "Bearer transport-fixture-secret" },
mode: "headless",
timeoutMs: 2000,
});
cleanups.push(() => connection.close());
return {
connection,
methods,
headers,
url: `http://127.0.0.1:${address.port}/mcp`,
};
};
it("uses the pinned SDK for a local Streamable HTTP handshake, paged discovery, structured results, and configured authentication", async () => {
const { connection, methods, headers } = await fixture();
expect(await connection.connect()).toEqual(["first", "second"]);
expect(connection.serverInfo()).toEqual({
name: "ida-transport-fixture",
version: "observed-server-version",
});
expect(await connection.call("first", {})).toEqual({ observed: true });
expect(methods).toContain("notifications/initialized");
expect(methods.filter((name) => name === "tools/list")).toHaveLength(2);
expect(
headers.every((value) => value === "Bearer transport-fixture-secret"),
).toBe(true);
});
it("rejects redirects instead of forwarding transport credentials to another endpoint", async () => {
const destination = await fixture();
const { connection } = await fixture(destination.url);
await expect(connection.connect()).rejects.toThrow();
expect(destination.headers).toEqual([]);
});
it("rejects nonterminating SDK pagination instead of returning a partial tool catalog", async () => {
const { connection, methods } = await fixture(undefined, true);
await expect(connection.connect()).rejects.toThrow(
"pagination did not terminate",
);
expect(
methods.filter((method) => method === "tools/list").length,
).toBeGreaterThan(2);
});
+159
View File
@@ -0,0 +1,159 @@
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { IdaProvider } from "../../src/ida/IdaProvider.js";
import { createIdaTarget, RecordingIdaMcp } from "../fixtures/idaMcp.js";
import { createTestBinarySession } from "../fixtures/binarySession.js";
import { parseConfig } from "../../src/config.js";
import {
createAnalysisSnapshotEntry,
snapshotBinding,
snapshotTarget,
} from "../../src/domain/analysisSnapshot.js";
import { createEvidence } from "../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../src/domain/evidenceBundle.js";
import { createAnalysisExecution } from "../../src/application/AnalysisProvider.js";
import { IDA_PROVIDER_IDENTITY } from "../../src/ida/IdaProvider.js";
const roots: string[] = [];
afterEach(async () => {
for (const root of roots.splice(0))
await rm(root, { recursive: true, force: true });
});
describe("IDA provider composition", () => {
it("discovers without launching and commits adapter semantics without persisting credentials", async () => {
const { root, target } = await createIdaTarget();
roots.push(root);
const path = join(root, "registration.json");
await writeFile(
path,
JSON.stringify({
url: "http://127.0.0.1:8745/mcp",
headers: { Authorization: "Bearer private-fixture-token" },
mode: "headless",
}),
);
const config = parseConfig({ REA_IDA_MCP_CONFIG: path });
if (!config.ok) throw config.error;
const producer = new RecordingIdaMcp(target, "headless");
const provider = new IdaProvider(config.value, () => producer);
expect(provider.inspectAvailability()).toMatchObject({
status: "available",
diagnostics: { live_connection_probed: false },
});
const resolution = await provider.resolveAnalysisProfile(target);
expect(resolution.ok).toBe(true);
if (!resolution.ok) throw resolution.error;
expect(resolution.value.profile.parameters).toMatchObject({
engine_version: null,
upstream_distribution_version: null,
cache_policy: "live",
version_scope: "rea-ida-adapter",
});
expect(JSON.stringify(resolution)).not.toContain("private-fixture-token");
expect(producer.connects).toBe(0);
expect(
provider
.capabilities()
.find(({ operation }) => operation === "procedure_callers")?.available,
).toBe(false);
});
it("re-observes externally mutable state even when a document is explicit and a snapshot is imported", async () => {
const { root, target } = await createIdaTarget();
roots.push(root);
const path = join(root, "registration.json");
await writeFile(path, JSON.stringify({ command: "fixture" }));
const config = parseConfig({ REA_IDA_MCP_CONFIG: path });
if (!config.ok) throw config.error;
const producer = new RecordingIdaMcp(target);
const session = createTestBinarySession(
new IdaProvider(config.value, () => producer),
);
expect((await session.open(target.path)).ok).toBe(true);
const query = { procedure: "main", document: target.path };
const first = await session.execute("procedure_pseudo_code", query);
expect(first.ok && first.value.result).toContain("42");
const snapshot = session.exportAnalysisSnapshot();
expect(snapshot.ok).toBe(true);
if (!snapshot.ok) throw snapshot.error;
expect(snapshot.value.entries).toEqual([]);
const profile = session.analysisProfile();
if (profile === undefined) throw new Error("Missing profile");
const cached = createAnalysisExecution(
"stale output",
IDA_PROVIDER_IDENTITY,
{
analysisProfile: profile,
subject: {
path: target.path,
sha256: target.sha256,
format: target.format,
...(target.architecture === undefined
? {}
: { architecture: target.architecture }),
},
},
);
snapshot.value.entries.push(
createAnalysisSnapshotEntry({
target: snapshotTarget(target),
binding: snapshotBinding(profile),
operation: "procedure_pseudo_code",
parameters: query,
execution: cached,
}),
);
snapshot.value.evidence_bundle = createEvidenceBundle([
...snapshot.value.evidence_bundle.records,
createEvidence(target, IDA_PROVIDER_IDENTITY, {
operation: "procedure_pseudo_code",
parameters: query,
result: cached.result,
rawResult: cached.rawResult,
analysisProfile: profile,
}),
]);
expect(session.importAnalysisSnapshot(snapshot.value).ok).toBe(true);
expect(session.allowsSnapshotReplay("procedure_pseudo_code")).toBe(false);
expect(session.allowsSnapshotReplay("binary_overview")).toBe(false);
producer.pseudocode = "int main(void) { return 99; }";
const second = await session.execute("procedure_pseudo_code", query);
expect(second.ok && second.value.result).toContain("99");
expect(
producer.calls.filter(({ name }) => name === "decompile_function"),
).toHaveLength(2);
await session.close();
expect(producer.closes).toBe(1);
});
it("rejects unsupported target kinds and incomplete upstream compatibility profiles with useful reasons", async () => {
const { root, target } = await createIdaTarget();
roots.push(root);
const path = join(root, "registration.json");
await writeFile(
path,
JSON.stringify({
command: "fixture",
mode: "headless",
workspaceRoot: root,
}),
);
const config = parseConfig({ REA_IDA_MCP_CONFIG: path });
if (!config.ok) throw config.error;
const producer = new RecordingIdaMcp(target);
const provider = new IdaProvider(config.value, () => producer);
expect(
provider.inspectTargetSupport({
path: target.path,
sha256: target.sha256,
kind: "database",
format: "analysis-database",
}),
).toMatchObject({ status: "unsupported", code: "target_kind_unsupported" });
const session = createTestBinarySession(provider);
const opened = await session.open(target.path);
expect(opened.ok).toBe(false);
if (!opened.ok) expect(opened.error.message).toContain("missing tools");
expect(producer.closes).toBe(1);
});
});
+15
View File
@@ -0,0 +1,15 @@
#ifdef _WIN32
#define REA_EXPORT __declspec(dllexport)
#define REA_NOINLINE __declspec(noinline)
#else
#define REA_EXPORT __attribute__((visibility("default")))
#define REA_NOINLINE __attribute__((noinline))
#endif
REA_EXPORT REA_NOINLINE int rea_fixture_add(int left, int right) {
return left + right + 7;
}
int main(void) {
return rea_fixture_add(11, 24);
}
@@ -0,0 +1,84 @@
import { rm } from "node:fs/promises";
import { afterEach, describe, expect, it } from "vitest";
import { createIdaTarget, RecordingIdaMcp } from "../../fixtures/idaMcp.js";
import { IdaSessionClient } from "../../../src/ida/IdaSessionClient.js";
import { IDA_OPERATIONS } from "../../../src/ida/IdaProviderCapabilities.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import type { JsonValue } from "../../../src/domain/jsonValue.js";
import { toCallToolResult } from "../../../src/server/toolResult.js";
const roots: string[] = [];
afterEach(async () => {
for (const root of roots.splice(0))
await rm(root, { recursive: true, force: true });
});
const parametersFor = (
operation: string,
): Readonly<Record<string, JsonValue>> => {
if (operation.startsWith("search_")) return { pattern: "a.b" };
if (operation === "xrefs") return { address: "0x1000" };
if (operation.startsWith("list_")) return { document: null };
return { procedure: "main" };
};
describe.each(["attached", "headless"] as const)(
"IDA %s caller-visible contracts",
(mode) => {
it.each(IDA_OPERATIONS)(
"serializes %s against its named advertised output contract",
async (operation) => {
const { root, target } = await createIdaTarget();
roots.push(root);
const client = new IdaSessionClient(
{
command: "fixture",
args: [],
env: {},
mode,
workspaceRoot: root,
timeoutMs: 1000,
},
target,
new RecordingIdaMcp(target, mode),
);
try {
const parameters = parametersFor(operation);
const execution = await client.execute(operation, parameters);
if (mode === "headless" && operation === "procedure_callers") {
expect(execution.ok).toBe(false);
if (!execution.ok)
expect(execution.error._tag).toBe(
"AnalysisCapabilityUnavailableError",
);
return;
}
if (!execution.ok) throw execution.error;
const evidence = createEvidence(target, execution.value.provider, {
operation,
parameters,
result: execution.value.result,
rawResult: execution.value.rawResult,
locations: execution.value.locations,
limitations: execution.value.limitations,
});
const contract = toolContract(operation);
const serialized = toCallToolResult(
{ ok: true, value: evidence },
contract,
);
expect(
contract.outputSchema.safeParse(serialized.structuredContent)
.success,
).toBe(true);
expect(serialized.content[0]).toEqual({
type: "text",
text: JSON.stringify(serialized.structuredContent),
});
} finally {
await client.close();
}
},
);
},
);
+262
View File
@@ -0,0 +1,262 @@
import { createHash } from "node:crypto";
import { mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { BinaryTarget } from "../../src/domain/binaryTarget.js";
import type { JsonValue } from "../../src/domain/jsonValue.js";
import type { IdaMcpConnection } from "../../src/ida/IdaMcpConnection.js";
import { elf } from "../../src/domain/binaryTarget.fixture.js";
/** Create a test-owned executable and workspace parent without invoking an engine. */
export const createIdaTarget = async () => {
const root = await mkdtemp(join(tmpdir(), "rea-ida-test-"));
const path = join(root, "target.elf");
const bytes = elf(2, 1, 62);
await writeFile(path, bytes);
const target: BinaryTarget = {
path,
sha256: createHash("sha256").update(bytes).digest("hex"),
kind: "executable",
format: "elf",
architecture: "x86_64",
availableArchitectures: ["x86_64"],
};
return { root, target };
};
const legacyNames = [
"get_metadata",
"list_functions",
"list_strings",
"get_function_by_name",
"get_function_by_address",
"decompile_function",
"disassemble_function",
"get_callers",
"get_callees",
"get_xrefs_to",
];
const modernNames = [
"idb_open",
"idb_list",
"idb_close",
"server_health",
"list_funcs",
"lookup_funcs",
"find_regex",
"decompile",
"disasm",
"callees",
"xrefs_to",
];
/** Stateful producer fixture at the real connection seam; no module mocking. */
export class RecordingIdaMcp implements IdaMcpConnection {
readonly calls: {
name: string;
args: Readonly<Record<string, JsonValue>>;
}[] = [];
connects = 0;
closes = 0;
inputSha256: string;
inputPath: string;
imageBase = "0x1000";
pseudocode = "int main(void) { return 42; }";
owned = true;
active = true;
database: string | undefined;
failClose = false;
beforeCall?: (
name: string,
args: Readonly<Record<string, JsonValue>>,
) => Promise<void>;
overrideCall?: (
name: string,
args: Readonly<Record<string, JsonValue>>,
) => JsonValue | undefined;
constructor(
readonly target: BinaryTarget,
readonly mode: "attached" | "headless" = "attached",
) {
this.inputSha256 = target.sha256;
this.inputPath = target.path;
}
async connect() {
this.connects += 1;
return this.mode === "attached" ? legacyNames : modernNames;
}
serverInfo() {
return { name: "upstream-fixture", version: "sdk-version-is-not-ida" };
}
async close() {
this.closes += 1;
}
async call(
name: string,
args: Readonly<Record<string, JsonValue>>,
): Promise<JsonValue> {
this.calls.push({ name, args: structuredClone(args) });
await this.beforeCall?.(name, args);
const overridden = this.overrideCall?.(name, args);
if (overridden !== undefined) return overridden;
if (["idb_open", "idb_list", "idb_close", "server_health"].includes(name))
return this.lifecycle(name, args);
return this.read(name);
}
private read(name: string): JsonValue {
const fn = { address: "0x1000", name: "main", size: "0x20" };
const asm = {
name: "main",
start_ea: "0x1000",
lines: [
{
address: "0x1000",
instruction: "ret",
comments: ["observed comment"],
},
],
return_type: "int",
arguments: [],
};
switch (name) {
case "get_metadata":
return {
path: this.inputPath,
module: "target.elf",
sha256: this.inputSha256,
base: this.imageBase,
};
case "list_functions":
return { data: [fn], next_offset: null };
case "list_funcs":
return [
{
data: [{ addr: fn.address, name: fn.name, size: fn.size }],
next_offset: null,
},
];
case "get_function_by_address":
return { ...fn, address: "0x1004" };
case "get_function_by_name":
return fn;
case "lookup_funcs":
return [
{
query: "main",
fn: { addr: fn.address, name: fn.name, size: fn.size },
error: null,
},
];
case "decompile_function":
return this.pseudocode;
case "decompile":
return { code: this.pseudocode, cursor: { done: true } };
case "disassemble_function":
return asm;
case "disasm":
return { asm, cursor: { done: true } };
case "get_callers":
return [
{ address: "0x1004", name: "main", size: "0x20" },
{ address: "0x1008", name: "main", size: "0x20" },
];
case "get_callees":
return [{ address: "0x2000", name: "puts", type: "external" }];
case "callees":
return [
{
callees: [{ addr: "0x2000", name: "puts", type: "external" }],
more: false,
},
];
case "get_xrefs_to":
return [{ address: "0x1004", type: "code", function: fn }];
case "xrefs_to":
return [
{
xrefs: [
{
addr: "0x1004",
type: "code",
fn: { addr: fn.address, name: fn.name, size: fn.size },
},
],
more: false,
},
];
case "list_strings":
return {
data: [{ address: "0x3000", length: 5, string: "a.b\nC" }],
next_offset: null,
};
case "find_regex":
return {
matches: [{ addr: "0x3000", string: "a.b\nC" }],
cursor: { done: true },
};
default:
throw new Error(`Unimplemented producer tool ${name}`);
}
}
private lifecycle(
name: string,
args: Readonly<Record<string, JsonValue>>,
): JsonValue {
switch (name) {
case "idb_open": {
if (
typeof args.preferred_session_id !== "string" ||
typeof args.input_path !== "string"
)
throw new Error("Missing lifecycle identity");
this.database = args.preferred_session_id;
this.inputPath = args.input_path;
return {
success: true,
session: { session_id: this.database, input_path: this.inputPath },
};
}
case "idb_list":
return {
sessions:
this.database === undefined
? []
: [
{
session_id: this.database,
input_path: this.inputPath,
owned: this.owned,
backend: "worker",
is_active: this.active,
},
],
};
case "server_health":
return {
status: "ok",
input_path: this.inputPath,
idb_path: `${this.inputPath}.i64`,
module: "target.elf",
imagebase: this.imageBase,
auto_analysis_ready: true,
};
case "idb_close": {
if (this.failClose) throw new Error("Worker release failed");
const session_id = this.database;
this.database = undefined;
return {
success: true,
session_id: session_id ?? "missing",
saved: null,
owned: this.owned,
backend: "worker",
};
}
default:
throw new Error(`Unimplemented producer tool ${name}`);
}
}
}