feat(ida): support optional native IDA Free MCP in attached mode (#1544)
Add an explicit attached native IDA MCP compatibility profile while preserving the legacy and headless workflows. Keep recorded input identity, complete source observations and the user's open GUI database. Batch unique callee lookups, conservatively prefilter literal strings, preserve Unicode matching and unavailable caller coverage, and require distinct-function switching in native verification. Verified with Windows IDA Pro 9.3 and the native MCP plugin built from c9d15d98e8a143fc74f6e14037c48f63889b6d6c with a loopback listener. Production CLI/MCP and an unchanged Windows whoami.exe passed. Windows IDA Free was not used. No personal paths or license registration information are included. Validation: 200 focused tests, static and documentation checks, architecture guards and discovery passed. Historical same-main warm task measurements improved from 675 to 317 ms; response token estimates fell from 16618 to 11509. Fresh-start, overall CPU and memory improvement were not established. Detailed scope is in experiments/analysis-efficiency/ida-native-windows.md. Co-authored-by: imissapixel <140405963+imissapixel@users.noreply.github.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> Co-authored-by: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com>
This commit is contained in:
co-authored by
morluto
N0zoM1z0
parent
f76163c246
commit
d1aaeee400
+37
-27
@@ -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 MCP 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,
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,713 @@
|
||||
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 {
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
} from "../domain/analysisErrorCore.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 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.provider.name).toBe("IDA MCP adapter");
|
||||
expect(profile.value.profile.parameters).toMatchObject({
|
||||
compatibility_profile: "native-ida-mcp",
|
||||
mode: "attached",
|
||||
cache_policy: "live",
|
||||
engine_version: null,
|
||||
});
|
||||
expect(
|
||||
provider
|
||||
.capabilities()
|
||||
.find(({ operation }) => operation === "procedure_pseudo_code")?.effects
|
||||
.mayShowUi,
|
||||
).toBe(true);
|
||||
expect(
|
||||
provider
|
||||
.capabilities()
|
||||
.find(({ operation }) => operation === "procedure_assembly")?.effects
|
||||
.mayShowUi,
|
||||
).toBe(false);
|
||||
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 provider observations", () => {
|
||||
it.each([false, true])(
|
||||
"keeps unknown callers in dossier coverage when callee truncation is %s",
|
||||
async (more) => {
|
||||
const { client, producer } = await fixture();
|
||||
const original = producer.overrideCall;
|
||||
producer.overrideCall = (name, args) =>
|
||||
name === "callees"
|
||||
? [
|
||||
{
|
||||
callees: [{ addr: "0x2000", name: "puts", type: "external" }],
|
||||
more,
|
||||
error: null,
|
||||
},
|
||||
]
|
||||
: original?.(name, args);
|
||||
try {
|
||||
const direct = await client.execute("procedure_callees", {
|
||||
procedure: "main",
|
||||
});
|
||||
if (!direct.ok) throw direct.error;
|
||||
expect(direct.value.relationshipCoverage).toMatchObject({
|
||||
status: more ? "partial" : "complete",
|
||||
});
|
||||
const dossier = await client.execute("analyze_function", {
|
||||
procedure: "main",
|
||||
});
|
||||
if (!dossier.ok) throw dossier.error;
|
||||
expect(dossier.value.relationshipCoverage).toEqual({
|
||||
status: "unknown",
|
||||
reason:
|
||||
"Upstream xrefs do not establish direct caller relationships.",
|
||||
});
|
||||
expect(dossier.value.result).toMatchObject({
|
||||
callers: [],
|
||||
callees: [{ address: "0x2000", name: "puts" }],
|
||||
});
|
||||
if (more)
|
||||
expect(dossier.value.limitations).toContain(
|
||||
"Upstream callees capped results at 500; additional callees remain unknown.",
|
||||
);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
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;
|
||||
expect(result.value.provider.name).toBe("IDA MCP adapter");
|
||||
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 query identity", () => {
|
||||
it.each([
|
||||
"procedure_address",
|
||||
"procedure_assembly",
|
||||
"procedure_pseudo_code",
|
||||
"analyze_function",
|
||||
] as const)(
|
||||
"rejects a successful lookup for another query before %s can accept the wrong function",
|
||||
async (operation) => {
|
||||
const { client, producer } = await fixture();
|
||||
producer.overrideCall = (name) =>
|
||||
name === "lookup_funcs"
|
||||
? [
|
||||
{
|
||||
query: "helper",
|
||||
fn: { addr: "0x2000", name: "helper", size: "0x20" },
|
||||
error: null,
|
||||
},
|
||||
]
|
||||
: undefined;
|
||||
try {
|
||||
const result = await client.execute(operation, { procedure: "main" });
|
||||
if (result.ok)
|
||||
throw new Error("Expected a mismatched lookup rejection");
|
||||
expect(result.error._tag).toBe("AnalysisProtocolError");
|
||||
expect(result.error.message).toContain("different query");
|
||||
expect(
|
||||
producer.calls.some(
|
||||
({ name }) => name === "disasm" || name === "decompile",
|
||||
),
|
||||
).toBe(false);
|
||||
} finally {
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("native IDA callee lookup batches", () => {
|
||||
it("batches unique callees and binds reordered replies to their source queries", async () => {
|
||||
const { client, producer } = await fixture();
|
||||
const previous = producer.overrideCall;
|
||||
producer.overrideCall = (name, args) => {
|
||||
if (name === "callees")
|
||||
return [
|
||||
{
|
||||
callees: [
|
||||
{ addr: "0x2004", name: "first", type: "internal" },
|
||||
{ addr: "0x2004", name: "first", type: "internal" },
|
||||
{ addr: "0x3000", name: "second", type: "internal" },
|
||||
{ addr: "0x4000", name: "import", type: "external" },
|
||||
],
|
||||
more: false,
|
||||
error: null,
|
||||
},
|
||||
];
|
||||
if (
|
||||
name === "lookup_funcs" &&
|
||||
Array.isArray(args.queries) &&
|
||||
args.queries.length > 1
|
||||
)
|
||||
return [
|
||||
{
|
||||
query: "0x3000",
|
||||
fn: { addr: "0x3000", name: "second", size: "0x20" },
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
query: "0x2004",
|
||||
fn: { addr: "0x2000", name: "first", size: "0x20" },
|
||||
error: null,
|
||||
},
|
||||
];
|
||||
return previous?.(name, args);
|
||||
};
|
||||
try {
|
||||
const result = await client.execute("procedure_callees", {
|
||||
procedure: "main",
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.result).toEqual(["0x4000", "0x2000", "0x3000"]);
|
||||
expect(
|
||||
producer.calls
|
||||
.filter(({ name }) => name === "lookup_funcs")
|
||||
.map(({ args }) => args.queries),
|
||||
).toEqual([["main"], ["0x2004", "0x3000"]]);
|
||||
expect(result.value.rawResult).toMatchObject({
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
tool: "lookup_funcs",
|
||||
arguments: { queries: ["0x2004", "0x3000"] },
|
||||
result: [
|
||||
expect.objectContaining({ query: "0x3000" }),
|
||||
expect.objectContaining({ query: "0x2004" }),
|
||||
],
|
||||
}),
|
||||
]),
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects missing, duplicate, unrelated, and failed callee lookup rows as provider faults", async () => {
|
||||
const { client, producer } = await fixture();
|
||||
const previous = producer.overrideCall;
|
||||
const first = {
|
||||
query: "0x2000",
|
||||
fn: { addr: "0x2000", name: "first", size: "0x20" },
|
||||
error: null,
|
||||
};
|
||||
const second = {
|
||||
query: "0x3000",
|
||||
fn: { addr: "0x3000", name: "second", size: "0x20" },
|
||||
error: null,
|
||||
};
|
||||
let rows: JsonValue = [];
|
||||
producer.overrideCall = (name, args) => {
|
||||
if (name === "callees")
|
||||
return [
|
||||
{
|
||||
callees: [
|
||||
{ addr: "0x2000", name: "first", type: "internal" },
|
||||
{ addr: "0x3000", name: "second", type: "internal" },
|
||||
],
|
||||
more: false,
|
||||
error: null,
|
||||
},
|
||||
];
|
||||
if (
|
||||
name === "lookup_funcs" &&
|
||||
Array.isArray(args.queries) &&
|
||||
args.queries.length > 1
|
||||
)
|
||||
return rows;
|
||||
return previous?.(name, args);
|
||||
};
|
||||
try {
|
||||
for (const reply of [
|
||||
[first],
|
||||
[first, first],
|
||||
[first, { ...second, query: "unrequested" }],
|
||||
[first, { query: "0x3000", fn: null, error: "Not found" }],
|
||||
]) {
|
||||
rows = reply;
|
||||
const result = await client.execute("procedure_callees", {
|
||||
procedure: "main",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok)
|
||||
expect(result.error).toBeInstanceOf(AnalysisProtocolError);
|
||||
}
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("native IDA literal matching", () => {
|
||||
it("retains literal, Unicode, case, and regex semantics while narrowing native candidates", async () => {
|
||||
const { client, producer } = await fixture();
|
||||
const values = [
|
||||
"A.B",
|
||||
"axb",
|
||||
"Kelvin",
|
||||
"İstanbul",
|
||||
"σ",
|
||||
"ς",
|
||||
"literal[bracket",
|
||||
"a\\b",
|
||||
"🧪",
|
||||
];
|
||||
producer.overrideCall = (name, args) => {
|
||||
if (name !== "find_regex") return undefined;
|
||||
if (typeof args.pattern !== "string")
|
||||
throw new Error("Invalid fixture pattern");
|
||||
// Exercise a byte-oriented producer seam, including Unicode candidates
|
||||
// whose final matching semantics belong to REA, not the upstream regex.
|
||||
const regex = new RegExp(
|
||||
Buffer.from(args.pattern).toString("latin1"),
|
||||
"i",
|
||||
);
|
||||
return {
|
||||
matches: values.flatMap((value, i) =>
|
||||
regex.test(Buffer.from(value).toString("latin1"))
|
||||
? [{ addr: `0x${(0x3000 + i).toString(16)}`, string: value }]
|
||||
: [],
|
||||
),
|
||||
cursor: { done: true },
|
||||
};
|
||||
};
|
||||
const cases = [
|
||||
{
|
||||
pattern: "a.b",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
expected: ["A.B"],
|
||||
},
|
||||
{ pattern: "a.b", mode: "literal", case_sensitive: true, expected: [] },
|
||||
{
|
||||
pattern: "kelvin",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
expected: ["Kelvin"],
|
||||
},
|
||||
{
|
||||
pattern: "İ",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
expected: ["İstanbul"],
|
||||
},
|
||||
{ pattern: "σ", mode: "literal", case_sensitive: false, expected: ["σ"] },
|
||||
{
|
||||
pattern: "σ",
|
||||
mode: "regex",
|
||||
case_sensitive: false,
|
||||
expected: ["σ", "ς"],
|
||||
},
|
||||
{
|
||||
pattern: "[",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
expected: ["literal[bracket"],
|
||||
},
|
||||
{
|
||||
pattern: "\\",
|
||||
mode: "literal",
|
||||
case_sensitive: true,
|
||||
expected: ["a\\b"],
|
||||
},
|
||||
{
|
||||
pattern: "\ud800",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
expected: [],
|
||||
},
|
||||
{
|
||||
pattern: "🧪",
|
||||
mode: "literal",
|
||||
case_sensitive: true,
|
||||
expected: ["🧪"],
|
||||
},
|
||||
];
|
||||
try {
|
||||
for (const { expected, ...query } of cases) {
|
||||
const before = producer.calls.length;
|
||||
const result = await client.execute("search_strings", query);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.result).toEqual(
|
||||
expected.map((value) => ({
|
||||
address: `0x${(0x3000 + values.indexOf(value)).toString(16)}`,
|
||||
value,
|
||||
})),
|
||||
);
|
||||
const reads = producer.calls
|
||||
.slice(before)
|
||||
.filter(({ name }) => name === "find_regex");
|
||||
expect(reads).toHaveLength(1);
|
||||
if (query.mode === "regex" || query.pattern === "\ud800")
|
||||
expect(reads[0]?.args.pattern).toBe("[\\s\\S]*");
|
||||
else expect(reads[0]?.args.pattern).not.toBe("[\\s\\S]*");
|
||||
}
|
||||
const before = producer.calls.length;
|
||||
const invalid = await client.execute("search_strings", {
|
||||
pattern: "[",
|
||||
mode: "regex",
|
||||
});
|
||||
expect(invalid.ok).toBe(false);
|
||||
if (!invalid.ok) expect(invalid.error).toBeInstanceOf(AnalysisInputError);
|
||||
expect(
|
||||
producer.calls.slice(before).some(({ name }) => name === "find_regex"),
|
||||
).toBe(false);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("native IDA string pagination and failures", () => {
|
||||
it("reads all candidate pages and reports native search failures explicitly", async () => {
|
||||
const { client, producer } = await fixture();
|
||||
producer.overrideCall = (name, args) =>
|
||||
name === "find_regex"
|
||||
? {
|
||||
matches: [
|
||||
{
|
||||
addr: args.offset === 0 ? "0x3000" : "0x3001",
|
||||
string: args.offset === 0 ? "σ" : "needle",
|
||||
},
|
||||
],
|
||||
cursor: args.offset === 0 ? { next: 1 } : { done: true },
|
||||
}
|
||||
: undefined;
|
||||
try {
|
||||
const found = await client.execute("search_strings", {
|
||||
pattern: "needle",
|
||||
});
|
||||
if (!found.ok) throw found.error;
|
||||
expect(found.value.result).toEqual([
|
||||
{ address: "0x3001", value: "needle" },
|
||||
]);
|
||||
const reads = producer.calls.filter(({ name }) => name === "find_regex");
|
||||
expect(reads.map(({ args }) => args.offset)).toEqual([0, 1]);
|
||||
expect(new Set(reads.map(({ args }) => args.pattern)).size).toBe(1);
|
||||
producer.overrideCall = (name) =>
|
||||
name === "find_regex"
|
||||
? {
|
||||
matches: [],
|
||||
cursor: { done: true },
|
||||
error: "Regex resource failure",
|
||||
}
|
||||
: undefined;
|
||||
const failed = await client.execute("search_strings", {
|
||||
pattern: "needle",
|
||||
});
|
||||
expect(failed.ok).toBe(false);
|
||||
if (!failed.ok) {
|
||||
expect(failed.error).toBeInstanceOf(AnalysisProtocolError);
|
||||
expect(failed.error.message).toContain("Regex resource failure");
|
||||
}
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("native IDA 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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import { z } from "zod";
|
||||
import { AnalysisProtocolError } from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
cursorSchema,
|
||||
disassemblySchema,
|
||||
idaAddressSchema,
|
||||
modernCalleesSchema,
|
||||
modernStringsSchema,
|
||||
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);
|
||||
|
||||
/** Native regex failures carry an empty page, which must not imply absence. */
|
||||
export const nativeStringsSchema = modernStringsSchema
|
||||
.extend({ error: z.string().optional() })
|
||||
.transform((page) => {
|
||||
if (page.error !== undefined)
|
||||
throw new AnalysisProtocolError(
|
||||
`Native IDA string search failed: ${page.error}`,
|
||||
);
|
||||
return page;
|
||||
});
|
||||
|
||||
/**
|
||||
* Native regexes fold bytes, while REA's insensitive literal search folds
|
||||
* Unicode strings. Include every non-ASCII value as a candidate, then apply
|
||||
* REA's exact predicate. Ill-formed UTF-16 cannot cross upstream JSON/UTF-8.
|
||||
*/
|
||||
export const nativeLiteralSearchPattern = (
|
||||
pattern: string,
|
||||
caseSensitive: boolean,
|
||||
): string | undefined => {
|
||||
if (/[\uD800-\uDFFF]/u.test(pattern)) return undefined;
|
||||
let literal = (caseSensitive ? pattern : pattern.toLowerCase()).replace(
|
||||
/[.*+?^${}()|[\]\\]/gu,
|
||||
"\\$&",
|
||||
);
|
||||
// Spell ASCII variants explicitly rather than depending on an upstream locale.
|
||||
if (!caseSensitive)
|
||||
literal = literal.replace(
|
||||
/[a-z]/gu,
|
||||
(char) => `[${char}${char.toUpperCase()}]`,
|
||||
);
|
||||
return caseSensitive ? literal : `(?:${literal})|[\\x80-\\xff]`;
|
||||
};
|
||||
|
||||
/** 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",
|
||||
];
|
||||
@@ -341,6 +341,10 @@ describe("headless IDA procedure lookup failures", () => {
|
||||
["an empty error", lookup("main", null, "")],
|
||||
["a whitespace-only error", lookup("main", null, " ")],
|
||||
["an answer for a different query", lookup("helper", null, "Not found")],
|
||||
[
|
||||
"a successful answer for a different query",
|
||||
lookup("helper", knownFunction, null),
|
||||
],
|
||||
])("keeps %s as unreadable output", async (_label, answer) => {
|
||||
const client = await missingProcedureFixture(() => answer);
|
||||
try {
|
||||
|
||||
+203
-79
@@ -1,4 +1,12 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
nativeDecompileSchema,
|
||||
nativeDisassemblySchema,
|
||||
nativeCalleesSchema,
|
||||
nativeXrefsSchema,
|
||||
nativeLiteralSearchPattern,
|
||||
nativeStringsSchema,
|
||||
} from "./IdaNativeProtocol.js";
|
||||
import { analysisSearchInput } from "../contracts/analysisSearchContract.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
@@ -14,7 +22,10 @@ import type { RelationshipCoverage } from "../domain/relationshipCoverage.js";
|
||||
import { readCallGraphCallees, unavailableCallGraph } from "./IdaCallGraph.js";
|
||||
import type { IdaMcpConnection } from "./IdaMcpConnection.js";
|
||||
import type { IdaOperation } from "./IdaProviderCapabilities.js";
|
||||
import { IDA_LIMITATIONS } from "./IdaProviderCapabilities.js";
|
||||
import {
|
||||
IDA_LIMITATIONS,
|
||||
IDA_NATIVE_STRING_LIMITATION,
|
||||
} from "./IdaProviderCapabilities.js";
|
||||
import type { EvidenceLocation } from "../domain/evidence.js";
|
||||
import {
|
||||
disassemblySchema,
|
||||
@@ -28,6 +39,7 @@ import {
|
||||
modernDecompileSchema,
|
||||
modernDisassemblySchema,
|
||||
modernLookupSchema,
|
||||
modernLookupBatchSchema,
|
||||
modernPageSchema,
|
||||
modernStringsSchema,
|
||||
modernXrefsSchema,
|
||||
@@ -53,6 +65,38 @@ const identity = (fn: IdaFunction) => ({
|
||||
classification: null,
|
||||
body: unknownBody,
|
||||
});
|
||||
interface IdaRelationships {
|
||||
readonly items: ReturnType<typeof identity>[];
|
||||
readonly coverage: RelationshipCoverage;
|
||||
}
|
||||
|
||||
const combinedRelationshipCoverage = (
|
||||
callers: RelationshipCoverage,
|
||||
callees: RelationshipCoverage,
|
||||
): RelationshipCoverage => {
|
||||
const coverage = [callers, callees];
|
||||
const diagnostics = [
|
||||
...new Set(
|
||||
coverage.flatMap((item) =>
|
||||
"diagnostics" in item ? item.diagnostics : [],
|
||||
),
|
||||
),
|
||||
];
|
||||
const details = diagnostics.length > 0 ? { diagnostics } : {};
|
||||
const unknown = coverage.filter((item) => item.status === "unknown");
|
||||
if (unknown.length > 0)
|
||||
return {
|
||||
status: "unknown",
|
||||
reason: [...new Set(unknown.map((item) => item.reason))].join(" "),
|
||||
...details,
|
||||
};
|
||||
const limitations = coverage.flatMap((item) =>
|
||||
item.status === "partial" ? item.limitations : [],
|
||||
);
|
||||
return limitations.length > 0
|
||||
? { status: "partial", limitations, ...details }
|
||||
: { status: "complete", ...details };
|
||||
};
|
||||
/** The only lookup answers upstream reports for a name or address that is not a function. */
|
||||
const MISSING_PROCEDURE_ANSWERS: ReadonlySet<string> = new Set([
|
||||
"Not found",
|
||||
@@ -60,6 +104,7 @@ const MISSING_PROCEDURE_ANSWERS: ReadonlySet<string> = new Set([
|
||||
]);
|
||||
const lines = (asm: IdaDisassembly) =>
|
||||
asm.lines.map(({ address, instruction }) => `${address}: ${instruction}`);
|
||||
const searchQuerySchema = z.object(analysisSearchInput);
|
||||
|
||||
/** Translate explicit analyst questions into a closed set of read-only upstream requests. */
|
||||
export class IdaOperationRunner {
|
||||
@@ -69,7 +114,7 @@ export class IdaOperationRunner {
|
||||
relationshipCoverage: RelationshipCoverage | undefined;
|
||||
constructor(
|
||||
private readonly connection: IdaMcpConnection,
|
||||
private readonly protocol: "legacy" | "modern",
|
||||
private readonly protocol: "legacy" | "modern" | "native",
|
||||
private readonly database?: string,
|
||||
private readonly options: {
|
||||
readonly signal?: AbortSignal | undefined;
|
||||
@@ -131,37 +176,11 @@ export class IdaOperationRunner {
|
||||
* addresses were reported by IDA itself.
|
||||
*/
|
||||
async resolve(query: string, requestedBy?: string): Promise<IdaFunction> {
|
||||
if (this.protocol === "modern") {
|
||||
if (this.protocol !== "legacy") {
|
||||
const item = modernLookupSchema.parse(
|
||||
await this.call("lookup_funcs", { queries: [query] }),
|
||||
)[0];
|
||||
if (
|
||||
requestedBy !== undefined &&
|
||||
item?.query === query &&
|
||||
item.fn === null &&
|
||||
item.error !== null &&
|
||||
MISSING_PROCEDURE_ANSWERS.has(item.error)
|
||||
)
|
||||
throw new AnalysisInputError(
|
||||
requestedBy,
|
||||
{
|
||||
cause: new AnalysisProtocolError(
|
||||
`IDA function lookup failed for ${query}: ${item.error}`,
|
||||
),
|
||||
},
|
||||
[
|
||||
{
|
||||
path: [],
|
||||
reason: "invalid_value",
|
||||
message: `IDA could not resolve procedure ${JSON.stringify(query)}: ${item.error}.`,
|
||||
},
|
||||
],
|
||||
);
|
||||
if (item?.fn == null || item.error !== null)
|
||||
throw new AnalysisProtocolError(
|
||||
`IDA function lookup failed for ${query}: ${item?.error ?? "missing function"}`,
|
||||
);
|
||||
return item.fn;
|
||||
return this.lookupFunction(query, item, requestedBy);
|
||||
}
|
||||
const address = idaAddressSchema.safeParse(
|
||||
/^0x/iu.test(query) ? query : undefined,
|
||||
@@ -184,6 +203,43 @@ export class IdaOperationRunner {
|
||||
return entry;
|
||||
}
|
||||
|
||||
private lookupFunction(
|
||||
query: string,
|
||||
item: z.infer<typeof modernLookupBatchSchema>[number] | undefined,
|
||||
requestedBy?: string,
|
||||
): IdaFunction {
|
||||
if (item?.query !== query)
|
||||
throw new AnalysisProtocolError(
|
||||
`IDA function lookup answered for a different query than ${JSON.stringify(query)}.`,
|
||||
);
|
||||
if (
|
||||
requestedBy !== undefined &&
|
||||
item.fn === null &&
|
||||
item.error !== null &&
|
||||
MISSING_PROCEDURE_ANSWERS.has(item.error)
|
||||
)
|
||||
throw new AnalysisInputError(
|
||||
requestedBy,
|
||||
{
|
||||
cause: new AnalysisProtocolError(
|
||||
`IDA function lookup failed for ${query}: ${item.error}`,
|
||||
),
|
||||
},
|
||||
[
|
||||
{
|
||||
path: [],
|
||||
reason: "invalid_value",
|
||||
message: `IDA could not resolve procedure ${JSON.stringify(query)}: ${item.error}.`,
|
||||
},
|
||||
],
|
||||
);
|
||||
if (item.fn === null || item.error !== null)
|
||||
throw new AnalysisProtocolError(
|
||||
`IDA function lookup failed for ${query}: ${item.error ?? "missing function"}`,
|
||||
);
|
||||
return item.fn;
|
||||
}
|
||||
|
||||
/** True only for modern callee reads on targets not proven x86-only; x86 reads never reach the graph code. */
|
||||
private readsCallGraph(direction: "callers" | "callees"): boolean {
|
||||
return (
|
||||
@@ -197,7 +253,7 @@ export class IdaOperationRunner {
|
||||
private async addCallGraphCallees(
|
||||
fn: IdaFunction,
|
||||
result: Map<string, ReturnType<typeof identity>>,
|
||||
): Promise<void> {
|
||||
): Promise<RelationshipCoverage> {
|
||||
const graph =
|
||||
this.options.callGraphAvailable === false
|
||||
? unavailableCallGraph("the upstream server does not advertise it")
|
||||
@@ -205,14 +261,18 @@ export class IdaOperationRunner {
|
||||
(tool, args) => this.call(tool, args),
|
||||
fn.address,
|
||||
);
|
||||
this.relationshipCoverage = graph.coverage;
|
||||
this.limitations.push(...graph.limitations);
|
||||
for (const callee of graph.callees)
|
||||
if (!result.has(callee.address))
|
||||
result.set(callee.address, identity({ ...callee, size: "unknown" }));
|
||||
return graph.coverage;
|
||||
}
|
||||
|
||||
async strings(): Promise<{ address: string; value: string }[]> {
|
||||
async strings(
|
||||
nativePattern?: string,
|
||||
): Promise<{ address: string; value: string }[]> {
|
||||
if (this.protocol === "native")
|
||||
this.limitations.push(IDA_NATIVE_STRING_LIMITATION);
|
||||
const result: { address: string; value: string }[] = [];
|
||||
let offset: number | null = 0;
|
||||
while (offset !== null) {
|
||||
@@ -229,9 +289,14 @@ export class IdaOperationRunner {
|
||||
);
|
||||
offset = page.next_offset;
|
||||
} else {
|
||||
const page = modernStringsSchema.parse(
|
||||
const page = (
|
||||
this.protocol === "native" ? nativeStringsSchema : modernStringsSchema
|
||||
).parse(
|
||||
await this.call("find_regex", {
|
||||
pattern: "(?s).*",
|
||||
pattern:
|
||||
this.protocol === "native"
|
||||
? (nativePattern ?? "[\\s\\S]*")
|
||||
: "(?s).*",
|
||||
offset,
|
||||
limit: 100,
|
||||
}),
|
||||
@@ -260,7 +325,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,
|
||||
@@ -294,6 +363,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) {
|
||||
@@ -323,9 +409,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"}`,
|
||||
@@ -344,12 +430,16 @@ export class IdaOperationRunner {
|
||||
async relationships(
|
||||
fn: IdaFunction,
|
||||
direction: "callers" | "callees",
|
||||
): Promise<ReturnType<typeof identity>[]> {
|
||||
): Promise<IdaRelationships> {
|
||||
const queries: string[] = [];
|
||||
const result = new Map<string, ReturnType<typeof identity>>();
|
||||
let coverage: RelationshipCoverage = {
|
||||
status: "unknown",
|
||||
reason: "The legacy relationship response does not report coverage.",
|
||||
};
|
||||
if (this.readsCallGraph(direction)) {
|
||||
await this.addCallGraphCallees(fn, result);
|
||||
return [...result.values()];
|
||||
coverage = await this.addCallGraphCallees(fn, result);
|
||||
return { items: [...result.values()], coverage };
|
||||
}
|
||||
if (this.protocol === "legacy") {
|
||||
const value = await this.call(
|
||||
@@ -367,16 +457,20 @@ 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.",
|
||||
);
|
||||
this.relationshipCoverage = {
|
||||
status: "unknown",
|
||||
reason:
|
||||
"Modern upstream xrefs do not establish direct caller relationships.",
|
||||
return {
|
||||
items: [],
|
||||
coverage: {
|
||||
status: "unknown",
|
||||
reason:
|
||||
"Upstream xrefs do not establish direct caller relationships.",
|
||||
},
|
||||
};
|
||||
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)
|
||||
@@ -387,7 +481,7 @@ export class IdaOperationRunner {
|
||||
this.limitations.push(
|
||||
"Upstream callees capped results at 500; additional callees remain unknown.",
|
||||
);
|
||||
this.relationshipCoverage =
|
||||
coverage =
|
||||
page.more === true
|
||||
? {
|
||||
status: "partial",
|
||||
@@ -405,35 +499,62 @@ export class IdaOperationRunner {
|
||||
else queries.push(item.addr);
|
||||
}
|
||||
}
|
||||
for (const query of new Set(queries)) {
|
||||
const resolved = identity(await this.resolve(query));
|
||||
result.set(resolved.address, resolved);
|
||||
const querySet = new Set(queries);
|
||||
if (this.protocol === "native" && querySet.size > 0) {
|
||||
const rows = modernLookupBatchSchema.parse(
|
||||
await this.call("lookup_funcs", { queries: [...querySet] }),
|
||||
);
|
||||
const byQuery = new Map(rows.map((row) => [row.query, row]));
|
||||
if (
|
||||
rows.length !== querySet.size ||
|
||||
byQuery.size !== rows.length ||
|
||||
rows.some((row) => !querySet.has(row.query))
|
||||
)
|
||||
throw new AnalysisProtocolError(
|
||||
"Native IDA returned an inconsistent callee lookup batch.",
|
||||
);
|
||||
for (const query of querySet) {
|
||||
const resolved = identity(
|
||||
this.lookupFunction(query, byQuery.get(query)),
|
||||
);
|
||||
result.set(resolved.address, resolved);
|
||||
}
|
||||
} else {
|
||||
for (const query of querySet) {
|
||||
const resolved = identity(await this.resolve(query));
|
||||
result.set(resolved.address, resolved);
|
||||
}
|
||||
}
|
||||
if (this.relationshipCoverage === undefined)
|
||||
this.relationshipCoverage = {
|
||||
status: "unknown",
|
||||
reason: "The legacy relationship response does not report coverage.",
|
||||
};
|
||||
return [...result.values()];
|
||||
return { items: [...result.values()], coverage };
|
||||
}
|
||||
|
||||
async run(
|
||||
operation: IdaOperation,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
): Promise<JsonValue> {
|
||||
const query =
|
||||
operation === "search_procedures" || operation === "search_strings"
|
||||
? searchQuerySchema.parse(parameters)
|
||||
: undefined;
|
||||
const matches =
|
||||
query === undefined ? undefined : this.searchPredicate(query);
|
||||
if (operation === "list_procedures" || operation === "search_procedures") {
|
||||
const items = (await this.functions()).map((fn) => ({
|
||||
address: fn.address,
|
||||
value: fn.name,
|
||||
}));
|
||||
return operation === "list_procedures"
|
||||
return matches === undefined
|
||||
? items
|
||||
: this.search(items, parameters);
|
||||
: items.filter(({ value }) => matches(value));
|
||||
}
|
||||
if (operation === "list_strings" || operation === "search_strings") {
|
||||
const items = await this.strings();
|
||||
return operation === "search_strings"
|
||||
? this.search(items, parameters)
|
||||
const nativePattern =
|
||||
this.protocol === "native" && query?.mode === "literal"
|
||||
? nativeLiteralSearchPattern(query.pattern, query.case_sensitive)
|
||||
: undefined;
|
||||
const items = await this.strings(nativePattern);
|
||||
return matches !== undefined
|
||||
? items.filter(({ value }) => matches(value))
|
||||
: parameters.address === undefined
|
||||
? items
|
||||
: items.filter(
|
||||
@@ -459,17 +580,18 @@ export class IdaOperationRunner {
|
||||
case "procedure_assembly":
|
||||
return lines(await this.assembly(fn)).join("\n");
|
||||
case "procedure_callers":
|
||||
if (this.protocol === "modern")
|
||||
case "procedure_callees": {
|
||||
if (operation === "procedure_callers" && this.protocol !== "legacy")
|
||||
throw new AnalysisProtocolError(
|
||||
"This IDA MCP profile cannot distinguish direct callers from other code references.",
|
||||
);
|
||||
return (await this.relationships(fn, "callers")).map(
|
||||
({ address }) => address,
|
||||
);
|
||||
case "procedure_callees":
|
||||
return (await this.relationships(fn, "callees")).map(
|
||||
({ address }) => address,
|
||||
const relationships = await this.relationships(
|
||||
fn,
|
||||
operation === "procedure_callers" ? "callers" : "callees",
|
||||
);
|
||||
this.relationshipCoverage = relationships.coverage;
|
||||
return relationships.items.map(({ address }) => address);
|
||||
}
|
||||
case "read_function_instructions":
|
||||
return functionInstructionWindowSchema.parse({
|
||||
procedure: identity(fn),
|
||||
@@ -481,11 +603,9 @@ export class IdaOperationRunner {
|
||||
}
|
||||
}
|
||||
|
||||
private search(
|
||||
items: { address: string; value: string }[],
|
||||
input: Readonly<Record<string, JsonValue>>,
|
||||
): JsonValue {
|
||||
const query = z.object(analysisSearchInput).parse(input);
|
||||
private searchPredicate(
|
||||
query: z.infer<typeof searchQuerySchema>,
|
||||
): (value: string) => boolean {
|
||||
let matches: (value: string) => boolean;
|
||||
if (query.mode === "regex") {
|
||||
try {
|
||||
@@ -504,7 +624,7 @@ export class IdaOperationRunner {
|
||||
matches = (value) =>
|
||||
(query.case_sensitive ? value : value.toLowerCase()).includes(needle);
|
||||
}
|
||||
return items.filter(({ value }) => matches(value));
|
||||
return matches;
|
||||
}
|
||||
|
||||
private async dossier(fn: IdaFunction): Promise<JsonValue> {
|
||||
@@ -512,6 +632,10 @@ export class IdaOperationRunner {
|
||||
const pseudocode = await this.pseudocode(fn);
|
||||
const callers = await this.relationships(fn, "callers");
|
||||
const callees = await this.relationships(fn, "callees");
|
||||
this.relationshipCoverage = combinedRelationshipCoverage(
|
||||
callers.coverage,
|
||||
callees.coverage,
|
||||
);
|
||||
const signature =
|
||||
asm.return_type == null || asm.arguments == null
|
||||
? null
|
||||
@@ -521,8 +645,8 @@ export class IdaOperationRunner {
|
||||
pseudocode: pseudocode ?? "",
|
||||
assembly: lines(asm),
|
||||
comments: [],
|
||||
callers,
|
||||
callees,
|
||||
callers: callers.items,
|
||||
callees: callees.items,
|
||||
incoming_references: [],
|
||||
outgoing_references: [],
|
||||
referenced_strings: [],
|
||||
|
||||
@@ -58,6 +58,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 {
|
||||
@@ -149,9 +150,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-mcp"
|
||||
: config.value.mode === "attached"
|
||||
? "legacy-1.4"
|
||||
: "database-supervisor",
|
||||
database_revision: null,
|
||||
cache_policy: "live",
|
||||
registration_digest: createHash("sha256")
|
||||
|
||||
@@ -3,14 +3,14 @@ import type {
|
||||
CapabilityDescriptor,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
|
||||
/** This version identifies REA's adapter, not IDA or the upstream Python package. */
|
||||
/** This version identifies REA's adapter, not IDA or the upstream MCP server. */
|
||||
export const IDA_PROVIDER_IDENTITY = Object.freeze({
|
||||
id: "ida",
|
||||
name: "IDA Pro MCP adapter",
|
||||
name: "IDA MCP adapter",
|
||||
version: "1",
|
||||
});
|
||||
|
||||
/** Read-only analyst outcomes supported by both upstream compatibility profiles. */
|
||||
/** Read-only analyst outcomes supported by the upstream compatibility profiles. */
|
||||
export const IDA_OPERATIONS = Object.freeze([
|
||||
"list_procedures",
|
||||
"search_procedures",
|
||||
@@ -37,6 +37,9 @@ export const IDA_LIMITATIONS = Object.freeze([
|
||||
"Complete function body ranges, typed references, unresolved indirect calls, referenced data, and basic blocks are unavailable in this adapter. Empty unsupported dossier facets are unknown, not observed absence.",
|
||||
]);
|
||||
|
||||
export const IDA_NATIVE_STRING_LIMITATION =
|
||||
"Native string observations use upstream C-string rendering; other string representations remain unknown.";
|
||||
|
||||
/**
|
||||
* Attached mode requires the legacy 1.4 profile, whose `disassemble_function`
|
||||
* jumps to the function and whose `decompile_function` opens or reuses a
|
||||
@@ -53,15 +56,17 @@ const ATTACHED_GUI_NAVIGATION_OPERATIONS: ReadonlySet<IdaOperation> = new Set([
|
||||
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",
|
||||
@@ -70,11 +75,17 @@ export const idaCapabilities = (
|
||||
launchesProcess: stdio || mode === "headless",
|
||||
mayShowUi:
|
||||
mode === "attached" &&
|
||||
ATTACHED_GUI_NAVIGATION_OPERATIONS.has(operation),
|
||||
(native
|
||||
? operation === "procedure_pseudo_code" ||
|
||||
operation === "analyze_function"
|
||||
: ATTACHED_GUI_NAVIGATION_OPERATIONS.has(operation)),
|
||||
mayAccessNetwork: true,
|
||||
mayWriteFilesystem: stdio || mode === "headless",
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limitations: IDA_LIMITATIONS,
|
||||
limitations:
|
||||
native && (operation === "list_strings" || operation === "search_strings")
|
||||
? [...IDA_LIMITATIONS, IDA_NATIVE_STRING_LIMITATION]
|
||||
: IDA_LIMITATIONS,
|
||||
}));
|
||||
|
||||
@@ -23,7 +23,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 { readSettledHealth } from "./IdaBusyHealth.js";
|
||||
import { isX86OnlyTarget } from "./IdaCallGraph.js";
|
||||
import { IdaOperationRunner } from "./IdaOperationRunner.js";
|
||||
@@ -75,6 +77,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 =>
|
||||
@@ -191,12 +194,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") {
|
||||
@@ -280,7 +286,7 @@ export class IdaSessionClient implements AnalysisClient {
|
||||
#runner(options: ExecutionOptions | undefined): IdaOperationRunner {
|
||||
return new IdaOperationRunner(
|
||||
this.connection,
|
||||
this.config.mode === "attached" ? "legacy" : "modern",
|
||||
idaProtocol(this.config),
|
||||
this.#database,
|
||||
{
|
||||
signal: options?.signal,
|
||||
@@ -418,11 +424,15 @@ export class IdaSessionClient implements AnalysisClient {
|
||||
const tools = new Set(await this.connection.connect());
|
||||
this.#callGraphAdvertised = tools.has("callgraph");
|
||||
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(", ")}. Native attached mode requires the native IDA MCP tool catalog; legacy attached mode requires the legacy 1.4 profile; headless mode requires the database supervisor profile. See docs/ida-provider.md.`,
|
||||
);
|
||||
if (this.config.mode === "headless") {
|
||||
this.#workspace = await IdaWorkspace.allocate(
|
||||
@@ -472,13 +482,24 @@ 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(
|
||||
options?: ExecutionOptions,
|
||||
onObserved?: (metadata: JsonValue) => void,
|
||||
): 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);
|
||||
this.#metadata = raw;
|
||||
onObserved?.(raw);
|
||||
|
||||
Reference in New Issue
Block a user