feat(ida): support optional native IDA Free MCP in attached mode

This commit is contained in:
Fernando
2026-10-10 12:21:17 +01:00
parent 3cd80cbb88
commit 0b60a2ce90
13 changed files with 678 additions and 64 deletions
+1 -1
View File
@@ -170,7 +170,7 @@ using your user permissions; each runtime guide describes its effects.
Native formats and host support vary by provider. See
[Hopper and Ghidra setup](docs/installation.md#hopper), the
[IDA guide](docs/ida-provider.md), and
[IDA guide](docs/ida-provider.md) (including an optional native IDA Free bridge), and
[experimental Windows Ghidra support](docs/windows-ghidra-p0.md).
Ghidra also supports [16-bit DOS analysis](docs/ghidra-dos.md).
For large binaries, raise its startup deadline with
+27 -5
View File
@@ -1,6 +1,6 @@
# IDA Pro provider
# IDA provider
REA adapts an existing [mrexodia/ida-pro-mcp](https://github.com/mrexodia/ida-pro-mcp) server into its native analysis tools. Install and configure IDA, Hex-Rays, Python, and upstream MCP using that repository's instructions. REA does not install, upgrade, activate, or license them, and does not bundle another IDA server.
REA adapts an existing IDA MCP server into its native analysis tools. IDA Pro profiles use [mrexodia/ida-pro-mcp](https://github.com/mrexodia/ida-pro-mcp); an optional IDA Free native bridge is described below. Install and configure your selected engine and upstream MCP using their instructions. REA does not install, upgrade, activate, or license them, and does not bundle another IDA server.
Choose one lifecycle mode in an upstream MCP JSON registration. Set `REA_IDA_MCP_CONFIG` to that file, then select `ida` once through `REA_ANALYSIS_PROVIDER`, the CLI's `--provider ida`, or MCP's `open_binary.provider_id`. No provider startup occurs during discovery.
@@ -32,6 +32,28 @@ Open the **original input binary** in REA, not an `.idb` or `.i64` database. Its
REA's close operation releases its MCP connection or proxy. It never saves or closes the existing GUI database. External edits remain visible because results are live and are not replayed from snapshots. These checks do not lock the GUI or prove that the database is unpatched.
## Optional IDA Free native bridge
IDA Free can use the separate [ida-free-mcp native plugin](https://github.com/0xshlomil/ida-free-mcp) through an explicit attached registration. Install and start that plugin using its upstream instructions, open the original binary in the IDA Free GUI, and wait for analysis. Bind the upstream listener to loopback; REA's URL restriction does not configure the plugin's listen address. REA does not install IDA, build the plugin, activate a license, or launch the GUI.
```json
{
"mode": "attached",
"protocol": "native",
"url": "http://127.0.0.1:13337/mcp"
}
```
Set `REA_IDA_MCP_CONFIG` to this file and select `ida` using the same CLI/MCP commands above. Omitting `protocol` preserves existing IDA Pro registrations. Native mode requires `resources/read` for `ida://idb/metadata` and its recorded input SHA-256; it never substitutes a digest of an unrelated local file. The native resource's `path` describes the IDB in the upstream protocol, not the original input path. REA retains it and checks database identity and image base before and after requests.
This experimental profile provides function/string inventory and search, function lookup, assembly, GUI pseudocode, callees, address xrefs, instruction windows, and function dossiers. Direct callers remain unavailable: native code/data xref labels do not prove call edges. It requires neither IDAPython nor idalib. Native headless registrations are rejected.
IDA Free's cloud decompiler needs network access and may request consent. Follow its licensing and supported architecture limits; see [IDA Free](https://hex-rays.com/ida-free). Decompilation moves GUI focus and the upstream plugin closes existing pseudocode tabs before requesting fresh output. REA advertises UI/network effects and closes only its MCP connection, preserving the open database. Rendered pseudocode has upstream traversal limits and does not prove complete source recovery. Cloud/widget failures remain explicit failures; retry after the GUI finishes or dismiss its prompt.
Native MCP 1.1.2 can navigate in the previously focused pseudocode tab when switching functions. Its producing navigation order must be fixed to focus the disassembly view **before** jumping to the requested entry. This REA profile does not repair stale GUI output. Verification must include two different functions before claiming reliable function switching. Reliable function switching requires that upstream correction. The initial Linux verification uses a locally corrected native plugin.
Native tool observations retain actual tool names and complete JSON text. Upstream `structuredContent` can be a shortened preview even while text contains the full result. REA reads the full native representation and rejects missing/malformed text instead of treating previews as complete observations.
## Give REA a target for headless analysis
The headless profile supports upstream's **database supervisor** API: `idb_open`, `idb_list`, `idb_close`, explicit `database` arguments, and modern analysis tools. Legacy 1.4.0 `idalib-mcp`, which accepts one initial filename and serves SSE, does not implement this profile. Follow the [upstream headless instructions](https://github.com/mrexodia/ida-pro-mcp#headless-idalib-session-model) for an installation with the supervisor API.
@@ -96,11 +118,11 @@ For guided registration, set `REA_IDA_MCP_CONFIG` before `rea setup --client <cl
## Coverage and evidence
Both profiles support procedure/string inventory and literal or regex search, procedure resolution, pseudocode, assembly, raw function instructions, resolved callees, incoming address references, and a function dossier. Inventories and modern pseudocode/assembly follow upstream pagination. Upstream limits on modern xrefs and callees are retained as explicit truncation limitations. A transport-level truncated preview is rejected rather than reported as complete evidence; the error preserves upstream retrieval guidance.
All profiles support procedure/string inventory and literal or regex search, procedure resolution, pseudocode, assembly, raw function instructions, resolved callees, incoming address references, and a function dossier. Inventories and modern pseudocode/assembly follow upstream pagination. Upstream limits on modern xrefs and callees are retained as explicit truncation limitations. A transport-level truncated preview is rejected rather than reported as complete evidence; the error preserves upstream retrieval guidance.
The legacy profile additionally supports direct callers. Its producer may report call-site or interior addresses; REA resolves the reported function symbol to its canonical entry. The modern profile does not prove direct callers from its code/data xref labels, so that capability is unavailable and the dossier marks it unknown.
The legacy profile additionally supports direct callers. Its producer may report call-site or interior addresses; REA resolves the reported function symbol to its canonical entry. The modern and native profiles do not prove direct callers from its code/data xref labels, so that capability is unavailable and the dossier marks it unknown.
Complete body ranges, typed reference edges, CFG, referenced data, source locals, comment kinds, and database revision are unavailable. Empty unsupported dossier facets mean **unknown**, not observed absence. `binary_overview`, whole-symbol inventory, mutation, debugging, arbitrary Python forwarding, and GUI navigation are outside this adapter's coverage. Check session availability before composing a workflow that needs those facets.
Complete body ranges, typed reference edges, CFG, referenced data, source locals, comment kinds, and database revision are unavailable. Empty unsupported dossier facets mean **unknown**, not observed absence. `binary_overview`, whole-symbol inventory, mutation, debugging, arbitrary Python forwarding, and analyst-requested GUI navigation are outside this adapter's coverage. Check session availability before composing a workflow that needs those facets.
`provider.version` identifies the REA adapter; the profile explicitly records `version_scope: "rea-ida-adapter"`. The MCP handshake's `serverInfo` is separate and does not establish IDA or Python distribution versions. Raw observations preserve producer metadata and output. Attached hashes identify the recorded original input; headless identity uses the digest-verified private copy and observed worker input path. Neither proves source-code recovery or an unmodified analysis database.
+3 -1
View File
@@ -481,7 +481,7 @@ or upgrade Java, Ghidra, .NET or native toolchains. See
`npm run verify:ida -- --target /absolute/path/to/program --procedure main`
uses the existing `REA_IDA_MCP_CONFIG` registration. It installs no engine,
Python package, or compiler. The target must already be open in the GUI for
the legacy attached profile; the database-supervisor headless profile opens
the legacy or native attached profile; the database-supervisor headless profile opens
a digest-verified private copy. A caller-supplied fixture keeps prerequisites
limited to the selected engine and host. `tests/conformance/ida/inventory.c`
provides an optional small native fixture source with an exported
@@ -507,6 +507,8 @@ establish real IDA operation. The initial real workflows cover legacy upstream
Linux/macOS headless, modern attached GUI tools, other engine versions and
architectures remain unverified; see the [provider guide](ida-provider.md).
Native IDA Free verification uses `"protocol": "native"` with an already-running native plugin. Add `--second-procedure other_function` to exercise GUI function switching and a return to the first function. Native cloud/widget failures are reported without hidden retries. Local validation covers Linux x64 IDA Free 9.4 with native MCP 1.1.2 and a corrected upstream navigation order; stock 1.1.2 switching and native Windows/macOS workflows are not established by that run. See the [optional native bridge prerequisites](ida-provider.md#optional-ida-free-native-bridge).
## DOS Ghidra analysis
`npm run verify:ghidra:dos` requires the supported Ghidra and JDK installation
+32 -2
View File
@@ -16,6 +16,7 @@ const { values } = parseArgs({
options: {
target: { type: "string" },
procedure: { type: "string", default: "rea_fixture_add" },
"second-procedure": { type: "string" },
"package-root": { type: "string" },
report: { type: "string" },
},
@@ -57,6 +58,8 @@ const environment = Object.fromEntries(
const report = {
passed: false,
mode: config.mode,
protocol:
config.protocol ?? (config.mode === "attached" ? "legacy" : "modern"),
checks: [],
observations: [],
};
@@ -156,7 +159,7 @@ const mcp = async (cliDossier) => {
["procedure_address", { procedure: dossier.procedure.name }],
["procedure_assembly", { procedure: dossier.procedure.address }],
["procedure_callees", { procedure: dossier.procedure.address }],
...(config.mode === "attached"
...(config.mode === "attached" && config.protocol !== "native"
? [["procedure_callers", { procedure: dossier.procedure.address }]]
: []),
["search_procedures", { pattern: dossier.procedure.name }],
@@ -168,6 +171,30 @@ const mcp = async (cliDossier) => {
const result = await call(name, args);
observe(result);
}
if (values["second-procedure"] !== undefined) {
const secondAddress = observe(
await call("procedure_address", {
procedure: values["second-procedure"],
}),
);
assert.notEqual(secondAddress, dossier.procedure.address);
const secondCode = observe(
await call("procedure_pseudo_code", {
procedure: values["second-procedure"],
}),
);
assert.equal(typeof secondCode, "string");
assert.ok(secondCode.length > 0);
const restored = observe(
await call("procedure_pseudo_code", {
procedure: dossier.procedure.address,
}),
);
assert.equal(restored, dossier.pseudocode);
report.checks.push(
"different-function pseudocode and return to the original function",
);
}
const invalid = await client.callTool({
name: "xrefs",
arguments: { address: "not-an-address" },
@@ -195,7 +222,10 @@ const cleanup = async () => {
try {
await upstream.connect();
if (config.mode === "attached") {
const metadata = await upstream.call("get_metadata", {});
const metadata =
config.protocol === "native"
? await upstream.readResource("ida://idb/metadata")
: await upstream.call("get_metadata", {});
assert.equal(metadata.sha256.toLowerCase(), await digest());
report.checks.push(
"existing GUI target remains open with the original input identity",
+37 -27
View File
@@ -6,43 +6,53 @@ import { err, ok, type Result } from "../domain/result.js";
const common = {
mode: z.enum(["attached", "headless"]).default("attached"),
protocol: z.literal("native").optional(),
timeoutMs: z.number().int().positive().max(2_147_483_647).default(300_000),
workspaceRoot: z
.string()
.refine(isAbsolute, "workspaceRoot must be absolute on the REA host")
.optional(),
};
const registrationSchema = z.union([
z
.object({
...common,
type: z.literal("stdio").optional(),
command: z.string().min(1),
args: z.array(z.string()).default([]),
env: z.record(z.string(), z.string()).default({}),
})
.strict(),
z
.object({
...common,
type: z.literal("http").optional(),
url: z.url().refine((value) => {
const url = new URL(value);
return (
["http:", "https:"].includes(url.protocol) &&
["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) &&
url.username === "" &&
url.password === ""
);
}, "IDA MCP must use a local HTTP endpoint without URL credentials"),
headers: z.record(z.string(), z.string()).default({}),
})
.strict(),
]);
const registrationSchema = z
.union([
z
.object({
...common,
type: z.literal("stdio").optional(),
command: z.string().min(1),
args: z.array(z.string()).default([]),
env: z.record(z.string(), z.string()).default({}),
})
.strict(),
z
.object({
...common,
type: z.literal("http").optional(),
url: z.url().refine((value) => {
const url = new URL(value);
return (
["http:", "https:"].includes(url.protocol) &&
["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) &&
url.username === "" &&
url.password === ""
);
}, "IDA MCP must use a local HTTP endpoint without URL credentials"),
headers: z.record(z.string(), z.string()).default({}),
})
.strict(),
])
.refine(
(config) => config.protocol !== "native" || config.mode === "attached",
"The native IDA Free protocol requires attached mode",
);
/** An upstream MCP registration plus REA's database lifecycle selection. */
export type IdaConfiguration = z.infer<typeof registrationSchema>;
/** Select a protocol without changing existing attached/headless registrations. */
export const idaProtocol = (config: IdaConfiguration) =>
config.protocol ?? (config.mode === "attached" ? "legacy" : "modern");
/** Read one explicit registration without starting or installing a provider. */
export const readIdaConfiguration = (
path: string,
+46 -1
View File
@@ -19,6 +19,7 @@ export interface IdaMcpConnection {
name: string,
args: Readonly<Record<string, JsonValue>>,
): Promise<JsonValue>;
readResource?(uri: string): Promise<JsonValue>;
serverInfo(): JsonValue;
close(): Promise<void>;
}
@@ -43,8 +44,23 @@ const toolResultSchema = z.object({
.optional(),
});
const parseIdaJsonText = (text: string): JsonValue => {
let value: unknown;
try {
value = JSON.parse(text);
} catch (cause: unknown) {
throw new AnalysisProtocolError("IDA MCP returned malformed JSON text.", {
cause,
});
}
return jsonValueSchema.parse(value);
};
/** Decode Python FastMCP's scalar wrapper without dropping structured dictionaries. */
export const decodeIdaToolResult = (input: unknown): JsonValue => {
export const decodeIdaToolResult = (
input: unknown,
protocol?: "native",
): JsonValue => {
const result = toolResultSchema.parse(input);
const blocks = result.content.flatMap((block) =>
block.type === "text" && block.text !== undefined ? [block.text] : [],
@@ -57,6 +73,15 @@ export const decodeIdaToolResult = (input: unknown): JsonValue => {
throw new AnalysisProtocolError(
`IDA MCP truncated its output; the preview cannot establish a complete observation. ${result._meta.ida_mcp.download_hint ?? "Use the upstream output download workflow to retrieve the full result."}`,
);
// Native MCP retains the complete JSON text while structuredContent may
// contain a shortened preview. Parse that producer-owned representation once.
if (protocol === "native") {
if (blocks.length !== 1)
throw new AnalysisProtocolError(
"Native IDA MCP omitted its complete JSON text result.",
);
return parseIdaJsonText(blocks[0] ?? "");
}
if (result.structuredContent !== undefined) {
const value = result.structuredContent;
return jsonValueSchema.parse(
@@ -156,8 +181,28 @@ export const createIdaMcpConnection = (
await client
.callTool({ name, arguments: args }, { timeout: config.timeoutMs })
.catch(transportFailure),
config.protocol,
);
},
async readResource(uri) {
const response = await client
.readResource({ uri }, { timeout: config.timeoutMs })
.catch(transportFailure);
const resource = z
.object({
contents: z
.array(
z.object({
uri: z.literal(uri),
mimeType: z.literal("application/json"),
text: z.string(),
}),
)
.length(1),
})
.parse(response);
return parseIdaJsonText(resource.contents[0]?.text ?? "");
},
serverInfo: () => jsonValueSchema.parse(client.getServerVersion() ?? null),
close: () => client.close().catch(transportFailure),
};
+329
View File
@@ -0,0 +1,329 @@
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
createIdaTarget,
RecordingIdaMcp,
} from "../../tests/fixtures/idaMcp.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { readIdaConfiguration } from "./IdaConfiguration.js";
import {
decodeIdaToolResult,
type IdaMcpConnection,
} from "./IdaMcpConnection.js";
import { parseConfig } from "../config/parseConfig.js";
import { IdaProvider } from "./IdaProvider.js";
import { idaCapabilities } from "./IdaProviderCapabilities.js";
import { IdaSessionClient } from "./IdaSessionClient.js";
const roots: string[] = [];
afterEach(async () => {
for (const root of roots.splice(0))
await rm(root, { recursive: true, force: true });
});
const fixture = async () => {
const { root, target } = await createIdaTarget();
roots.push(root);
const producer = new RecordingIdaMcp(target);
producer.overrideCall = (name) => {
if (name === "decompile")
return {
addr: "0x1000",
ok: true,
pseudocode: producer.pseudocode,
lines: 1,
};
if (name === "disasm")
return {
asm: {
name: "main",
start_ea: "0x1000",
lines: "main (.text @ 0x1000):\n1000 ret",
},
cursor: { done: true },
};
if (name === "callees")
return [
{
callees: [{ addr: "0x2000", name: "puts", type: "external" }],
more: false,
error: null,
},
];
if (name === "xrefs_to")
return [
{
xrefs: [{ addr: "0x1004", type: "code", fn: null }],
more: false,
error: null,
},
];
return undefined;
};
const resources: string[] = [];
const connection: IdaMcpConnection = {
connect: async () => [
"list_funcs",
"lookup_funcs",
"find_regex",
"decompile",
"disasm",
"callees",
"xrefs_to",
],
call: (name, args) => producer.call(name, args),
readResource: async (uri) => {
resources.push(uri);
const metadata = await producer.call("get_metadata", {});
if (
metadata === null ||
typeof metadata !== "object" ||
Array.isArray(metadata)
)
throw new Error("Invalid metadata fixture");
return { ...metadata, path: `${producer.inputPath}.i64` };
},
serverInfo: () => producer.serverInfo(),
close: () => producer.close(),
};
const client = new IdaSessionClient(
{
url: "http://127.0.0.1:13337/mcp",
headers: {},
mode: "attached",
protocol: "native",
timeoutMs: 1000,
},
target,
connection,
);
return { producer, client, target, resources, root };
};
describe("native IDA Free attached protocol", () => {
it("requires explicit opt-in and rejects native headless registrations", async () => {
const { root } = await fixture();
const path = join(root, "native.json");
await writeFile(
path,
JSON.stringify({ url: "http://127.0.0.1:13337/mcp", protocol: "native" }),
);
expect(readIdaConfiguration(path)).toMatchObject({
ok: true,
value: { mode: "attached", protocol: "native" },
});
await writeFile(
path,
JSON.stringify({
url: "http://127.0.0.1:13337/mcp",
protocol: "native",
mode: "headless",
}),
);
expect(readIdaConfiguration(path).ok).toBe(false);
await writeFile(path, JSON.stringify({ command: "python" }));
const old = readIdaConfiguration(path);
expect(old.ok && old.value.protocol).toBeUndefined();
});
it("commits native profile semantics and advertises GUI effects without starting a provider", async () => {
const { root, target, producer } = await fixture();
const path = join(root, "profile.json");
await writeFile(
path,
JSON.stringify({ url: "http://127.0.0.1:13337/mcp", protocol: "native" }),
);
const config = parseConfig({ REA_IDA_MCP_CONFIG: path });
if (!config.ok) throw config.error;
const provider = new IdaProvider(config.value, {}, () => {
throw new Error("Unexpected discovery startup");
});
expect(provider.inspectAvailability().status).toBe("available");
const profile = await provider.resolveAnalysisProfile(target);
if (!profile.ok) throw profile.error;
expect(profile.value.profile.parameters).toMatchObject({
compatibility_profile: "native-ida-free",
mode: "attached",
cache_policy: "live",
engine_version: null,
});
expect(
provider
.capabilities()
.find(({ operation }) => operation === "procedure_pseudo_code")?.effects
.mayShowUi,
).toBe(true);
expect(producer.connects).toBe(0);
});
it("uses complete native JSON text instead of a shortened structured preview", () => {
const complete = [
{
data: [{ addr: "0x1000", name: "main", size: "0x20" }],
next_offset: null,
},
];
const response = {
content: [{ type: "text", text: JSON.stringify(complete) }],
structuredContent: { result: [], _output_truncated: true },
};
expect(decodeIdaToolResult(response, "native")).toEqual(complete);
expect(() =>
decodeIdaToolResult({ ...response, content: [] }, "native"),
).toThrow("complete JSON");
expect(() =>
decodeIdaToolResult(
{ ...response, content: [{ type: "text", text: "broken JSON" }] },
"native",
),
).toThrow();
expect(() =>
decodeIdaToolResult({ ...response, isError: true }, "native"),
).toThrow("tool failed");
});
});
describe("native IDA Free provider observations", () => {
it("retains native tool provenance, reads recorded metadata, and closes only its connection", async () => {
const { client, producer, resources } = await fixture();
for (const operation of [
"list_procedures",
"list_strings",
"procedure_assembly",
"procedure_pseudo_code",
"procedure_callees",
"xrefs",
"analyze_function",
] as const) {
const result = await client.execute(
operation,
operation === "list_procedures" || operation === "list_strings"
? {}
: operation === "xrefs"
? { address: "0x1000" }
: { procedure: "main" },
);
if (!result.ok) throw result.error;
if (operation === "procedure_assembly")
expect(result.value.result).toBe("0x1000: ret");
if (operation === "procedure_pseudo_code") {
expect(result.value.result).toBe(producer.pseudocode);
expect(result.value.rawResult).toMatchObject({
observations: expect.arrayContaining([
expect.objectContaining({
tool: "decompile",
result: {
addr: "0x1000",
ok: true,
pseudocode: producer.pseudocode,
lines: 1,
},
}),
]),
});
}
}
expect(resources).toHaveLength(14);
expect(new Set(resources)).toEqual(new Set(["ida://idb/metadata"]));
expect(
producer.calls.find(({ name }) => name === "find_regex")?.args.pattern,
).toBe("[\\s\\S]*");
expect(
(await client.execute("procedure_callers", { procedure: "main" })).ok,
).toBe(false);
expect((await client.close()).ok).toBe(true);
expect(producer.closes).toBe(1);
expect(producer.calls.some(({ name }) => name.startsWith("idb_"))).toBe(
false,
);
const capabilities = idaCapabilities("attached", false, true);
expect(
capabilities.find(({ operation }) => operation === "procedure_callers")
?.available,
).toBe(false);
expect(
capabilities.find(
({ operation }) => operation === "procedure_pseudo_code",
)?.effects,
).toMatchObject({ mayShowUi: true, mayAccessNetwork: true });
expect(
idaCapabilities("attached", false).find(
({ operation }) => operation === "procedure_callers",
)?.available,
).toBe(true);
});
it("rejects unavailable or mismatched recorded input hashes and database switches", async () => {
const { client, producer, target } = await fixture();
for (const hash of ["unavailable", "a".repeat(64)]) {
producer.inputSha256 = hash;
expect((await client.execute("health", {})).ok).toBe(false);
}
producer.inputSha256 = target.sha256;
expect((await client.execute("health", {})).ok).toBe(true);
producer.inputPath += ".other.i64";
expect((await client.execute("list_procedures", {})).ok).toBe(false);
await client.close();
});
});
describe("native IDA Free malformed observations", () => {
it("rejects wrong-function pseudocode, upstream cloud failures, and malformed assembly", async () => {
const { client, producer } = await fixture();
for (const value of [
{ addr: "0x2000", ok: true, pseudocode: "int wrong(void);" },
{
addr: "0x1000",
ok: false,
error: "No pseudocode widget for this function after decompilation",
},
{ addr: "0x1000", ok: true },
]) {
producer.overrideCall = (name) =>
name === "decompile" ? value : undefined;
const result = await client.execute("procedure_pseudo_code", {
procedure: "main",
});
expect(result.ok).toBe(false);
}
producer.overrideCall = (name) =>
name === "disasm"
? {
asm: {
name: "main",
start_ea: "0x1000",
lines: "main (.text @ 0x1000):\nunsupported",
},
cursor: { done: true },
}
: undefined;
expect(
(await client.execute("procedure_assembly", { procedure: "main" })).ok,
).toBe(false);
await client.close();
});
it("follows native assembly pages and rejects non-advancing cursors", async () => {
const { client, producer } = await fixture();
producer.overrideCall = (name, args): JsonValue | undefined =>
name === "disasm"
? {
asm: {
name: "main",
start_ea: "0x1000",
lines: `main (.text @ 0x1000):\n${args.offset === 0 ? "1000 nop" : "1001 ret"}`,
},
cursor: args.offset === 0 ? { next: 1 } : { done: true },
}
: undefined;
const result = await client.execute("procedure_assembly", {
procedure: "main",
});
expect(result.ok && result.value.result).toBe("0x1000: nop\n0x1001: ret");
producer.overrideCall = (name) =>
name === "find_regex" ? { matches: [], cursor: { next: 0 } } : undefined;
expect((await client.execute("list_strings", {})).ok).toBe(false);
await client.close();
});
});
+80
View File
@@ -0,0 +1,80 @@
import { z } from "zod";
import { AnalysisProtocolError } from "../domain/analysisErrorCore.js";
import {
cursorSchema,
disassemblySchema,
idaAddressSchema,
modernCalleesSchema,
modernXrefsSchema,
} from "./IdaProtocolValues.js";
/** Native MCP renders an assembly header followed by bare hexadecimal coordinates. */
const nativeAssemblySchema = disassemblySchema
.omit({ lines: true })
.extend({
lines: z.string(),
})
.transform((asm) => {
const [header, ...body] = asm.lines.split("\n");
const match = header?.match(/^(.+) \((.*) @ (0x[0-9a-f]+)\):$/iu);
if (
match?.[1] !== asm.name ||
idaAddressSchema.parse(match?.[3]) !== asm.start_ea
)
throw new AnalysisProtocolError(
"Native IDA assembly header contradicts its function identity.",
);
return {
...asm,
lines: body.map((line) => {
const item = line.match(/^([0-9a-f]+) (.*)$/iu);
if (item === null)
throw new AnalysisProtocolError(
"Native IDA returned an unsupported assembly line.",
);
return {
address: idaAddressSchema.parse(item[1]),
instruction: item[2] ?? "",
};
}),
};
});
/** Native assembly retains the same explicit pagination cursor as modern MCP. */
export const nativeDisassemblySchema = z.object({
asm: nativeAssemblySchema.nullable(),
error: z.string().optional(),
cursor: cursorSchema,
});
/** GUI decompilation reports the resolved entry and an explicit success/failure. */
export const nativeDecompileSchema = z.object({
addr: idaAddressSchema,
ok: z.boolean(),
pseudocode: z.string().min(1).optional(),
lines: z.number().int().nonnegative().optional(),
error: z.string().optional(),
});
/** Native relationship successes explicitly carry null errors. Normalize that omission here. */
const nativeErrorSchema = z
.string()
.nullish()
.transform((value) => value ?? undefined);
export const nativeCalleesSchema = z
.array(modernCalleesSchema.element.extend({ error: nativeErrorSchema }))
.length(1);
export const nativeXrefsSchema = z
.array(modernXrefsSchema.element.extend({ error: nativeErrorSchema }))
.length(1);
/** Read-only tools required from the native bridge; GUI lifecycle tools are excluded. */
export const nativeTools = [
"list_funcs",
"lookup_funcs",
"find_regex",
"decompile",
"disasm",
"callees",
"xrefs_to",
];
+39 -10
View File
@@ -1,4 +1,10 @@
import { z } from "zod";
import {
nativeDecompileSchema,
nativeDisassemblySchema,
nativeCalleesSchema,
nativeXrefsSchema,
} from "./IdaNativeProtocol.js";
import { analysisSearchInput } from "../contracts/analysisSearchContract.js";
import {
AnalysisInputError,
@@ -60,7 +66,7 @@ export class IdaOperationRunner {
readonly limitations: string[] = [];
constructor(
private readonly connection: IdaMcpConnection,
private readonly protocol: "legacy" | "modern",
private readonly protocol: "legacy" | "modern" | "native",
private readonly database?: string,
) {}
@@ -103,7 +109,7 @@ export class IdaOperationRunner {
}
async resolve(query: string): Promise<IdaFunction> {
if (this.protocol === "modern") {
if (this.protocol !== "legacy") {
const item = modernLookupSchema.parse(
await this.call("lookup_funcs", { queries: [query] }),
)[0];
@@ -153,7 +159,7 @@ export class IdaOperationRunner {
} else {
const page = modernStringsSchema.parse(
await this.call("find_regex", {
pattern: "(?s).*",
pattern: this.protocol === "native" ? "[\\s\\S]*" : "(?s).*",
offset,
limit: 100,
}),
@@ -182,7 +188,11 @@ export class IdaOperationRunner {
let result: IdaDisassembly | undefined;
let offset: number | null = 0;
while (offset !== null) {
const page = modernDisassemblySchema.parse(
const page = (
this.protocol === "native"
? nativeDisassemblySchema
: modernDisassemblySchema
).parse(
await this.call("disasm", {
addr: fn.address,
offset,
@@ -216,6 +226,23 @@ export class IdaOperationRunner {
.string()
.nullable()
.parse(await this.call("decompile_function", { address: fn.address }));
if (this.protocol === "native") {
const page = nativeDecompileSchema.parse(
await this.call("decompile", { addr: fn.address }),
);
if (page.addr !== fn.address)
throw new AnalysisProtocolError(
"Native IDA pseudocode identifies a different function than the resolved entry.",
);
if (!page.ok || page.error !== undefined || page.pseudocode === undefined)
throw new AnalysisProtocolError(
`Native IDA decompilation failed: ${page.error ?? "missing pseudocode"}`,
);
this.limitations.push(
"Native pseudocode is rendered GUI text; the upstream viewer traversal is bounded and does not establish complete source recovery.",
);
return page.pseudocode;
}
const result: string[] = [];
let offset: number | null = 0;
while (offset !== null) {
@@ -245,9 +272,9 @@ export class IdaOperationRunner {
return legacyXrefsSchema.parse(
await this.call("get_xrefs_to", { address }),
);
const page = modernXrefsSchema.parse(
await this.call("xrefs_to", { addrs: [address], limit: 1000 }),
)[0];
const page = (
this.protocol === "native" ? nativeXrefsSchema : modernXrefsSchema
).parse(await this.call("xrefs_to", { addrs: [address], limit: 1000 }))[0];
if (page?.xrefs == null || page.error !== undefined)
throw new AnalysisProtocolError(
`IDA xrefs failed: ${page?.error ?? "missing references"}`,
@@ -285,11 +312,13 @@ export class IdaOperationRunner {
}
} else if (direction === "callers") {
this.limitations.push(
"Modern upstream xrefs classify references as code or data, without proving call edges. Direct callers are unavailable in this profile.",
"Upstream xrefs classify references as code or data, without proving call edges. Direct callers are unavailable in this profile.",
);
return [];
} else {
const page = modernCalleesSchema.parse(
const page = (
this.protocol === "native" ? nativeCalleesSchema : modernCalleesSchema
).parse(
await this.call("callees", { addrs: [fn.address], limit: 500 }),
)[0];
if (page?.callees == null || page.error !== undefined)
@@ -357,7 +386,7 @@ export class IdaOperationRunner {
case "procedure_assembly":
return lines(await this.assembly(fn)).join("\n");
case "procedure_callers":
if (this.protocol === "modern")
if (this.protocol !== "legacy")
throw new AnalysisProtocolError(
"This IDA MCP profile cannot distinguish direct callers from other code references.",
);
+6 -3
View File
@@ -55,6 +55,7 @@ export class IdaProvider implements AnalysisProviderCandidate {
return idaCapabilities(
config.ok ? config.value.mode : "attached",
config.ok && "command" in config.value,
config.ok && config.value.protocol === "native",
);
}
inspectAvailability(): ProviderAvailability {
@@ -126,9 +127,11 @@ export class IdaProvider implements AnalysisProviderCandidate {
upstream_distribution_version: null,
mode: config.value.mode,
compatibility_profile:
config.value.mode === "attached"
? "legacy-1.4"
: "database-supervisor",
config.value.protocol === "native"
? "native-ida-free"
: config.value.mode === "attached"
? "legacy-1.4"
: "database-supervisor",
database_revision: null,
cache_policy: "live",
registration_digest: createHash("sha256")
+9 -4
View File
@@ -41,22 +41,27 @@ export const IDA_LIMITATIONS = Object.freeze([
export const idaCapabilities = (
mode: "attached" | "headless",
stdio: boolean,
native = false,
): readonly CapabilityDescriptor[] =>
IDA_OPERATIONS.map((operation) => ({
provider: IDA_PROVIDER_IDENTITY,
operation,
...(mode === "headless" && operation === "procedure_callers"
...((mode === "headless" || native) && operation === "procedure_callers"
? ({
available: false,
reason:
"The modern upstream profile reports code references without proving direct call edges.",
reason: native
? "The native upstream profile reports code references without proving direct call edges."
: "The modern upstream profile reports code references without proving direct call edges.",
} as const)
: ({ available: true, reason: null } as const)),
cachePolicy: "live",
effects: {
mutatesArtifact: false,
launchesProcess: stdio || mode === "headless",
mayShowUi: false,
mayShowUi:
native &&
(operation === "procedure_pseudo_code" ||
operation === "analyze_function"),
mayAccessNetwork: true,
mayWriteFilesystem: stdio || mode === "headless",
changesPermissions: false,
+27 -6
View File
@@ -19,7 +19,9 @@ import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import type { IdaConfiguration } from "./IdaConfiguration.js";
import { idaProtocol } from "./IdaConfiguration.js";
import type { IdaMcpConnection } from "./IdaMcpConnection.js";
import { nativeTools } from "./IdaNativeProtocol.js";
import { IdaOperationRunner } from "./IdaOperationRunner.js";
import {
IDA_LIMITATIONS,
@@ -67,6 +69,7 @@ const modernTools = [
"xrefs_to",
];
const operationSet: ReadonlySet<string> = new Set(IDA_OPERATIONS);
const isIdaOperation = (operation: string): operation is IdaOperation =>
operationSet.has(operation);
const wasCancelled = (options: ExecutionOptions | undefined): boolean =>
@@ -149,12 +152,15 @@ export class IdaSessionClient implements AnalysisClient {
"This integration admits read-only analysis operations only.",
),
);
if (operation === "procedure_callers" && this.config.mode === "headless")
if (
operation === "procedure_callers" &&
idaProtocol(this.config) !== "legacy"
)
return err(
new AnalysisCapabilityUnavailableError(
"ida",
operation,
"The modern upstream profile does not prove direct callers.",
"This upstream profile does not prove direct callers.",
),
);
if (operation !== "health") {
@@ -193,7 +199,7 @@ export class IdaSessionClient implements AnalysisClient {
);
const runner = new IdaOperationRunner(
this.connection,
this.config.mode === "attached" ? "legacy" : "modern",
idaProtocol(this.config),
this.#database,
);
const result = await runner.run(operation, parameters);
@@ -282,11 +288,15 @@ export class IdaSessionClient implements AnalysisClient {
async #initialize(): Promise<void> {
const tools = new Set(await this.connection.connect());
const expected =
this.config.mode === "attached" ? legacyTools : modernTools;
this.config.protocol === "native"
? nativeTools
: this.config.mode === "attached"
? legacyTools
: modernTools;
const missing = expected.filter((name) => !tools.has(name));
if (missing.length > 0)
throw new AnalysisProtocolError(
`IDA MCP ${this.config.mode} compatibility profile is missing tools: ${missing.join(", ")}. Attached mode requires the legacy 1.4 profile; headless mode requires the database supervisor profile. See docs/ida-provider.md.`,
`IDA MCP ${this.config.protocol === "native" ? "native attached" : this.config.mode} compatibility profile is missing tools: ${missing.join(", ")}. See docs/ida-provider.md.`,
);
if (this.config.mode === "headless") {
this.#workspace = await IdaWorkspace.allocate(
@@ -336,10 +346,21 @@ export class IdaSessionClient implements AnalysisClient {
}
}
async #nativeMetadata(): Promise<JsonValue> {
if (this.connection.readResource === undefined)
throw new AnalysisProtocolError(
"Native IDA MCP requires resources/read for recorded input metadata.",
);
return this.connection.readResource("ida://idb/metadata");
}
async #observe(): Promise<JsonValue> {
let identity: string;
if (this.config.mode === "attached") {
const raw = await this.connection.call("get_metadata", {});
const raw =
this.config.protocol === "native"
? await this.#nativeMetadata()
: await this.connection.call("get_metadata", {});
const metadata = legacyMetadataSchema.parse(raw);
if (metadata.sha256.toLowerCase() !== this.target.sha256.toLowerCase())
throw new AnalysisProtocolError(
+42 -4
View File
@@ -19,7 +19,7 @@ const requestSchema = z.object({
.passthrough()
.optional(),
});
const fixture = async (redirectUrl?: string, cycle = false) => {
const fixture = async (redirectUrl?: string, cycle = false, native = false) => {
const methods: string[] = [];
const headers: (string | undefined)[] = [];
const server = createServer(async (request, response) => {
@@ -47,7 +47,7 @@ const fixture = async (redirectUrl?: string, cycle = false) => {
input.method === "initialize"
? {
protocolVersion: input.params?.protocolVersion,
capabilities: { tools: {} },
capabilities: { tools: {}, ...(native ? { resources: {} } : {}) },
serverInfo: {
name: "ida-transport-fixture",
version: "observed-server-version",
@@ -72,7 +72,32 @@ const fixture = async (redirectUrl?: string, cycle = false) => {
}
: {}),
}
: { content: [], structuredContent: { observed: true } };
: input.method === "resources/read"
? {
contents: [
{
uri: "ida://idb/metadata",
mimeType: "application/json",
text: JSON.stringify({
path: "/fixture/input.i64",
sha256: "a".repeat(64),
base: "0x1000",
module: "input",
}),
},
],
}
: native
? {
content: [
{
type: "text",
text: JSON.stringify([{ observed: true }]),
},
],
structuredContent: { result: [], _output_truncated: true },
}
: { content: [], structuredContent: { observed: true } };
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify({ jsonrpc: "2.0", id: input.id, result }));
});
@@ -93,7 +118,8 @@ const fixture = async (redirectUrl?: string, cycle = false) => {
{
url: `http://127.0.0.1:${address.port}/mcp`,
headers: { Authorization: "Bearer transport-fixture-secret" },
mode: "headless",
mode: native ? "attached" : "headless",
...(native ? { protocol: "native" as const } : {}),
timeoutMs: 2000,
},
{},
@@ -138,3 +164,15 @@ it("rejects nonterminating SDK pagination instead of returning a partial tool ca
methods.filter((method) => method === "tools/list").length,
).toBeGreaterThan(2);
});
it("reads native metadata resources and complete JSON text through the real SDK transport", async () => {
const { connection, methods } = await fixture(undefined, false, true);
expect(await connection.connect()).toEqual(["first", "second"]);
expect(await connection.call("first", {})).toEqual([{ observed: true }]);
expect(await connection.readResource?.("ida://idb/metadata")).toMatchObject({
path: "/fixture/input.i64",
sha256: "a".repeat(64),
});
await expect(connection.readResource?.("ida://other")).rejects.toThrow();
expect(methods).toContain("resources/read");
});