diff --git a/.agents/skills/reverse-engineer-anything/SKILL.md b/.agents/skills/reverse-engineer-anything/SKILL.md index 53ce105a81..2f53469783 100644 --- a/.agents/skills/reverse-engineer-anything/SKILL.md +++ b/.agents/skills/reverse-engineer-anything/SKILL.md @@ -408,16 +408,16 @@ explicit path or endpoint and do not need it. For an existing IDA MCP configuration, use `open_binary` with the original input binary and `provider_id: "ida"`; do not pass an `.idb` or `.i64` database. -The legacy attached profile binds the already-open GUI input by SHA-256 and +The native attached profile binds the already-open GUI input by SHA-256 and leaves its database open. The modern headless profile creates and closes an -owned private database without saving. Installation and registration reuse -[mrexodia/ida-pro-mcp](https://github.com/mrexodia/ida-pro-mcp); see the +owned private database without saving; it reuses +[mrexodia/ida-pro-mcp](https://github.com/mrexodia/ida-pro-mcp). See the [IDA provider guide](https://github.com/morluto/rea/blob/main/docs/providers/ida-provider.md). -For migration to the separate native IDA MCP plugin, follow the guide's -[legacy attached migration](https://github.com/morluto/rea/blob/main/docs/providers/ida-provider.md#migrate-a-legacy-attached-registration). -Replace the upstream registration explicitly; modern mrexodia tools are not the -native profile. Native attachment preserves the database but does not provide -direct callers; check session availability and the guide's verification limits. +A registration naming the removed ida-pro-mcp 1.4 `"legacy"` protocol is +refused; follow the guide's +[legacy attached migration](https://github.com/morluto/rea/blob/main/docs/providers/ida-provider.md#migrate-a-legacy-attached-registration) +instead of editing the protocol value. No IDA profile provides direct callers; +check session availability and the guide's verification limits. Proceed directly to `analyze_function`, pseudocode, or function/string searches after opening; IDA does not supply `binary_overview`. Consult session availability when composing broader workflows. Modern direct callers and unsupported dossier diff --git a/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md b/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md index 53ce105a81..2f53469783 100644 --- a/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md +++ b/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md @@ -408,16 +408,16 @@ explicit path or endpoint and do not need it. For an existing IDA MCP configuration, use `open_binary` with the original input binary and `provider_id: "ida"`; do not pass an `.idb` or `.i64` database. -The legacy attached profile binds the already-open GUI input by SHA-256 and +The native attached profile binds the already-open GUI input by SHA-256 and leaves its database open. The modern headless profile creates and closes an -owned private database without saving. Installation and registration reuse -[mrexodia/ida-pro-mcp](https://github.com/mrexodia/ida-pro-mcp); see the +owned private database without saving; it reuses +[mrexodia/ida-pro-mcp](https://github.com/mrexodia/ida-pro-mcp). See the [IDA provider guide](https://github.com/morluto/rea/blob/main/docs/providers/ida-provider.md). -For migration to the separate native IDA MCP plugin, follow the guide's -[legacy attached migration](https://github.com/morluto/rea/blob/main/docs/providers/ida-provider.md#migrate-a-legacy-attached-registration). -Replace the upstream registration explicitly; modern mrexodia tools are not the -native profile. Native attachment preserves the database but does not provide -direct callers; check session availability and the guide's verification limits. +A registration naming the removed ida-pro-mcp 1.4 `"legacy"` protocol is +refused; follow the guide's +[legacy attached migration](https://github.com/morluto/rea/blob/main/docs/providers/ida-provider.md#migrate-a-legacy-attached-registration) +instead of editing the protocol value. No IDA profile provides direct callers; +check session availability and the guide's verification limits. Proceed directly to `analyze_function`, pseudocode, or function/string searches after opening; IDA does not supply `binary_overview`. Consult session availability when composing broader workflows. Modern direct callers and unsupported dossier diff --git a/docs/providers/ida-provider.md b/docs/providers/ida-provider.md index de117bd135..1c9a7eff7d 100644 --- a/docs/providers/ida-provider.md +++ b/docs/providers/ida-provider.md @@ -1,12 +1,12 @@ # IDA provider -REA adapts an existing IDA MCP server into its native analysis tools. Existing IDA Pro profiles use [mrexodia/ida-pro-mcp](https://github.com/mrexodia/ida-pro-mcp); an optional native bridge for IDA Pro and IDA Free 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. +REA adapts an existing IDA MCP server into its native analysis tools. Headless IDA Pro analysis uses the [mrexodia/ida-pro-mcp](https://github.com/mrexodia/ida-pro-mcp) database supervisor; analysis of a database already open in the IDA GUI uses the separate [ida-free-mcp native plugin](https://github.com/0xshlomil/ida-free-mcp) for IDA Pro and IDA Free. 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. An attached registration (the default mode) must also name its upstream `protocol`: `"legacy"` for the ida-pro-mcp 1.4 GUI proxy or `"native"` for the ida-free-mcp plugin. Headless registrations omit `protocol`. An attached registration without `protocol` is refused with a configuration error naming the choice; REA no longer assumes the legacy proxy. 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. +Choose one lifecycle mode in an upstream MCP JSON registration. An attached registration (the default mode) must also name its upstream protocol, `"protocol": "native"`. Headless registrations omit `protocol`. An attached registration without `protocol` is refused with a configuration error naming the choice. A registration that still names `"protocol": "legacy"` is refused with guidance to [migrate it](#migrate-a-legacy-attached-registration): the ida-pro-mcp 1.4 attached protocol has been removed, and REA never reads that value as another protocol. 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. ## Supported upstream versions -Each mode accepts one upstream tool profile, checked against `tools/list` before any analysis runs. The attached profile requires the legacy GUI tool names; upstream 2.0.0 renamed those tools, and REA has not established an equivalent attached-mode lifecycle and ownership contract for that catalog. It therefore fails closed with the missing tool names in the error diagnostics. +Each mode accepts one upstream tool profile, checked against `tools/list` before any analysis runs. The attached profile requires the native plugin's tool catalog and its `ida://idb/metadata` resource. REA has not established an attached-mode lifecycle and ownership contract for the mrexodia 2.x GUI tool catalog, so an attached registration that reaches it fails closed with the missing tool names in the error diagnostics. Startup failures identify the accepted REA analysis operation. Missing-profile and typed startup transport failures retain the original stage in `details.diagnostics.startup_operation`; existing diagnostics, timeout budgets and resource limits remain available. Startup remains shared within a session; each caller receives its own operation attribution. Cancellation retains live cleanup ownership, so a successful retry releases the originating cancellation outcome as well. @@ -14,27 +14,21 @@ The headless profile is defined by the database-supervisor API, not by an upstre | Mode | Upstream profile | Known working | | --------------------------------- | ------------------- | ------------------------------------------------------ | -| attached (`"protocol": "legacy"`) | legacy GUI tools | 1.4.0 | +| attached (`"protocol": "native"`) | ida-free-mcp plugin | see [the native bridge](#native-ida-mcp-bridge) | | headless | database supervisor | builds serving `idb_open`, `idb_list`, and `idb_close` | ## Analyze an already-open GUI target -The attached profile supports upstream **1.4.0 legacy tools**, including `get_metadata`, `list_functions`, and `decompile_function`. Copy the upstream registration's `command`, `args`, and optional `env` into a JSON file and add `"protocol": "legacy"`. An existing `mcpServers` object with an `ida-pro-mcp` entry is also accepted; add `"protocol": "legacy"` to that entry. For example: +Attached analysis uses the [native IDA MCP bridge](#native-ida-mcp-bridge). Write its local endpoint to a JSON file with `"protocol": "native"`. An existing `mcpServers` object with an `ida-pro-mcp` entry is also accepted; add `"protocol": "native"` to that entry. For example: ```json { - "protocol": "legacy", - "command": "python", - "args": [ - "/absolute/path/to/ida_pro_mcp/server.py", - "--ida-rpc", - "http://127.0.0.1:13337" - ] + "mode": "attached", + "protocol": "native", + "url": "http://127.0.0.1:13337/mcp" } ``` -Use the executable and arguments from your working upstream registration. The legacy GUI's `/mcp` endpoint is its internal RPC endpoint; connect REA through the upstream stdio proxy rather than treating that URL as Streamable HTTP. - ```bash export REA_IDA_MCP_CONFIG=/absolute/path/to/ida-mcp.json export REA_ANALYSIS_PROVIDER=ida @@ -62,19 +56,11 @@ 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 native IDA MCP bridge +## Native IDA MCP bridge -IDA Pro and 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 GUI, and wait for analysis. The native MCP 1.1.2 release binds `0.0.0.0` without a listen-address setting. Restrict inbound access with the host firewall or use an upstream build that binds only to loopback before starting it. REA's local URL restriction does not change the plugin's listener. REA does not install IDA, build the plugin, activate a license, or launch the GUI. +IDA Pro and IDA Free 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 GUI, and wait for analysis. The native MCP 1.1.2 release binds `0.0.0.0` without a listen-address setting. Restrict inbound access with the host firewall or use an upstream build that binds only to loopback before starting it. REA's local URL restriction does not change the plugin's listener. 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. Attached IDA Pro registrations name `"protocol": "legacy"` instead. 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. +Set `REA_IDA_MCP_CONFIG` to the [attached registration](#analyze-an-already-open-gui-target) and select `ida` using the same CLI/MCP commands. 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. @@ -90,8 +76,20 @@ Native tool observations retain actual tool names and complete JSON text. Upstre ### Migrate a legacy attached registration -Both attached profiles remain supported. Migrating replaces the upstream server; -adding `"protocol": "native"` to a legacy Python proxy registration is insufficient. +REA no longer supports the ida-pro-mcp 1.4 attached GUI proxy. A registration +that names `"protocol": "legacy"` is refused at configuration with a +`REA_IDA_MCP_CONFIG` constraint naming this section; REA never connects to the +proxy or reads the value as another protocol, and it does not rewrite the file. +Replace the registration yourself with one of the supported profiles: + +- the native plugin below, to keep analyzing the database already open in the + IDA GUI; or +- an ida-pro-mcp 2.x database supervisor in + [headless mode](#give-rea-a-target-for-headless-analysis), where REA opens and + closes its own private copy of the input instead of the GUI database. + +Migrating to the native plugin replaces the upstream server; changing +`"protocol"` to `"native"` in a legacy Python proxy registration is insufficient. The native plugin is separate from mrexodia/ida-pro-mcp, and upgrading mrexodia to its modern tool catalog does not select this profile. @@ -121,7 +119,7 @@ its modern tool catalog does not select this profile. } ``` - becomes: + becomes (REA refuses the first form): ```json { @@ -151,10 +149,11 @@ its modern tool catalog does not select this profile. connection, target identity, or function switching. REA continues to verify identity and image base around requests and closes only -its connection, preserving the attached database. Restore the backed-up legacy -registration and its upstream endpoint to return to the legacy profile. +its connection, preserving the attached database. The removed legacy profile was +the only one that reported direct `procedure_callers`; no supported profile +replaces it, so caller questions remain unknown rather than inferred from xrefs. -The legacy producer moves the active GUI as a side effect: assembly and raw function instructions jump to the function, and successful pseudocode opens or reuses a pseudocode view. A function dossier does both. Native GUI decompilation also changes the active view. `binary_session` reports these operations with `effects.may_show_ui: true`; headless operations and the other attached operations report `false`. +Native GUI decompilation changes the active view as a side effect. `binary_session` reports pseudocode and function dossiers with `effects.may_show_ui: true`; assembly, raw function instructions, the other attached operations, and headless operations report `false`. ## Give REA a target for headless analysis @@ -239,7 +238,7 @@ All profiles support procedure/string inventory and literal or regex search, pro All profiles expose `list_documents` as the single target admitted for the session. Attached mode verifies its digest against IDA metadata before returning it; headless mode binds the digest-checked private input. `inspect_address_context`, `trace_feature`, and `binary_overview` can therefore resolve that identity without upstream document-listing tools. Segment enumeration is optional: when the selected profile cannot provide it, `binary_overview` still returns document and procedure/string counts and omits `segments` and `segment_count`; omission means unobserved, not empty. The modern headless profile also supports `resolve_containing_procedure`. An address resolves through upstream `lookup_funcs` to the canonical entry of the function that contains it; the body stays unavailable like other IDA identities. When no function contains it, REA reads the database-scoped minimal `survey_binary` and reports `not_in_procedure` for an address inside one of its segments (ends are exclusive) and `outside_segments` otherwise. A missing, truncated or inconsistent survey fails the read instead of guessing a reason. `trace_feature` marks a trace truncated, with a residual unknown for that address, when upstream caps the references it returned. Attached profiles do not declare address containment resolution. -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. +No profile supports direct callers. Upstream code/data xref labels do not prove call edges, so `procedure_callers` is unavailable and the dossier marks callers 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. Whole-symbol inventory, mutation, debugging, arbitrary Python forwarding, and requested GUI navigation are outside this adapter's coverage. Check session availability before composing a workflow that needs those facets. @@ -253,7 +252,7 @@ Native verification requires `--second-procedure other_function --second-marker The verifier requires the resolved procedure in both inventory and procedure search, then compares address, assembly, pseudocode, instruction windows and relationship results with the CLI/MCP dossier. Supply `--expected-string known_literal` to check a known positive string inventory/search result and `--expected-xref 0xSOURCE` to check a known reference source address. Choose those oracles independently from the operation under test. Without them, string and xref correctness are listed in `unverified`; valid output shapes alone do not establish those behaviors. Callee parity does not independently establish semantic completeness. Native callee successes must report an explicit truncation marker; missing markers remain protocol failures. -The initial real workflows use stdio registrations for the legacy Windows GUI profile and a Windows x64 headless supervisor with IDA 9.3. The headless workflow has also passed on macOS arm64 with IDA Professional 9.1 (build 9.1.250226) against the same upstream commit `c133c3853faa111a9b00ee615c013b720d0c4acd`, using a source-built arm64 Mach-O fixture; Mach-O C symbols carry a leading underscore, so the procedure name is `_rea_fixture_add`. Streamable HTTP is tested against a loopback MCP fixture with the pinned client SDK; a real IDA HTTP-supervisor workflow remains unverified. Linux headless engine operation, other IDA releases, architectures, and modern attached GUI tools require their corresponding real workflows before support is claimed. +The initial real workflows used stdio registrations for the since-removed legacy Windows GUI profile and a Windows x64 headless supervisor with IDA 9.3. The headless workflow has also passed on macOS arm64 with IDA Professional 9.1 (build 9.1.250226) against the same upstream commit `c133c3853faa111a9b00ee615c013b720d0c4acd`, using a source-built arm64 Mach-O fixture; Mach-O C symbols carry a leading underscore, so the procedure name is `_rea_fixture_add`. Streamable HTTP is tested against a loopback MCP fixture with the pinned client SDK; a real IDA HTTP-supervisor workflow remains unverified. Linux headless engine operation, other IDA releases, architectures, and modern attached GUI tools require their corresponding real workflows before support is claimed. Native Windows verification uses IDA Pro 9.3 with the public two-function fixture and Windows `whoami.exe`, using upstream `c9d15d98e8a143fc74f6e14037c48f63889b6d6c` with a loopback-listener change. It covers production CLI/MCP parity, distinct-function switching, identity and connection cleanup. See the [correctness and performance measurements](https://github.com/morluto/rea/blob/a2e2c29b59e8775b0e6aedb09a9eb16adf32646b/experiments/analysis-efficiency/ida-native-windows.md). This follow-up did not run Windows IDA Free or native macOS. diff --git a/docs/testing-lanes.md b/docs/testing-lanes.md index 22064a17dc..a5c518480c 100644 --- a/docs/testing-lanes.md +++ b/docs/testing-lanes.md @@ -386,7 +386,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 or native attached profile; the database-supervisor headless profile opens +the 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 exported @@ -410,7 +410,7 @@ Adapter and composition tests cover producer parsing, pagination, canonical entries, external callees, target switches, cancellation draining, snapshot replay exclusion, ownership failures, and incomplete cleanup. They do not establish real IDA operation. The initial real workflows cover legacy upstream -1.4.0 on a Windows GUI and the modern supervisor at upstream commit +1.4.0 on a Windows GUI (a profile REA has since removed) and the modern supervisor at upstream commit `c133c3853faa111a9b00ee615c013b720d0c4acd` with Windows x64 IDA 9.3, and the headless profile on macOS arm64 with IDA Professional 9.1 (build 9.1.250226) at the same upstream commit, using `tests/conformance/ida/inventory.c` built @@ -423,7 +423,7 @@ other engine versions and architectures remain unverified; see the Native IDA MCP verification uses `"protocol": "native"` with an already-running native plugin and requires `--second-procedure other_function --second-marker unique_second_body_text` to exercise GUI function switching and a return to the first function. These options remain optional for other profiles. The literal marker must appear in the second function's pseudocode and be absent from the first. Native cloud/widget failures are reported without hidden retries. -The initial Linux x64 IDA Free 9.4 run used native MCP 1.1.2 with a local navigation correction. Windows x64 verification uses **IDA Pro 9.3**, the two-function public fixture, and the shipped Windows `whoami.exe` application. The native plugin was built from upstream `c9d15d98e8a143fc74f6e14037c48f63889b6d6c`, including the merged navigation fix, with a local loopback-listener change. Production CLI/MCP parity, switching, identity and cleanup passed. Correctness and performance measurements are recorded in the [Windows native verification notes](https://github.com/morluto/rea/blob/a2e2c29b59e8775b0e6aedb09a9eb16adf32646b/experiments/analysis-efficiency/ida-native-windows.md). Stock 1.1.2 switching, native macOS, and Windows IDA Free remain unverified. See the [native bridge prerequisites](providers/ida-provider.md#optional-native-ida-mcp-bridge). +The initial Linux x64 IDA Free 9.4 run used native MCP 1.1.2 with a local navigation correction. Windows x64 verification uses **IDA Pro 9.3**, the two-function public fixture, and the shipped Windows `whoami.exe` application. The native plugin was built from upstream `c9d15d98e8a143fc74f6e14037c48f63889b6d6c`, including the merged navigation fix, with a local loopback-listener change. Production CLI/MCP parity, switching, identity and cleanup passed. Correctness and performance measurements are recorded in the [Windows native verification notes](https://github.com/morluto/rea/blob/a2e2c29b59e8775b0e6aedb09a9eb16adf32646b/experiments/analysis-efficiency/ida-native-windows.md). Stock 1.1.2 switching, native macOS, and Windows IDA Free remain unverified. See the [native bridge prerequisites](providers/ida-provider.md#native-ida-mcp-bridge). ## Kuna lane diff --git a/scripts/verify-real-ida.mjs b/scripts/verify-real-ida.mjs index f2f4083d98..c53662498b 100644 --- a/scripts/verify-real-ida.mjs +++ b/scripts/verify-real-ida.mjs @@ -213,9 +213,6 @@ 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.protocol !== "native" - ? [["procedure_callers", { procedure: dossier.procedure.address }]] - : []), ["search_procedures", { pattern: dossier.procedure.name }], ["procedure_pseudo_code", { procedure: dossier.procedure.address }], ["read_function_instructions", { procedure: dossier.procedure.address }], @@ -252,16 +249,12 @@ const mcp = async (cliDossier) => { case "procedure_pseudo_code": assert.equal(value, dossier.pseudocode); break; - case "procedure_callers": - case "procedure_callees": { - const expected = - name === "procedure_callers" ? dossier.callers : dossier.callees; + case "procedure_callees": assert.deepEqual( [...value].sort(), - expected.map((item) => item.address).sort(), + dossier.callees.map((item) => item.address).sort(), ); break; - } case "read_function_instructions": assert.deepEqual(value.procedure.address, dossier.procedure.address); assert.deepEqual(value.instructions, dossier.assembly); @@ -420,10 +413,7 @@ const cleanup = async () => { try { await upstream.connect(); if (config.mode === "attached") { - const metadata = - config.protocol === "native" - ? await upstream.readResource("ida://idb/metadata") - : await upstream.call("get_metadata", {}); + const metadata = await upstream.readResource("ida://idb/metadata"); assert.equal(metadata.sha256.toLowerCase(), await digest()); report.checks.push( "existing GUI target remains open with the original input identity", diff --git a/src/doctorRuntime.test.ts b/src/doctorRuntime.test.ts index b9e3ca9f33..53fa2ac60b 100644 --- a/src/doctorRuntime.test.ts +++ b/src/doctorRuntime.test.ts @@ -472,7 +472,7 @@ it("shares one parsed IDA registration between timeout-budget and doctor project const registration = join(root, "registration.json"); await writeFile( registration, - JSON.stringify({ command: "fixture", protocol: "legacy", timeoutMs: 3210 }), + JSON.stringify({ command: "fixture", protocol: "native", timeoutMs: 3210 }), ); const host = createSystemDoctorHost({ REA_IDA_MCP_CONFIG: registration }); try { diff --git a/src/ida/IdaCalleeRelationships.test.ts b/src/ida/IdaCalleeRelationships.test.ts index 3230fffd28..7de97665a1 100644 --- a/src/ida/IdaCalleeRelationships.test.ts +++ b/src/ida/IdaCalleeRelationships.test.ts @@ -217,7 +217,7 @@ describe("headless IDA callee edges on x86 targets", () => { } }); - it("does not use the call graph for the legacy attached profile on an ARM target", async () => { + it("does not use the call graph for the native attached profile on an ARM target", async () => { const { root, target } = await createIdaTarget("arm64"); attachedRoots.push(root); const producer = new RecordingIdaMcp(target, "attached"); @@ -227,7 +227,7 @@ describe("headless IDA callee edges on x86 targets", () => { args: [], env: {}, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, workspaceRoot: root, }, @@ -239,10 +239,10 @@ describe("headless IDA callee edges on x86 targets", () => { procedure: "main", }); - expect(result.ok, "the legacy read still works").toBe(true); + expect(result.ok, "the native read still works").toBe(true); expect( producer.calls.some(({ name }) => name === "callgraph"), - "the legacy profile has no call graph source", + "the native profile reads upstream callees, not the call graph", ).toBe(false); } finally { expect((await client.close()).ok).toBe(true); diff --git a/src/ida/IdaConfiguration.test.ts b/src/ida/IdaConfiguration.test.ts index 666b70546d..0cd07ef55f 100644 --- a/src/ida/IdaConfiguration.test.ts +++ b/src/ida/IdaConfiguration.test.ts @@ -3,7 +3,10 @@ import { appendFile, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { createIdaTarget } from "../../tests/fixtures/idaMcp.js"; -import { readIdaConfiguration } from "./IdaConfiguration.js"; +import { + LEGACY_PROTOCOL_REMOVED, + readIdaConfiguration, +} from "./IdaConfiguration.js"; import type { RetainedResourceScope } from "../ports/AnalysisProvider.js"; import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; import * as regularFile from "../filesystem/RegularFile.js"; @@ -15,9 +18,9 @@ const resourceScope: RetainedResourceScope = { run: (operation) => operation(), }; /** An attached registration names its upstream protocol. */ -const LEGACY_REGISTRATION = JSON.stringify({ +const ATTACHED_REGISTRATION = JSON.stringify({ command: "python", - protocol: "legacy", + protocol: "native", }); const read = (path: string) => readIdaConfiguration(path, { resourceScope }); @@ -33,13 +36,13 @@ describe("IDA registration and MCP result boundaries", () => { roots.push(root); const path = join(root, "mcp.json"); for (const input of [ - { command: "python", args: ["server.py"], protocol: "legacy" }, + { command: "python", args: ["server.py"], protocol: "native" }, { mcpServers: { "ida-pro-mcp": { command: "python", args: ["server.py"], - protocol: "legacy", + protocol: "native", }, unrelated: { command: "untouched" }, }, @@ -52,7 +55,7 @@ describe("IDA registration and MCP result boundaries", () => { command: "python", args: ["server.py"], mode: "attached", - protocol: "legacy", + protocol: "native", }, }); } @@ -72,7 +75,7 @@ describe("IDA registration and MCP result boundaries", () => { { command: "python", workspaceRoot: "relative" }, { command: "python", args: "server.py" }, ]) { - await writeFile(path, JSON.stringify({ ...input, protocol: "legacy" })); + await writeFile(path, JSON.stringify({ ...input, protocol: "native" })); expect((await read(path)).ok).toBe(false); } await writeFile( @@ -88,13 +91,13 @@ describe("IDA registration and MCP result boundaries", () => { "http://host.docker.internal:13337/mcp", "http://HOST.CONTAINERS.INTERNAL:13337/mcp", ]) { - await writeFile(path, JSON.stringify({ url, protocol: "legacy" })); + await writeFile(path, JSON.stringify({ url, protocol: "native" })); expect(await read(path)).toMatchObject({ ok: true, value: { url } }); } await writeFile(path, "malformed"); expect((await read(path)).ok).toBe(false); expect((await read(join(root, "absent"))).ok).toBe(false); - const registration = LEGACY_REGISTRATION; + const registration = ATTACHED_REGISTRATION; await writeFile(path, registration.padEnd(65_536)); expect((await read(path)).ok).toBe(true); await writeFile(path, registration.padEnd(65_537)); @@ -109,7 +112,7 @@ it("rejects registration growth beyond the byte limit after descriptor admission const { root } = await createIdaTarget(); roots.push(root); const path = join(root, "mcp.json"); - await writeFile(path, LEGACY_REGISTRATION); + await writeFile(path, ATTACHED_REGISTRATION); const openRegularFile = regularFile.openRegularFile; const admission = vi .spyOn(regularFile, "openRegularFile") @@ -133,7 +136,7 @@ describe("IDA registration descriptor ownership", () => { const { root } = await createIdaTarget(); roots.push(root); const path = join(root, "mcp.json"); - await writeFile(path, LEGACY_REGISTRATION); + await writeFile(path, ATTACHED_REGISTRATION); const retained: { close(): Promise }[] = []; const owner: RetainedResourceScope = { retain: (resource) => retained.push(resource), @@ -165,7 +168,7 @@ describe("IDA registration descriptor ownership", () => { const { root } = await createIdaTarget(); roots.push(root); const path = join(root, "mcp.json"); - await writeFile(path, LEGACY_REGISTRATION); + await writeFile(path, ATTACHED_REGISTRATION); const reason = new Error("stop registration inspection"); const controller = new AbortController(); controller.abort(reason); @@ -180,7 +183,7 @@ describe("IDA registration descriptor ownership", () => { const { root } = await createIdaTarget(); roots.push(root); const path = join(root, "mcp.json"); - await writeFile(path, LEGACY_REGISTRATION); + await writeFile(path, ATTACHED_REGISTRATION); const retained: { close(): Promise }[] = []; const owner: RetainedResourceScope = { retain: (resource) => retained.push(resource), @@ -221,7 +224,7 @@ describe("IDA registration descriptor ownership", () => { const { root } = await createIdaTarget(); roots.push(root); const path = join(root, "mcp.json"); - await writeFile(path, LEGACY_REGISTRATION); + await writeFile(path, ATTACHED_REGISTRATION); const retained: { close(): Promise }[] = []; const owner: RetainedResourceScope = { retain: (resource) => retained.push(resource), @@ -279,8 +282,8 @@ it.each(["env", "headers"] as const)( ); const transport = field === "env" - ? { command: "python", protocol: "legacy" } - : { url: "http://127.0.0.1:8745/mcp", protocol: "legacy" }; + ? { command: "python", protocol: "native" } + : { url: "http://127.0.0.1:8745/mcp", protocol: "native" }; await writeFile(path, JSON.stringify({ ...transport, [field]: mapping })); const result = await read(path); if (!result.ok) throw result.error; @@ -303,8 +306,8 @@ it.each(["env", "headers"] as const)( const path = join(root, "mcp.json"); const transport = field === "env" - ? { command: "python", protocol: "legacy" } - : { url: "http://127.0.0.1:8745/mcp", protocol: "legacy" }; + ? { command: "python", protocol: "native" } + : { url: "http://127.0.0.1:8745/mcp", protocol: "native" }; for (const value of [42, null, {}]) { await writeFile( path, @@ -318,8 +321,40 @@ it.each(["env", "headers"] as const)( }, ); -// An attached registration no longer defaults to the legacy 1.4 proxy; it -// fails closed naming the protocol choice instead of guessing. +// A stored registration that still selects the removed 1.4 proxy is refused +// with migration guidance; it is never read as the native or headless protocol. +it.each([ + { command: "python", args: ["server.py"], protocol: "legacy" }, + { url: "http://127.0.0.1:13337/mcp", mode: "attached", protocol: "legacy" }, + { + mcpServers: { + "ida-pro-mcp": { command: "python", protocol: "legacy" }, + }, + }, +])("refuses the removed legacy protocol in %j", async (input) => { + const { root } = await createIdaTarget(); + roots.push(root); + const path = join(root, "mcp.json"); + await writeFile(path, JSON.stringify(input)); + const parsed = await read(path); + if (parsed.ok) throw new Error("Expected the legacy protocol to fail"); + // The refusal names the protocol setting and delivers the owner's guidance. + const constraint = `protocol: ${LEGACY_PROTOCOL_REMOVED}`; + expect(parsed.error.settings).toEqual([ + { setting: "REA_IDA_MCP_CONFIG", constraint }, + ]); + expect(parsed.error.message).toContain(constraint); + // The guidance names a migration target the provider guide documents. + expect(LEGACY_PROTOCOL_REMOVED).toContain('"protocol": "native"'); + const guide = await fs.readFile("docs/providers/ida-provider.md", "utf8"); + expect(guide).toMatch(/^### Migrate a legacy attached registration$/mu); + expect(LEGACY_PROTOCOL_REMOVED).toContain( + '"Migrate a legacy attached registration"', + ); +}); + +// An attached registration has no default protocol; it fails closed naming +// the protocol choice instead of guessing. it.each([ { command: "python", args: ["server.py"] }, { command: "python", mode: "attached" }, @@ -359,7 +394,7 @@ it("resolves the single headless protocol without a protocol field", async () => JSON.stringify({ command: "python", mode: "headless", - protocol: "legacy", + protocol: "native", }), ); expect((await read(path)).ok).toBe(false); diff --git a/src/ida/IdaConfiguration.ts b/src/ida/IdaConfiguration.ts index 743f24ec19..9e14a4c792 100644 --- a/src/ida/IdaConfiguration.ts +++ b/src/ida/IdaConfiguration.ts @@ -47,9 +47,11 @@ const common = { .optional(), mode: z.enum(["attached", "headless"]).default("attached"), /** - * Attached mode serves two upstream protocols, so an attached registration - * names one; omitting it no longer selects the legacy 1.4 GUI proxy. - * Headless mode has one protocol (the database supervisor). + * An attached registration names its upstream protocol. `"legacy"` (the + * removed ida-pro-mcp 1.4 GUI proxy) is still recognized so that a stored + * registration is refused with migration guidance rather than reported as an + * unknown value or read as another protocol. Headless mode has one protocol + * (the database supervisor). */ protocol: z.enum(["legacy", "native"]).optional(), timeoutMs: z @@ -62,6 +64,9 @@ const common = { .refine(isAbsolute, "workspaceRoot must be absolute on the REA host") .optional(), }; +/** Refusal for a stored registration that still selects the removed 1.4 proxy. */ +export const LEGACY_PROTOCOL_REMOVED = + 'the legacy ida-pro-mcp 1.4 attached protocol was removed. Replace this registration with the native ida-free-mcp plugin ("protocol": "native") for an open GUI database, or an ida-pro-mcp 2.x database supervisor in headless mode, as described in "Migrate a legacy attached registration"'; const registrationSchema = z .union([ z @@ -96,13 +101,20 @@ const registrationSchema = z ) .refine( (config) => config.protocol !== undefined || config.mode !== "attached", - 'attached IDA registrations must set protocol to "native" (ida-free-mcp plugin) or "legacy" (ida-pro-mcp 1.4 GUI proxy)', + 'attached IDA registrations must set protocol to "native" (ida-free-mcp plugin)', ) // Resolve the upstream protocol once; consumers never infer it from mode. - .transform((config) => ({ - ...config, - protocol: config.protocol ?? ("modern" as const), - })); + .transform((config, context) => { + if (config.protocol === "legacy") { + context.addIssue({ + code: "custom", + path: ["protocol"], + message: LEGACY_PROTOCOL_REMOVED, + }); + return z.NEVER; + } + return { ...config, protocol: config.protocol ?? ("modern" as const) }; + }); /** An upstream MCP registration plus REA's database lifecycle selection. */ export type IdaConfiguration = z.infer; @@ -120,13 +132,6 @@ const registrationConstraint = ( /** Resolved compatibility facts; persisted identities and diagnostics intentionally differ. */ export const IDA_COMPATIBILITY_PROFILES = { - legacy: { - protocol: "legacy", - mode: "attached", - identity: "legacy-1.4", - diagnosticIdentity: "legacy-1.4", - diagnosticLabel: "attached", - }, modern: { protocol: "modern", mode: "headless", diff --git a/src/ida/IdaContainment.test.ts b/src/ida/IdaContainment.test.ts index 18bcdd0ed3..4ab8f52944 100644 --- a/src/ida/IdaContainment.test.ts +++ b/src/ida/IdaContainment.test.ts @@ -127,7 +127,7 @@ const session = async ( args: [], env: {}, mode, - protocol: mode === "attached" ? "legacy" : "modern", + protocol: mode === "attached" ? "native" : "modern", timeoutMs: 1000, workspaceRoot: root, }, @@ -151,11 +151,9 @@ const found = (query: string, fn: typeof function_) => ({ describe("IDA containment capabilities", () => { it("declares document identity in both profiles and address resolution only in headless", () => { - const declared = (mode: "attached" | "headless", native = false) => + const declared = (mode: "attached" | "headless") => idaCapabilities( - IDA_COMPATIBILITY_PROFILES[ - native ? "native" : mode === "attached" ? "legacy" : "modern" - ], + IDA_COMPATIBILITY_PROFILES[mode === "attached" ? "native" : "modern"], false, ) .map(({ operation }) => operation) @@ -179,17 +177,13 @@ describe("IDA containment capabilities", () => { "resolve_containing_procedure", "list_documents", ]); - expect(declared("attached")).toEqual(["list_documents"]); - expect(declared("attached", true)).toEqual(["list_documents"]); expect( - idaCapabilities(IDA_COMPATIBILITY_PROFILES.legacy, false).map( - ({ operation }) => operation, - ), - "attached profiles declare the bound document but not address resolution", - ).toContain("list_documents"); + declared("attached"), + "the attached profile declares the bound document but not address resolution", + ).toEqual(["list_documents"]); }); - it("refuses address resolution on the legacy attached profile", async () => { + it("refuses address resolution on the native attached profile", async () => { const { client, producer } = await session({}, "attached"); try { const result = await client.execute("resolve_containing_procedure", { diff --git a/src/ida/IdaDiagnosticRedactor.test.ts b/src/ida/IdaDiagnosticRedactor.test.ts index 8af299488d..ca5b80ac90 100644 --- a/src/ida/IdaDiagnosticRedactor.test.ts +++ b/src/ida/IdaDiagnosticRedactor.test.ts @@ -10,7 +10,7 @@ describe("IDA diagnostic credential redaction", () => { url: "http://localhost:1234/mcp", headers: { Authorization: "Bearer fixture-secret" }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }).url; expect( @@ -26,7 +26,7 @@ describe("IDA diagnostic credential redaction", () => { headers: { "X-Private": "café secret" }, sensitive: { headers: ["X-Private"], env: [] }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }).url; expect( @@ -48,7 +48,7 @@ describe("IDA diagnostic credential redaction", () => { url: "http://127.0.0.1:12345/mcp", headers: Object.fromEntries(reversed ? entries.reverse() : entries), mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }).text; expect( @@ -69,7 +69,7 @@ describe("IDA diagnostic credential redaction", () => { CoOkIe: " session=cookie-secret\t", }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }).text; expect( @@ -85,7 +85,7 @@ describe("IDA diagnostic credential redaction", () => { url: "http://127.0.0.1:12345/mcp", headers: { "Set-Cookie": "sid=private-secret; Path=/; HttpOnly" }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }).text; expect(redact("rejected private-secret at /caller/input")).toBe( @@ -101,7 +101,7 @@ describe("IDA diagnostic credential redaction", () => { Cookie: "\t", }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }).text; const message = "Failed at /caller/input \t with ordinary whitespace"; @@ -115,7 +115,7 @@ describe("IDA diagnostic credential redaction", () => { headers: { [name]: "\t" }, sensitive: { headers: [name.toLowerCase()], env: [] }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }).text; expect(redact("input\tvalue")).toBe( @@ -128,7 +128,7 @@ describe("IDA diagnostic credential redaction", () => { url: "http://127.0.0.1:12345/mcp", headers: { Authorization: "Bearer alpha", Cookie: "redacted" }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }).text; expect(redact("alpha redacted")).toBe("␟ ␟"); @@ -211,7 +211,7 @@ it.each(credentialCases)( url: "http://127.0.0.1:12345/mcp", headers, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }).text; expect(redact(message)).toBe(expected); @@ -224,7 +224,7 @@ it("redacts full configured malformed headers without guessing their internal va url: "http://127.0.0.1:12345/mcp", headers: { Authorization: header }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }); expect(redactor.text(header)).toBe("[redacted transport credential]"); @@ -239,7 +239,7 @@ const redactorFor = (header: string, name = "Authorization") => url: "http://127.0.0.1:12345/mcp", headers: { [name]: header }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }); @@ -428,7 +428,7 @@ it("redacts protocol-decoded Basic credentials and password without treating ord const redactor = createIdaDiagnosticRedactor({ url: "http://127.0.0.1:12345/mcp", mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, headers: { Authorization: `Basic ${Buffer.from("user:secret").toString("base64")}`, @@ -448,7 +448,7 @@ it.each(["text", "json"] as const)( const redactor = createIdaDiagnosticRedactor({ url: "http://127.0.0.1:12345/mcp", mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, headers: { Cookie: "a=Q" }, }); @@ -470,7 +470,7 @@ it.each(["text", "json"] as const)( const redactor = createIdaDiagnosticRedactor({ url: "http://127.0.0.1:12345/mcp", mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, headers, }); @@ -488,7 +488,7 @@ it.each(["dXNlcjpzZWNyZXQ=", "dXNlcjpzZWNyZXQ", "dXNlcjpzZWNyZXQ=="])( const redactor = createIdaDiagnosticRedactor({ url: "http://127.0.0.1:12345/mcp", mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, headers: { Authorization: `Basic ${payload}` }, }); @@ -513,7 +513,7 @@ describe("overlapping IDA credential source spans", () => { url: "http://127.0.0.1:12345/mcp", headers: Object.fromEntries(reversed ? entries.reverse() : entries), mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }); const result = redactor.text( @@ -529,7 +529,7 @@ describe("overlapping IDA credential source spans", () => { url: "http://127.0.0.1:12345/mcp", headers: { Authorization: "Custom abc", Cookie: "a=cde; b=def" }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }); expect(redactor.text("prefix abcdefg suffix")).toBe( @@ -565,7 +565,7 @@ describe("credential-safe redaction markers", () => { const redactor = createIdaDiagnosticRedactor({ url: "http://127.0.0.1:12345/mcp", mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, headers: { Authorization: "Custom " + secret, Cookie: "a=X" }, }); @@ -582,7 +582,7 @@ describe("credential-safe redaction markers", () => { const redactor = createIdaDiagnosticRedactor({ url: "http://127.0.0.1:12345/mcp", mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, headers: { Authorization: @@ -604,7 +604,7 @@ describe("unclassified diagnostic blocks and message ownership", () => { const redactor = createIdaDiagnosticRedactor({ url: "http://127.0.0.1:12345/mcp", mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, headers, }); @@ -643,7 +643,7 @@ it("redacts explicitly marked registration values without guessing from environm env: { PRIVATE_VALUE: "marked-secret", IDADIR: "/caller/ida" }, sensitive: { env: ["PRIVATE_VALUE"], headers: [] }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }); expect(environment.text("marked-secret /caller/ida")).toBe( @@ -654,7 +654,7 @@ it("redacts explicitly marked registration values without guessing from environm headers: { "X-Custom": "marked-header", "X-Input": "retained" }, sensitive: { headers: ["x-custom"], env: [] }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }); expect(headers.text("marked-header retained")).toBe( diff --git a/src/ida/IdaJsonDiagnostic.test.ts b/src/ida/IdaJsonDiagnostic.test.ts index c3a9d084a0..9fcd704b4e 100644 --- a/src/ida/IdaJsonDiagnostic.test.ts +++ b/src/ida/IdaJsonDiagnostic.test.ts @@ -30,7 +30,7 @@ const forCredential = (credential: string) => url: "http://127.0.0.1:12345/mcp", headers: { Authorization: `Custom ${credential}` }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }); @@ -180,7 +180,7 @@ describe("IDA JSON diagnostic source preservation", () => { headers: {}, url: "http://127.0.0.1:12345/mcp", mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }); expect(redactor.json(source)).toBe(source); @@ -281,7 +281,7 @@ describe("overlapping raw and decoded JSON credential spans", () => { url: "http://127.0.0.1:12345/mcp", headers: { Authorization: "Custom X]", Cookie: "a=]SECRET" }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }); it.each([ @@ -306,7 +306,7 @@ describe("overlapping raw and decoded JSON credential spans", () => { url: "http://127.0.0.1:12345/mcp", headers: { Authorization: "Basic " + encoded, Cookie: "a=]SECRET" }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }); expect( diff --git a/src/ida/IdaMcpConnection.test.ts b/src/ida/IdaMcpConnection.test.ts index 455c105b09..b2ac2d166d 100644 --- a/src/ida/IdaMcpConnection.test.ts +++ b/src/ida/IdaMcpConnection.test.ts @@ -19,21 +19,20 @@ import { readSettledHealth } from "./IdaBusyHealth.js"; import { idaConnectionDependencies } from "../../tests/support/idaConnectionDependencies.js"; describe("upstream IDA tool result decoding", () => { - it("leaves successful legacy, structured, and native evidence unchanged", () => { + it("leaves successful JSON text, structured, and native evidence unchanged", () => { const redact = createIdaDiagnosticRedactor({ url: "http://127.0.0.1:12345/mcp", headers: { Authorization: "Bearer fixture-secret" }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }); const evidence = "Caller-selected fixture-secret evidence"; expect( decodeIdaToolResult( - { content: [{ type: "text", text: evidence }] }, + { content: [{ type: "text", text: JSON.stringify(evidence) }] }, undefined, redact, - "text", ), ).toBe(evidence); expect( @@ -56,7 +55,7 @@ describe("upstream IDA tool result decoding", () => { url: "http://127.0.0.1:12345/mcp", headers: { Authorization: "Bearer fixture-secret" }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }); expect(() => @@ -78,7 +77,7 @@ describe("upstream IDA tool result decoding", () => { "Download /caller/output?cursor=kept using [redacted transport credential]", ); }); - it("decodes scalar wrappers and legacy text without dropping structured dictionaries", () => { + it("decodes scalar wrappers and JSON text without dropping structured dictionaries", () => { expect( decodeIdaToolResult({ content: [], @@ -105,36 +104,16 @@ describe("upstream IDA tool result decoding", () => { content: [{ type: "text", text: '[{"address":"0x1000"}]' }], }), ).toEqual([{ address: "0x1000" }]); - expect( - decodeIdaToolResult( - { content: [{ type: "text", text: "int main(void);" }] }, - undefined, - undefined, - "text", - ), - ).toBe("int main(void);"); }); it.each([ ["truncated JSON", '{"code": "int main('], ["ordinary text", "int main(void);"], - ])("rejects %s from a tool that declares a JSON reply", (_label, text) => { + ])("rejects %s text", (_label, text) => { expect( () => decodeIdaToolResult({ content: [{ type: "text", text }] }), "malformed JSON is never decoded as an ordinary string", ).toThrow("IDA MCP returned malformed JSON text."); }); - it("keeps JSON-shaped text from a tool that declares a text reply", () => { - for (const text of ["null", "42", '{"code": "int main(']) - expect( - decodeIdaToolResult( - { content: [{ type: "text", text }] }, - undefined, - undefined, - "text", - ), - "plain-text pseudocode is never reinterpreted as JSON", - ).toBe(text); - }); it("preserves upstream failures and rejects truncated previews that still satisfy item schemas", () => { expect(() => decodeIdaToolResult({ content: [] })).toThrow( "empty observation", @@ -184,7 +163,7 @@ const failingHttpConnection = ( url: "http://127.0.0.1:12345/mcp", headers: { Authorization: "Custom " + credential }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }, {}, @@ -287,7 +266,7 @@ it("preserves the SDK request timeout as a typed IDA timeout", async () => { url: "http://127.0.0.1:12345/mcp", headers: { Authorization: "Bearer fixture-secret" }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs, }, {}, @@ -510,7 +489,7 @@ const withIdaResource = async ( url: "http://127.0.0.1:12345/mcp", headers: {}, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }, {}, @@ -575,7 +554,7 @@ it("owns unclassified truncated-output hints separately from their context", () const diagnostic = createIdaDiagnosticRedactor({ url: "http://127.0.0.1:12345/mcp", mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, headers: { Authorization: 'Custom q"uote' }, }); @@ -678,7 +657,7 @@ it("uses the actual SDK abort outcome to preserve the caller reason", async () = url: "http://127.0.0.1:12345/mcp", headers: {}, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }, {}, @@ -736,7 +715,7 @@ it("keeps a real SDK physical failure when abort arrives during its outer unwind url: "http://127.0.0.1:12345/mcp", headers: {}, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }, {}, @@ -882,7 +861,7 @@ const cleanupConnection = () => url: "http://127.0.0.1:12345/mcp", headers: {}, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }, {}, @@ -1130,7 +1109,7 @@ it.each(["completed", "pending", "rejected"] as const)( url: "http://127.0.0.1:12345/mcp", headers: {}, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 30, }, {}, diff --git a/src/ida/IdaMcpConnection.ts b/src/ida/IdaMcpConnection.ts index f0d6e63696..072fe973f3 100644 --- a/src/ida/IdaMcpConnection.ts +++ b/src/ida/IdaMcpConnection.ts @@ -8,8 +8,7 @@ import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { mcpToolResultSchema, mcpTextBlocks, - decodeMcpTextReply, - type McpTextReplyKind, + decodeMcpJsonText, } from "../providers/McpToolResult.js"; import { StructuredContentMcpClient } from "../providers/StructuredContentMcpClient.js"; import { @@ -73,8 +72,6 @@ export interface IdaMcpConnection { options?: { readonly timeoutMs?: number | undefined; readonly signal?: AbortSignal | undefined; - /** The tool's declared text reply kind; JSON unless the tool returns plain text. */ - readonly reply?: McpTextReplyKind | undefined; }, ): Promise; readResource?( @@ -190,11 +187,8 @@ const idaStdioLauncher = }); }; -const parseIdaTextReply = ( - text: string, - reply: McpTextReplyKind = "json", -): JsonValue => { - const decoded = decodeMcpTextReply(text, reply); +const parseIdaTextReply = (text: string): JsonValue => { + const decoded = decodeMcpJsonText(text); if (!decoded.ok) throw new AnalysisProtocolError("IDA MCP returned malformed JSON text."); return decoded.value; @@ -202,13 +196,12 @@ const parseIdaTextReply = ( /** * Decode Python FastMCP's scalar wrapper without dropping structured - * dictionaries. A text block is read as the tool's declared reply kind. + * dictionaries. A text block is read as JSON. */ export const decodeIdaToolResult = ( input: unknown, protocol?: "native", diagnostic: IdaDiagnosticRedactor = createIdaDiagnosticRedactor(), - reply: McpTextReplyKind = "json", ): JsonValue => { const result = toolResultSchema.parse(input); const blocks = mcpTextBlocks(result.content); @@ -251,7 +244,7 @@ export const decodeIdaToolResult = ( throw new AnalysisProtocolError( "IDA MCP omitted a single structured or text result; unsupported content cannot establish an empty observation.", ); - return parseIdaTextReply(text, reply); + return parseIdaTextReply(text); }; // Retain only producer-sanitized JSON diagnostics, never a native parser cause. @@ -745,7 +738,6 @@ export const createIdaMcpConnection = ( }), config.protocol === "native" ? "native" : undefined, redactor, - options?.reply, ); }, async readResource(uri, options) { diff --git a/src/ida/IdaMcpEnvironment.test.ts b/src/ida/IdaMcpEnvironment.test.ts index 2e6b42f061..15eff0cb81 100644 --- a/src/ida/IdaMcpEnvironment.test.ts +++ b/src/ida/IdaMcpEnvironment.test.ts @@ -22,7 +22,7 @@ input.on('line', (line) => { ? { protocolVersion: request.params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'environment-producer', version: '1' } } : request.method === 'tools/list' ? { tools: [{ name: 'environment', inputSchema: { type: 'object' } }] } - : { content: [], structuredContent: { selected: process.env.REA_SELECTED_CONTEXT ?? null, registration: process.env.REA_REGISTRATION_CONTEXT ?? null, ambient: process.env.REA_AMBIENT_CONTEXT ?? null, home: process.env.HOME ?? null, path: process.env.PATH ?? null } }; + : { content: [{ type: 'text', text: JSON.stringify({ selected: process.env.REA_SELECTED_CONTEXT ?? null, registration: process.env.REA_REGISTRATION_CONTEXT ?? null, ambient: process.env.REA_AMBIENT_CONTEXT ?? null, home: process.env.HOME ?? null, path: process.env.PATH ?? null }) }] }; process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }) + '\\n'); }); `, @@ -55,7 +55,7 @@ input.on('line', (line) => { args: [script], env: registrationEnvironment, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 5000, }, selected, @@ -102,7 +102,7 @@ input.on('line', (line) => { command: process.execPath, args: [script], env: {}, - protocol: "legacy", + protocol: "native", mode: "attached", timeoutMs: 5000, }, diff --git a/src/ida/IdaMcpOwnedCleanup.test.ts b/src/ida/IdaMcpOwnedCleanup.test.ts index 1537253649..f1552f50cc 100644 --- a/src/ida/IdaMcpOwnedCleanup.test.ts +++ b/src/ida/IdaMcpOwnedCleanup.test.ts @@ -62,7 +62,7 @@ it("keeps a failed handshake's incomplete cleanup observable with the redacted s command: "/opt/ida-mcp/server", args: [], env: {}, - protocol: "legacy", + protocol: "native", mode: "attached", timeoutMs: 5000, }, diff --git a/src/ida/IdaMcpWindowsLaunch.test.ts b/src/ida/IdaMcpWindowsLaunch.test.ts index f7f2086fb7..fc98d9d07b 100644 --- a/src/ida/IdaMcpWindowsLaunch.test.ts +++ b/src/ida/IdaMcpWindowsLaunch.test.ts @@ -46,7 +46,7 @@ const observeLaunch = async ( command, args: ["--stdio"], env: {}, - protocol: "legacy", + protocol: "native", mode: "attached", timeoutMs: 5000, }, @@ -147,7 +147,7 @@ it("closes while a Windows command lookup is stalled on an unreachable PATH dire command: "ida-mcp", args: [], env: {}, - protocol: "legacy", + protocol: "native", mode: "attached", timeoutMs: 5000, }, @@ -185,7 +185,7 @@ it("ends a stalled Windows command lookup at the registration timeout", async () command: "ida-mcp", args: [], env: {}, - protocol: "legacy", + protocol: "native", mode: "attached", timeoutMs: 50, }, diff --git a/src/ida/IdaNativeProtocol.test.ts b/src/ida/IdaNativeProtocol.test.ts index 09d540a67f..bbeb70542b 100644 --- a/src/ida/IdaNativeProtocol.test.ts +++ b/src/ida/IdaNativeProtocol.test.ts @@ -92,16 +92,9 @@ const fixture = async () => { "xrefs_to", ], call: (name, args) => producer.call(name, args), - readResource: async (uri) => { + readResource: (uri, options) => { 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` }; + return producer.readResource(uri, options); }, serverInfo: () => producer.serverInfo(), close: () => producer.close(), @@ -130,7 +123,7 @@ describe("native IDA attached protocol", () => { JSON.stringify({ command: "first-server", mode: "attached", - protocol: "legacy", + protocol: "native", }), ); const config = parseConfig({ REA_IDA_MCP_CONFIG: path }); @@ -175,7 +168,7 @@ describe("native IDA attached protocol", () => { const path = join(root, "independent-registration.json"); await writeFile( path, - JSON.stringify({ command: "first-server", protocol: "legacy" }), + JSON.stringify({ command: "first-server", protocol: "native" }), ); const config = parseConfig({ REA_IDA_MCP_CONFIG: path }); if (!config.ok) throw config.error; @@ -196,7 +189,7 @@ describe("native IDA attached protocol", () => { if (!firstProfile.ok) throw firstProfile.error; await writeFile( path, - JSON.stringify({ command: "second-server", protocol: "legacy" }), + JSON.stringify({ command: "second-server", protocol: "native" }), ); const secondScope = new ProviderInspectionScope(); const second = await provider.inspectReadinessSnapshot({ @@ -244,7 +237,7 @@ describe("IDA selected registration factories", () => { for (let index = 0; index < 40; index += 1) { await writeFile( path, - JSON.stringify({ command: `server-${index}`, protocol: "legacy" }), + JSON.stringify({ command: `server-${index}`, protocol: "native" }), ); const scope = new ProviderInspectionScope(); const resolution = await provider.resolveAnalysisProfile(target, { @@ -315,8 +308,10 @@ describe("IDA selected registration factories", () => { path, JSON.stringify({ command: "python", protocol: "legacy" }), ); - const old = await readIdaConfiguration(path, { resourceScope }); - expect(old.ok && old.value.protocol).toBe("legacy"); + expect( + (await readIdaConfiguration(path, { resourceScope })).ok, + "the removed legacy protocol is refused, not read as native", + ).toBe(false); }); it("commits native profile semantics and advertises GUI effects without starting a provider", async () => { @@ -511,11 +506,6 @@ describe("native IDA provider observations", () => { declared.find(({ operation }) => operation === "procedure_pseudo_code") ?.effects, ).toMatchObject({ mayShowUi: true, mayAccessNetwork: true }); - expect( - idaCapabilities(IDA_COMPATIBILITY_PROFILES.legacy, false).find( - ({ operation }) => operation === "procedure_callers", - )?.available, - ).toBe(true); }); it("rejects unavailable or mismatched recorded input hashes and database switches", async () => { diff --git a/src/ida/IdaOperationFailures.test.ts b/src/ida/IdaOperationFailures.test.ts index 0d7c2f99f5..b0ca425afa 100644 --- a/src/ida/IdaOperationFailures.test.ts +++ b/src/ida/IdaOperationFailures.test.ts @@ -699,82 +699,3 @@ describe("provider-derived procedure selectors", () => { }, ); }); - -describe("attached IDA procedure lookup failures", () => { - it("leaves a failed legacy lookup as unreadable output", async () => { - const { root, target } = await createIdaTarget(); - roots.push(root); - const producer = new RecordingIdaMcp(target, "attached"); - producer.overrideCall = (name) => - name === "get_function_by_name" ? null : undefined; - const client = new IdaSessionClient( - { - command: "fixture", - args: [], - env: {}, - mode: "attached", - protocol: "legacy", - timeoutMs: 1000, - workspaceRoot: root, - }, - target, - producer, - ); - try { - const result = await client.execute("procedure_pseudo_code", { - procedure: "main", - }); - - if (result.ok) throw new Error("expected unreadable output"); - expect( - projectAnalysisError(result.error).code, - "the legacy profile keeps its pre-existing classification", - ).toBe("unreadable_output"); - } finally { - expect((await client.close()).ok).toBe(true); - } - }); - - it("leaves an MCP error reply for an unknown legacy name as unreadable output", async () => { - const { root, target } = await createIdaTarget(); - roots.push(root); - const producer = new RecordingIdaMcp(target, "attached"); - producer.beforeCall = async (name) => { - if (name === "get_function_by_name") - decodeIdaToolResult({ - content: [{ type: "text", text: "Function not found: main" }], - isError: true, - }); - }; - const client = new IdaSessionClient( - { - command: "fixture", - args: [], - env: {}, - mode: "attached", - protocol: "legacy", - timeoutMs: 1000, - workspaceRoot: root, - }, - target, - producer, - ); - try { - const result = await client.execute("procedure_pseudo_code", { - procedure: "main", - }); - - if (result.ok) throw new Error("expected unreadable output"); - expect( - result.error._tag, - "a producer error reply, not caller input", - ).toBe("AnalysisProtocolError"); - expect( - projectAnalysisError(result.error).code, - "the legacy profile keeps its existing classification", - ).toBe("unreadable_output"); - } finally { - expect((await client.close()).ok).toBe(true); - } - }); -}); diff --git a/src/ida/IdaOperationRunner.test.ts b/src/ida/IdaOperationRunner.test.ts index bd932e8425..426f965fe7 100644 --- a/src/ida/IdaOperationRunner.test.ts +++ b/src/ida/IdaOperationRunner.test.ts @@ -6,12 +6,17 @@ import { } from "../../tests/fixtures/idaMcp.js"; import { IdaOperationRunner } from "./IdaOperationRunner.js"; import type { JsonValue } from "../domain/jsonValue.js"; +import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; -it.each(["legacy", "modern", "native"] as const)( +/** The fixture serves the native protocol attached and the supervisor headless. */ +const producerFor = (target: BinaryTarget, protocol: "modern" | "native") => + new RecordingIdaMcp(target, protocol === "native" ? "attached" : "headless"); + +it.each(["modern", "native"] as const)( "%s validates string address selectors independently of inventory contents", async (protocol) => { const { root, target } = await createIdaTarget(); - const producer = new RecordingIdaMcp(target); + const producer = producerFor(target, protocol); const runner = new IdaOperationRunner(producer, protocol); try { for (const populated of [false, true]) { @@ -22,8 +27,6 @@ it.each(["legacy", "modern", "native"] as const)( ] : []; producer.overrideCall = (tool) => { - if (tool === "list_strings") - return { data: strings, next_offset: null }; if (tool === "find_regex") return { matches: strings.map(({ address, string }) => ({ @@ -50,14 +53,11 @@ it.each(["legacy", "modern", "native"] as const)( }, ); -it.each(["legacy", "modern", "native"] as const)( +it.each(["modern", "native"] as const)( "%s procedure resolution rejects file coordinates before any symbol lookup", async (protocol) => { const { root, target } = await createIdaTarget(); - const producer = new RecordingIdaMcp( - target, - protocol === "legacy" ? "attached" : "headless", - ); + const producer = producerFor(target, protocol); const runner = new IdaOperationRunner(producer, protocol); try { await expect( @@ -81,11 +81,11 @@ it.each(["legacy", "modern", "native"] as const)( }, ); -it.each(["legacy", "modern", "native"] as const)( +it.each(["modern", "native"] as const)( "%s retains function identities independently of unused source spans", async (protocol) => { const { root, target } = await createIdaTarget(); - const producer = new RecordingIdaMcp(target); + const producer = producerFor(target, protocol); const runner = new IdaOperationRunner(producer, protocol); try { // Cover omitted, malformed and normal source spans at the connection seam. @@ -96,20 +96,13 @@ it.each(["legacy", "modern", "native"] as const)( { size: "0x20" }, ]; for (const span of spans) { - const fn = { address: "0x1000", name: "main", ...span }; - const modernFn = { addr: fn.address, name: fn.name, ...span }; + const modernFn = { addr: "0x1000", name: "main", ...span }; producer.overrideCall = (tool) => { switch (tool) { - case "list_functions": - return { data: [fn], next_offset: null }; case "list_funcs": return [{ data: [modernFn], next_offset: null }]; - case "get_function_by_name": - return fn; case "lookup_funcs": return [{ query: "main", fn: modernFn, error: null }]; - case "get_xrefs_to": - return [{ address: "0x1004", type: "code", function: fn }]; case "xrefs_to": return [ { @@ -117,17 +110,6 @@ it.each(["legacy", "modern", "native"] as const)( more: false, }, ]; - case "disasm": - if (protocol === "native") - return { - asm: { - name: "main", - start_ea: "0x1000", - lines: "main (.text @ 0x1000):\n1000 ret", - }, - cursor: { done: true }, - }; - return undefined; default: return undefined; } @@ -159,14 +141,10 @@ it.each(["legacy", "modern", "native"] as const)( }, }, }); - const source = protocol === "legacy" ? fn : modernFn; expect(runner.raw).toContainEqual( expect.objectContaining({ - tool: protocol === "legacy" ? "list_functions" : "list_funcs", - result: - protocol === "legacy" - ? { data: [source], next_offset: null } - : [{ data: [source], next_offset: null }], + tool: "list_funcs", + result: [{ data: [modernFn], next_offset: null }], }), ); } @@ -175,7 +153,6 @@ it.each(["legacy", "modern", "native"] as const)( { address: "0x1000", name: "" }, ]) { producer.overrideCall = (tool): JsonValue | undefined => { - if (tool === "get_function_by_name") return malformed; if (tool === "lookup_funcs") return [{ query: "main", fn: malformed, error: null }]; return undefined; @@ -190,35 +167,24 @@ it.each(["legacy", "modern", "native"] as const)( ); it.each([ - ["legacy", "functions"], ["modern", "functions"], ["native", "functions"], - ["legacy", "strings"], ["modern", "strings"], ["native", "strings"], ] as const)( "%s %s inventory rejects a repeated or backward offset before another request", async (protocol, inventory) => { const { root, target } = await createIdaTarget(); - const producer = new RecordingIdaMcp(target); + const producer = producerFor(target, protocol); try { for (const next of [2, 1]) { let pages = 0; producer.overrideCall = (tool) => { - if ( - ![ - "list_functions", - "list_funcs", - "list_strings", - "find_regex", - ].includes(tool) - ) - return undefined; + if (!["list_funcs", "find_regex"].includes(tool)) return undefined; const nextOffset = pages++ === 0 ? 2 : next; if (tool === "find_regex") return { matches: [], cursor: { next: nextOffset } }; - const page = { data: [], next_offset: nextOffset }; - return tool === "list_funcs" ? [page] : page; + return [{ data: [], next_offset: nextOffset }]; }; const runner = new IdaOperationRunner(producer, protocol); await expect(runner[inventory]()).rejects.toMatchObject({ diff --git a/src/ida/IdaOperationRunner.ts b/src/ida/IdaOperationRunner.ts index cde3a6b982..f7b8e63e62 100644 --- a/src/ida/IdaOperationRunner.ts +++ b/src/ida/IdaOperationRunner.ts @@ -1,4 +1,3 @@ -import type { McpTextReplyKind } from "../providers/McpToolResult.js"; import type { RegexMatchingDeadline } from "../config/regexMatchingDeadline.js"; import type { RegexWorkerHeapRequest } from "../config/regexWorkerHeapRequest.js"; import { z } from "zod"; @@ -43,14 +42,9 @@ import { } from "./IdaProviderCapabilities.js"; import type { EvidenceLocation } from "../domain/evidence.js"; import { - disassemblySchema, idaAddressSchema, idaFunctionSchema, idaStringsPageSchema, - legacyCalleesSchema, - legacyPageSchema, - legacyStringSchema, - legacyXrefsSchema, modernCalleesSchema, modernDecompileSchema, modernDisassemblySchema, @@ -109,7 +103,7 @@ export class IdaOperationRunner { referencesTruncated: boolean | undefined; constructor( private readonly connection: IdaMcpConnection, - private readonly protocol: "legacy" | "modern" | "native", + private readonly protocol: "modern" | "native", private readonly database?: string, private readonly options: { readonly signal?: AbortSignal | undefined; @@ -130,7 +124,6 @@ export class IdaOperationRunner { async call( tool: string, args: Readonly>, - reply?: McpTextReplyKind, ): Promise { if (this.options.signal?.aborted) throw cancelledBy(tool, this.options.signal); @@ -138,7 +131,6 @@ export class IdaOperationRunner { this.database === undefined ? args : { ...args, database: this.database }; const result = await this.connection.call(tool, scoped, { signal: this.options.signal, - ...(reply === undefined ? {} : { reply }), }); this.raw.push({ tool, arguments: scoped, result }); if (this.options.signal?.aborted) @@ -151,16 +143,9 @@ export class IdaOperationRunner { let offset: number | null = 0; while (offset !== null) { const current: number = offset; - const value: z.infer | undefined = - this.protocol === "legacy" - ? legacyPageSchema.parse( - await this.call("list_functions", { offset, count: 100 }), - ) - : modernPageSchema.parse( - await this.call("list_funcs", { - queries: { offset, count: 100 }, - }), - )[0]; + const value = modernPageSchema.parse( + await this.call("list_funcs", { queries: { offset, count: 100 } }), + )[0]; if (value === undefined) throw new AnalysisProtocolError("IDA MCP omitted its function page."); result.push(...value.data.map((fn) => idaFunctionSchema.parse(fn))); @@ -192,31 +177,10 @@ export class IdaOperationRunner { }, ], ); - if (this.protocol !== "legacy") { - const item = modernLookupSchema.parse( - await this.call("lookup_funcs", { queries: [query] }), - )[0]; - return this.lookupFunction(query, item, requestedBy); - } - const address = idaAddressSchema.safeParse( - /^0x/iu.test(query) ? query : undefined, - ); - const found = idaFunctionSchema.parse( - await this.call( - address.success ? "get_function_by_address" : "get_function_by_name", - address.success ? { address: address.data } : { name: query }, - ), - ); - // Legacy producers may echo an interior query or call site in address. - // Resolve the reported symbol again to obtain its actual entry, never infer from size. - const entry = idaFunctionSchema.parse( - await this.call("get_function_by_name", { name: found.name }), - ); - if (entry.name !== found.name) - throw new AnalysisProtocolError( - "IDA function identity changed during lookup.", - ); - return entry; + const item = modernLookupSchema.parse( + await this.call("lookup_funcs", { queries: [query] }), + )[0]; + return this.lookupFunction(query, item, requestedBy); } /** Parse one lookup row: a function, an expected "missing" answer, or a producer failure. */ @@ -341,47 +305,29 @@ export class IdaOperationRunner { let offset: number | null = 0; while (offset !== null) { const current: number = offset; - if (this.protocol === "legacy") { - const page = legacyPageSchema.parse( - await this.call("list_strings", { offset, count: 0 }), + const page = idaStringsPageSchema.parse( + await this.call("find_regex", { + pattern: + this.protocol === "native" + ? (nativePattern ?? "[\\s\\S]*") + : "(?s).*", + offset, + limit: 100, + }), + ); + if (page.error !== undefined && page.error !== null) + throw new AnalysisProtocolError( + `${this.protocol === "native" ? "Native IDA" : "IDA"} string search failed: ${page.error}`, ); - for (const item of page.data) { - const s = legacyStringSchema.parse(item); - result.push({ address: s.address, value: s.string }); - } - offset = nextPageOffset(page.next_offset, current); - } else { - const page = idaStringsPageSchema.parse( - await this.call("find_regex", { - pattern: - this.protocol === "native" - ? (nativePattern ?? "[\\s\\S]*") - : "(?s).*", - offset, - limit: 100, - }), - ); - if (page.error !== undefined && page.error !== null) - throw new AnalysisProtocolError( - `${this.protocol === "native" ? "Native IDA" : "IDA"} string search failed: ${page.error}`, - ); - result.push( - ...page.matches.map((s) => ({ address: s.addr, value: s.string })), - ); - offset = nextOffset(page.cursor, current); - } + result.push( + ...page.matches.map((s) => ({ address: s.addr, value: s.string })), + ); + offset = nextOffset(page.cursor, current); } return result; } async assembly(fn: IdaFunction): Promise { - if (this.protocol === "legacy") { - const result = disassemblySchema.parse( - await this.call("disassemble_function", { start_address: fn.address }), - ); - this.verifyAssembly(fn, result); - return result; - } let result: IdaDisassembly | undefined; let offset: number | null = 0; while (offset !== null) { @@ -418,18 +364,6 @@ export class IdaOperationRunner { } async pseudocode(fn: IdaFunction): Promise { - if (this.protocol === "legacy") - return z - .string() - .nullable() - .parse( - // Legacy decompilation returns plain-text pseudocode. - await this.call( - "decompile_function", - { address: fn.address }, - "text", - ), - ); if (this.protocol === "native") { const page = nativeDecompileSchema.parse( await this.call("decompile", { addr: fn.address }), @@ -472,10 +406,6 @@ export class IdaOperationRunner { ): Promise< { address: string; type: string; function: IdaFunction | null }[] > { - if (this.protocol === "legacy") - return legacyXrefsSchema.parse( - await this.call("get_xrefs_to", { address }), - ); const page = ( this.protocol === "native" ? nativeXrefsSchema : modernXrefsSchema ).parse(await this.call("xrefs_to", { addrs: [address], limit: 1000 }))[0]; @@ -499,14 +429,9 @@ export class IdaOperationRunner { fn: IdaFunction, direction: "callers" | "callees", ): Promise { - const queries: string[] = []; const result = new Map>(); - let coverage: RelationshipCoverage = { - status: "unknown", - reason: "The legacy relationship response does not report coverage.", - }; if (this.readsCallGraph(direction)) { - coverage = await this.addCallGraphCallees(fn, result); + const coverage = await this.addCallGraphCallees(fn, result); return { items: [...result.values()], coverage, @@ -518,21 +443,7 @@ export class IdaOperationRunner { : { available: true }, }; } - if (this.protocol === "legacy") { - const value = await this.call( - direction === "callers" ? "get_callers" : "get_callees", - { function_address: fn.address }, - ); - const items = - direction === "callers" - ? z.array(idaFunctionSchema).parse(value) - : legacyCalleesSchema.parse(value); - for (const item of items) { - if ("type" in item && item.type === "external") - result.set(item.address, identity(item)); - else queries.push(item.name); - } - } else if (direction === "callers") { + if (direction === "callers") { this.limitations.push( "Upstream xrefs classify references as code or data, without proving call edges. Direct callers are unavailable in this profile.", ); @@ -549,49 +460,46 @@ export class IdaOperationRunner { "Upstream xrefs do not establish direct caller relationships.", }, }; - } else { - 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) - throw new AnalysisProtocolError( - `IDA callees failed: ${page?.error ?? "missing callees"}`, - ); - if (page.more === true) - this.limitations.push( - "Upstream callees capped results at 500; additional callees remain unknown.", - ); - coverage = { - ...(page.more === undefined - ? { - status: "unknown" as const, - reason: - "Upstream callees omitted an explicit truncation marker; additional callees remain unknown.", - } - : page.more - ? { - status: "partial" as const, - limitations: [ - "Upstream callees capped results at 500; additional callees remain unknown.", - ], - limited_directions: ["callees"] as const, - } - : { status: "complete" as const }), - discovery: IDA_CALLEE_DISCOVERY, - }; - for (const item of page.callees) { - if ("type" in item && item.type === "external") - result.set( - item.addr, - identity({ address: item.addr, name: item.name }), - ); - else queries.push(item.addr); - } } - const querySet = new Set(queries); - if (this.protocol !== "legacy" && querySet.size > 0) { + 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) + throw new AnalysisProtocolError( + `IDA callees failed: ${page?.error ?? "missing callees"}`, + ); + if (page.more === true) + this.limitations.push( + "Upstream callees capped results at 500; additional callees remain unknown.", + ); + const coverage: RelationshipCoverage = { + ...(page.more === undefined + ? { + status: "unknown" as const, + reason: + "Upstream callees omitted an explicit truncation marker; additional callees remain unknown.", + } + : page.more + ? { + status: "partial" as const, + limitations: [ + "Upstream callees capped results at 500; additional callees remain unknown.", + ], + limited_directions: ["callees"] as const, + } + : { status: "complete" as const }), + discovery: IDA_CALLEE_DISCOVERY, + }; + const querySet = new Set(); + for (const item of page.callees) { + if (item.type === "external") + result.set( + item.addr, + identity({ address: item.addr, name: item.name }), + ); + else querySet.add(item.addr); + } + if (querySet.size > 0) { const rows = modernLookupBatchSchema.parse( await this.call("lookup_funcs", { queries: [...querySet] }), ); @@ -610,11 +518,6 @@ export class IdaOperationRunner { ); result.set(resolved.address, resolved); } - } else { - for (const query of querySet) { - const resolved = identity(await this.resolve(query)); - result.set(resolved.address, resolved); - } } return { items: [...result.values()], @@ -712,15 +615,11 @@ export class IdaOperationRunner { case "procedure_assembly": return lines(await this.assembly(fn)).join("\n"); case "procedure_callers": - 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.", - ); - const relationships = await this.relationships( - fn, - operation === "procedure_callers" ? "callers" : "callees", + throw new AnalysisProtocolError( + "This IDA MCP profile cannot distinguish direct callers from other code references.", ); + case "procedure_callees": { + const relationships = await this.relationships(fn, "callees"); this.relationshipCoverage = relationships.coverage; return relationships.items.map(({ address }) => address); } diff --git a/src/ida/IdaProtocolValues.ts b/src/ida/IdaProtocolValues.ts index 509c2cce9d..15407a44a1 100644 --- a/src/ida/IdaProtocolValues.ts +++ b/src/ida/IdaProtocolValues.ts @@ -29,8 +29,8 @@ export const idaFunctionSchema = z.union([ ]); export type IdaFunction = z.infer; -/** Legacy metadata describes the recorded input, whereas modern health names live paths. */ -export const legacyMetadataSchema = z +/** Attached metadata describes the recorded input, whereas modern health names live paths. */ +export const attachedMetadataSchema = z .object({ path: z.string().min(1), module: z.string(), @@ -61,7 +61,7 @@ export const cursorSchema = z.union([ z.object({ next: z.int().nonnegative() }), z.object({ done: z.literal(true) }), ]); -/** Both legacy pages and modern cursors must finish or advance strictly. */ +/** Offset pages and cursors must finish or advance strictly. */ export const nextPageOffset = ( next: number | null, current: number, @@ -78,11 +78,15 @@ export const nextOffset = ( ): number | null => nextPageOffset("done" in cursor ? null : cursor.next, current); -export const legacyPageSchema = z.object({ - data: z.array(jsonValueSchema), - next_offset: z.int().nonnegative().nullable(), -}); -export const modernPageSchema = z.array(legacyPageSchema).length(1); +/** One `list_funcs` page: a single-query batch with an offset continuation. */ +export const modernPageSchema = z + .array( + z.object({ + data: z.array(jsonValueSchema), + next_offset: z.int().nonnegative().nullable(), + }), + ) + .length(1); const modernLookupRowSchema = z.object({ query: z.string(), @@ -129,23 +133,11 @@ export const modernDecompileSchema = z.object({ total_lines: z.int().nonnegative().optional(), }); -export const legacyStringSchema = z.object({ - address: idaAddressSchema, - string: z.string(), - length: z.int().nonnegative(), -}); export const idaStringsPageSchema = z.object({ matches: z.array(z.object({ addr: idaAddressSchema, string: z.string() })), cursor: cursorSchema, error: z.string().nullish(), }); -export const legacyXrefsSchema = z.array( - z.object({ - address: idaAddressSchema, - type: z.string(), - function: idaFunctionSchema.nullable(), - }), -); export const modernXrefsSchema = z .array( z.object({ @@ -205,9 +197,6 @@ export const modernCallGraphSchema = z .passthrough(), ) .length(1); -export const legacyCalleesSchema = z.array( - z.object({ address: idaAddressSchema, name: z.string() }).passthrough(), -); /** Parsed database lifecycle observations retain explicit ownership information. */ export const openDatabaseSchema = z diff --git a/src/ida/IdaProvider.test.ts b/src/ida/IdaProvider.test.ts index e4753ec0b7..991674b2eb 100644 --- a/src/ida/IdaProvider.test.ts +++ b/src/ida/IdaProvider.test.ts @@ -84,7 +84,7 @@ it("keeps a selected valid registration distinct from a live IDA connection", as JSON.stringify({ mode: "attached", url: "http://127.0.0.1:13337/mcp", - protocol: "legacy", + protocol: "native", }), ); const config = parseConfig({ REA_IDA_MCP_CONFIG: path }); @@ -333,12 +333,12 @@ it.each(["http", "stdio"] as const)( transport === "http" ? { url: "http://127.0.0.1:8745/mcp", - protocol: "legacy", + protocol: "native", headers: { Authorization: token, "X-Input": "retained" }, } : { command: "fixture", - protocol: "legacy", + protocol: "native", env: { PRIVATE_VALUE: token, IDADIR: "/fixture/ida" }, sensitive: { env: ["PRIVATE_VALUE"] }, }, @@ -366,7 +366,7 @@ it.each(["http", "stdio"] as const)( transport === "http" ? { url: "http://127.0.0.1:8745/mcp", - protocol: "legacy", + protocol: "native", headers: { Authorization: "second credential", "X-Input": "changed input", @@ -374,7 +374,7 @@ it.each(["http", "stdio"] as const)( } : { command: "fixture", - protocol: "legacy", + protocol: "native", env: { PRIVATE_VALUE: "second credential", IDADIR: "/changed/ida", @@ -405,7 +405,7 @@ it("applies runtime regex budgets through a bound IDA client and recovers in the JSON.stringify({ mode: "attached", url: "http://127.0.0.1:13337/mcp", - protocol: "legacy", + protocol: "native", }), ); const parsed = parseConfig({ REA_IDA_MCP_CONFIG: path }); @@ -414,10 +414,10 @@ it("applies runtime regex budgets through a bound IDA client and recovers in the const producer = new RecordingIdaMcp(target, "attached"); const value = "a".repeat(40) + "!"; producer.overrideCall = (name) => - name === "list_strings" + name === "find_regex" ? { - data: [{ address: "0x3000", length: value.length, string: value }], - next_offset: null, + matches: [{ addr: "0x3000", string: value }], + cursor: { done: true }, } : undefined; provider = new IdaProvider( diff --git a/src/ida/IdaProvider.ts b/src/ida/IdaProvider.ts index 077b7d917a..9570891f88 100644 --- a/src/ida/IdaProvider.ts +++ b/src/ida/IdaProvider.ts @@ -106,11 +106,6 @@ export class IdaProvider implements AnalysisProviderCandidate { } capabilities(): readonly CapabilityDescriptor[] { const profiles = [ - ...idaCapabilities( - IDA_COMPATIBILITY_PROFILES.legacy, - false, - this.#regexLimitation(), - ), ...idaCapabilities( IDA_COMPATIBILITY_PROFILES.native, true, diff --git a/src/ida/IdaProviderCapabilities.test.ts b/src/ida/IdaProviderCapabilities.test.ts index f533785bf1..cb35808824 100644 --- a/src/ida/IdaProviderCapabilities.test.ts +++ b/src/ida/IdaProviderCapabilities.test.ts @@ -24,10 +24,10 @@ describe("IDA profile operation admission", () => { expect(capability.reason).toBe(reason ?? null); } } + // No supported profile proves direct call edges. expect( - idaOperationUnavailableReason("procedure_callers", profile) === - undefined, - ).toBe(name === "legacy"); + idaOperationUnavailableReason("procedure_callers", profile), + ).toBeDefined(); expect( idaOperationUnavailableReason("procedure_callees", profile), ).toBeUndefined(); diff --git a/src/ida/IdaProviderCapabilities.ts b/src/ida/IdaProviderCapabilities.ts index ae5af1d00c..a8f197a907 100644 --- a/src/ida/IdaProviderCapabilities.ts +++ b/src/ida/IdaProviderCapabilities.ts @@ -27,10 +27,8 @@ export const idaOperationUnavailableReason = ( ): string | undefined => { if (!idaProfileAdmits(operation, profile)) return "This operation is available for the modern headless profile only."; - if (operation === "procedure_callers" && profile.protocol !== "legacy") - return profile.protocol === "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."; + if (operation === "procedure_callers") + return "IDA MCP profiles report code references without proving direct call edges."; return undefined; }; @@ -47,18 +45,6 @@ export const IDA_LIMITATIONS = Object.freeze([ export const IDA_NATIVE_STRING_LIMITATION = "Native string observations use upstream C-string rendering; other string representations remain unknown."; -/** - * The legacy attached profile uses `disassemble_function`, which - * jumps to the function and whose `decompile_function` opens or reuses a - * pseudocode view whenever an IDA window is active. - */ -const ATTACHED_GUI_NAVIGATION_OPERATIONS: ReadonlySet = new Set([ - "procedure_pseudo_code", - "procedure_assembly", - "read_function_instructions", - "analyze_function", -]); - /** Advertise live observations and configured lifecycle effects truthfully. */ export const idaCapabilities = ( profile: IdaCompatibilityProfile, @@ -79,12 +65,11 @@ export const idaCapabilities = ( effects: { mutatesArtifact: false, launchesProcess: stdio || profile.mode === "headless", + // Native GUI decompilation changes the active pseudocode view. mayShowUi: profile.mode === "attached" && - (profile.protocol === "native" - ? operation === "procedure_pseudo_code" || - operation === "analyze_function" - : ATTACHED_GUI_NAVIGATION_OPERATIONS.has(operation)), + (operation === "procedure_pseudo_code" || + operation === "analyze_function"), mayAccessNetwork: true, mayWriteFilesystem: stdio || profile.mode === "headless", changesPermissions: false, diff --git a/src/ida/IdaReferenceCoverage.test.ts b/src/ida/IdaReferenceCoverage.test.ts index 7859f4ffa7..d6b4e7dbe5 100644 --- a/src/ida/IdaReferenceCoverage.test.ts +++ b/src/ida/IdaReferenceCoverage.test.ts @@ -1,22 +1,10 @@ -import { rm } from "node:fs/promises"; import { afterEach, describe, expect, it } from "vitest"; -import { - createIdaTarget, - RecordingIdaMcp, -} from "../../tests/fixtures/idaMcp.js"; import { callGraphSession as session, removeCallGraphSessions, } from "../../tests/fixtures/idaCallGraph.js"; -import { IdaSessionClient } from "./IdaSessionClient.js"; - -const attachedRoots: string[] = []; -afterEach(async () => { - await removeCallGraphSessions(); - for (const root of attachedRoots.splice(0)) - await rm(root, { recursive: true, force: true }); -}); +afterEach(removeCallGraphSessions); const xrefs = async (more: boolean | undefined) => { const { client, producer } = await session({ callees: [] }, "x86_64"); @@ -68,30 +56,4 @@ describe("headless IDA reference coverage", () => { expect((await client.close()).ok).toBe(true); } }); - - it("reports nothing for the legacy profile, whose producer has no cap flag", async () => { - const { root, target } = await createIdaTarget("x86_64"); - attachedRoots.push(root); - const client = new IdaSessionClient( - { - command: "fixture", - args: [], - env: {}, - mode: "attached", - protocol: "legacy", - timeoutMs: 1000, - workspaceRoot: root, - }, - target, - new RecordingIdaMcp(target, "attached"), - ); - try { - const result = await client.execute("xrefs", { address: "0x1000" }); - - if (!result.ok) throw result.error; - expect(result.value.referencesTruncated).toBeUndefined(); - } finally { - expect((await client.close()).ok).toBe(true); - } - }); }); diff --git a/src/ida/IdaSessionClient.test.ts b/src/ida/IdaSessionClient.test.ts index 9152f0eb5f..b6df5c109a 100644 --- a/src/ida/IdaSessionClient.test.ts +++ b/src/ida/IdaSessionClient.test.ts @@ -80,7 +80,6 @@ const LIVE_PEER = { const fixture = async ( mode: "attached" | "headless" = "attached", timeoutMs = 1000, - protocol?: "native", ) => { const { root, target } = await createIdaTarget(); roots.push(root); @@ -91,7 +90,7 @@ const fixture = async ( args: [], env: {}, mode, - protocol: protocol ?? (mode === "attached" ? "legacy" : "modern"), + protocol: mode === "attached" ? "native" : "modern", timeoutMs, workspaceRoot: root, }, @@ -127,7 +126,7 @@ it.each([ url: selected, headers: { Authorization: "Bearer fixture-secret" }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }, target, @@ -162,7 +161,7 @@ it.each([ url: `http://localhost:1234/mcp?token=${encoded}&cursor=keep`, headers: { Authorization: "Bearer fixture-secret" }, mode: "attached", - protocol: "legacy", + protocol: "native", timeoutMs: 1000, }, target, @@ -487,9 +486,7 @@ describe("attached IDA input identity and validation", () => { }); expect(result.ok).toBe(true); - expect(producer.calls.some(({ name }) => name === "list_functions")).toBe( - true, - ); + expect(producer.calls.some(({ name }) => name === "list_funcs")).toBe(true); await client.close(); }); @@ -579,14 +576,17 @@ describe("attached IDA input identity and validation", () => { it("preserves hexadecimal-looking function names as names unless the caller uses an explicit 0x address", async () => { const { producer, client } = await fixture(); producer.overrideCall = (name, args) => - name === "get_function_by_name" && args.name === "f" - ? { address: "0x1000", name: "f", size: "0x20" } + name === "lookup_funcs" + ? [{ query: "f", fn: { addr: "0x1000", name: "f" }, error: null }] : undefined; const found = await client.execute("procedure_address", { procedure: "f" }); expect(found.ok && found.value.result).toBe("0x1000"); expect( - producer.calls.some(({ name }) => name === "get_function_by_address"), - ).toBe(false); + producer.calls + .filter(({ name }) => name === "lookup_funcs") + .map(({ args }) => args.queries), + "the selector is looked up by name, not rewritten as an address", + ).toEqual([["f"]]); await client.close(); }); it("preserves omitted optional arguments and rejects explicit null before connecting", async () => { @@ -613,14 +613,14 @@ describe("attached IDA input identity and validation", () => { (await client.execute("procedure_pseudo_code", { procedure: "main" })).ok, ).toBe(true); expect( - producer.calls.filter(({ name }) => name === "decompile_function"), + producer.calls.filter(({ name }) => name === "decompile"), ).toHaveLength(1); await client.close(); }); }); describe("attached IDA function observations", () => { - it("resolves interior addresses and call sites to canonical entries, preserves externals, and reports unknown body evidence", async () => { + it("resolves an interior address to its canonical entry, preserves externals, and reports unknown callers and body evidence", async () => { const { producer, client } = await fixture(); const result = await client.execute("analyze_function", { procedure: "0x1004", @@ -628,13 +628,16 @@ describe("attached IDA function observations", () => { if (!result.ok) throw result.error; const dossier = functionDossierSchema.parse(result.value.result); expect(dossier.procedure.address).toBe("0x1000"); - expect(dossier.callers.map((caller) => caller.address)).toEqual(["0x1000"]); + expect(dossier.callers).toEqual([]); + expect(dossier.facet_availability?.callers).toMatchObject({ + available: false, + }); expect(dossier.callees.map((callee) => callee.address)).toEqual(["0x2000"]); expect(dossier.procedure.body.available).toBe(false); expect(dossier.comments).toEqual([]); expect(result.value.rawResult).toMatchObject({ observations: expect.arrayContaining([ - expect.objectContaining({ tool: "get_callers" }), + expect.objectContaining({ tool: "callees" }), ]), }); expect(result.value.provider.version).toBe("1"); @@ -648,19 +651,19 @@ describe("attached IDA function observations", () => { }); it("returns complete paged inventory and distinguishes literal from regex search", async () => { const { producer, client } = await fixture(); - producer.overrideCall = (name, args) => - name === "list_functions" - ? { - data: [ - { - address: args.offset === 0 ? "0x1000" : "0x2000", - name: "main", - size: "0x10", - }, - ], - next_offset: args.offset === 0 ? 100 : null, - } - : undefined; + producer.overrideCall = (name, args) => { + if (name !== "list_funcs") return undefined; + const first = + z.object({ offset: z.number() }).parse(args.queries).offset === 0; + return [ + { + data: [ + { addr: first ? "0x1000" : "0x2000", name: "main", size: "0x10" }, + ], + next_offset: first ? 100 : null, + }, + ]; + }; const inventory = await client.execute("list_procedures", {}); expect(inventory.ok && inventory.value.result).toHaveLength(2); for (const [pattern, mode, count] of [ @@ -702,23 +705,24 @@ describe("attached IDA regex supervision", () => { const { producer, client } = await fixture(); const values = ["skip", "ÄPFEL", "äpfel"]; producer.overrideCall = (name) => - name === "list_functions" - ? { - data: values.map((name, index) => ({ - address: `0x${String(1000 + index)}`, - name, - size: "0x10", - })), - next_offset: null, - } - : name === "list_strings" - ? { - data: values.map((string, index) => ({ - address: `0x${String(3000 + index)}`, - length: string.length, - string, + name === "list_funcs" + ? [ + { + data: values.map((name, index) => ({ + addr: `0x${String(1000 + index)}`, + name, + size: "0x10", })), next_offset: null, + }, + ] + : name === "find_regex" + ? { + matches: values.map((string, index) => ({ + addr: `0x${String(3000 + index)}`, + string, + })), + cursor: { done: true }, } : undefined; try { @@ -752,17 +756,17 @@ describe("attached IDA regex supervision", () => { const { producer, client } = await fixture(); const value = "a".repeat(26) + "!"; producer.overrideCall = (name) => - name === "list_functions" - ? { - data: [{ address: "0x1000", name: value, size: "0x10" }], - next_offset: null, - } - : name === "list_strings" - ? { - data: [ - { address: "0x3000", length: value.length, string: value }, - ], + name === "list_funcs" + ? [ + { + data: [{ addr: "0x1000", name: value, size: "0x10" }], next_offset: null, + }, + ] + : name === "find_regex" + ? { + matches: [{ addr: "0x3000", string: value }], + cursor: { done: true }, } : undefined; await client.execute("health", {}); @@ -792,10 +796,10 @@ describe("attached IDA regex supervision", () => { const { producer, client } = await fixture(); const value = "a".repeat(40) + "!"; producer.overrideCall = (name) => - name === "list_strings" + name === "find_regex" ? { - data: [{ address: "0x3000", length: value.length, string: value }], - next_offset: null, + matches: [{ addr: "0x3000", string: value }], + cursor: { done: true }, } : undefined; try { @@ -856,10 +860,11 @@ describe("attached IDA function failure handling", () => { }, }); } - expect(producer.calls.map(({ name }) => name)).toEqual(["get_metadata"]); + expect(producer.calls).toEqual([]); + expect(producer.resources).toEqual(["ida://idb/metadata"]); producer.inputSha256 = target.sha256; producer.beforeCall = async (name) => { - if (name === "decompile_function") producer.imageBase = "0x2000"; + if (name === "decompile") producer.imageBase = "0x2000"; }; const changed = await client.execute("procedure_pseudo_code", { procedure: "main", @@ -888,10 +893,10 @@ describe("attached IDA function failure handling", () => { expect(invalidAddress.error._tag).toBe("AnalysisInputError"); expect(producer.connects).toBe(0); producer.overrideCall = (name) => - name === "list_functions" ? { data: [], next_offset: 0 } : undefined; + name === "list_funcs" ? [{ data: [], next_offset: 0 }] : undefined; expect((await client.execute("list_procedures", {})).ok).toBe(false); producer.overrideCall = (name) => - name === "decompile_function" ? { unexpected: true } : undefined; + name === "decompile" ? { unexpected: true } : undefined; const malformed = await client.execute("procedure_pseudo_code", { procedure: "main", }); @@ -904,7 +909,7 @@ describe("attached IDA function failure handling", () => { await client.execute("health", {}); const readOnlyCall = phaseGate(); producer.beforeCall = async (name) => { - if (name === "decompile_function") await readOnlyCall.hold(); + if (name === "decompile") await readOnlyCall.hold(); }; const controller = new AbortController(); const call = client.execute( @@ -1233,7 +1238,7 @@ describe("headless IDA non-busy health payloads", () => { describe("IDA compatibility profile mismatch", () => { it("reports the native profile for an incompatible catalog", async () => { - const { producer, client } = await fixture("attached", 1000, "native"); + const { producer, client } = await fixture("attached"); producer.tools = []; const result = await client.execute("health", {}); if (result.ok) throw new Error("Expected incompatible native catalog"); @@ -1281,9 +1286,9 @@ describe("IDA compatibility profile mismatch", () => { }); }); - it("reports the legacy profile when an attached producer serves modern tools", async () => { + it("reports the native profile when an attached registration reaches a database supervisor", async () => { const { producer, client } = await fixture("attached"); - producer.tools = ["server_health", "lookup_funcs", "decompile", "disasm"]; + producer.tools = ["idb_open", "idb_list", "idb_close", "server_health"]; const result = await client.execute("health", {}); expect(result.ok, "an incomplete profile cannot serve analysis").toBe( false, @@ -1291,9 +1296,13 @@ describe("IDA compatibility profile mismatch", () => { if (result.ok) return; expect( projectAnalysisError(result.error).details, - "attached mode names the legacy profile it expected", + "attached mode names the native profile it expected", ).toMatchObject({ - diagnostics: { mode: "attached", expected_profile: "legacy-1.4" }, + diagnostics: { + mode: "attached", + expected_profile: "native", + missing_tools: expect.arrayContaining(["list_funcs", "decompile"]), + }, }); }); }); @@ -2086,7 +2095,7 @@ it("binds retained transport diagnostics to the requested operation and recovery const { producer, client } = await fixture("attached"); await client.execute("health", {}); producer.beforeCall = async (name) => { - if (name === "list_functions") + if (name === "list_funcs") throw new ProviderAdapterError("ida", "transport", { diagnostics: { reason: "upstream closed" }, capturedOutput: { @@ -2111,46 +2120,14 @@ it("binds retained transport diagnostics to the requested operation and recovery await client.close(); }); -describe("attached IDA legacy string inventory", () => { - it("fetches legacy strings and literal searches in single upstream calls", async () => { - const { producer, client } = await fixture(); - const all = Array.from({ length: 250 }, (_, i) => ({ - address: `0x${(0x3000 + i).toString(16)}`, - length: 5, - string: `hello-${i}`, - })); - producer.overrideCall = (name, args) => { - if (name !== "list_strings") return undefined; - const offset = Number(args.offset ?? 0); - const count = Number(args.count ?? 100); - const data = count === 0 ? all : all.slice(offset, offset + count); - return { - data, - next_offset: - count === 0 || offset + count >= all.length ? null : offset + count, - }; - }; - const listed = await client.execute("list_strings", {}); - expect(listed.ok && listed.value.result).toHaveLength(250); - expect( - producer.calls.filter(({ name }) => name === "list_strings")[0]?.args - .count, - ).toBe(0); - expect( - producer.calls.filter(({ name }) => name === "list_strings"), - ).toHaveLength(1); - await client.close(); - }); -}); - it("retains transport diagnostics on a cancellation regardless of stderr", async () => { const { producer, client } = await fixture("attached"); await client.execute("health", {}); const controller = new AbortController(); producer.beforeCall = async (name) => { - if (name === "list_functions") { + if (name === "list_funcs") { controller.abort(); - throw new AnalysisCancelledError("list_functions", { + throw new AnalysisCancelledError("list_funcs", { cause: controller.signal.reason, diagnostics: { reason: "upstream closed after cancellation" }, capturedOutput: { @@ -2215,7 +2192,7 @@ it.each([false, true])( diagnostics: { reason: "upstream closed before cancellation" }, }); producer.beforeCall = async (name) => { - if (name !== "list_functions") return; + if (name !== "list_funcs") return; if (lateAbort) queueMicrotask(() => controller.abort({ caller: "late" })); throw failure; }; @@ -2267,8 +2244,23 @@ it.each(["before", "during"] as const)( }, ); +it("refuses null native IDA metadata before any analysis tool runs", async () => { + const { producer, client } = await fixture("attached"); + producer.tools = [...nativeTools]; + producer.overrideCall = (name) => + name === "ida://idb/metadata" ? null : undefined; + const result = await client.execute("procedure_pseudo_code", { + procedure: "main", + }); + if (result.ok) throw new Error("Expected null metadata to be refused"); + expect(result.error._tag).toBe("AnalysisOutputError"); + expect(producer.resources).toEqual(["ida://idb/metadata"]); + expect(producer.calls).toEqual([]); + await expectCleanClose(producer, client); +}); + it("attributes native IDA metadata timeout to the requested analysis operation", async () => { - const { producer, client } = await fixture("attached", 1000, "native"); + const { producer, client } = await fixture("attached"); producer.tools = [...nativeTools]; const timeout = new AnalysisTimeoutError("ida_mcp_read_resource", 40, { diagnostics: { uri: "ida://idb/metadata" }, @@ -2317,7 +2309,7 @@ it("keeps the session cleanup owner until an ignored-abort HTTP acquisition and url: "http://127.0.0.1:12345/mcp", headers: {}, mode: "attached" as const, - protocol: "legacy" as const, + protocol: "native" as const, timeoutMs: 30, }; const client = new IdaSessionClient( diff --git a/src/ida/IdaSessionClient.ts b/src/ida/IdaSessionClient.ts index 863068ae59..faf21ecf4d 100644 --- a/src/ida/IdaSessionClient.ts +++ b/src/ida/IdaSessionClient.ts @@ -44,9 +44,9 @@ import { } from "./IdaProviderMetadata.js"; import { absentDatabaseCloseSchema, + attachedMetadataSchema, closeDatabaseSchema, databaseListSchema, - legacyMetadataSchema, modernHealthSchema, openDatabaseSchema, rejectedOpenDatabaseSchema, @@ -71,18 +71,6 @@ import { } from "../providers/AnalysisClientFailure.js"; import { errorMessage } from "../kernel/errorMessage.js"; -const legacyTools = [ - "get_metadata", - "list_functions", - "list_strings", - "get_function_by_name", - "get_function_by_address", - "decompile_function", - "disassemble_function", - "get_callers", - "get_callees", - "get_xrefs_to", -]; const modernTools = [ "idb_open", "idb_list", @@ -663,12 +651,11 @@ export class IdaSessionClient implements AnalysisClient { const profile = idaCompatibilityProfile(this.config); const expected = { native: nativeTools, - legacy: legacyTools, modern: modernTools, }[profile.protocol]; const missing = expected.filter((name) => !tools.has(name)); if (missing.length > 0) { - const summary = `IDA MCP ${profile.diagnosticLabel} 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/providers/ida-provider.md.`; + const summary = `IDA MCP ${profile.diagnosticLabel} compatibility profile is missing tools: ${missing.join(", ")}. Attached mode requires the native IDA MCP tool catalog; headless mode requires the database supervisor profile. See docs/providers/ida-provider.md.`; // The caller cannot act on a profile mismatch it never sees, so the // missing names travel as adapter diagnostics rather than a bare message. throw new ProviderAdapterError("ida", "initialize", { @@ -763,15 +750,8 @@ export class IdaSessionClient implements AnalysisClient { ): Promise { let identity: string; if (this.config.mode === "attached") { - const raw = - idaCompatibilityProfile(this.config).protocol === "native" - ? await this.#nativeMetadata(options?.signal) - : await this.connection.call( - "get_metadata", - {}, - { signal: options?.signal }, - ); - const metadata = legacyMetadataSchema.parse(raw); + const raw = await this.#nativeMetadata(options?.signal); + const metadata = attachedMetadataSchema.parse(raw); this.#metadata = raw; onObserved?.(raw); if (metadata.sha256.toLowerCase() !== this.target.sha256.toLowerCase()) diff --git a/src/jeb/JebMcpConnection.ts b/src/jeb/JebMcpConnection.ts index 245f34f140..d6445de67f 100644 --- a/src/jeb/JebMcpConnection.ts +++ b/src/jeb/JebMcpConnection.ts @@ -2,7 +2,7 @@ import { SdkError, type Client } from "@modelcontextprotocol/client"; import { mcpToolResultSchema, mcpTextBlocks, - decodeMcpTextReply, + decodeMcpJsonText, } from "../providers/McpToolResult.js"; import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js"; import { @@ -70,7 +70,7 @@ export const decodeJebToolResult = (input: unknown): JsonValue => { throw new AnalysisProtocolError( "JEB MCP omitted a single structured or text result; unsupported content cannot establish an empty observation.", ); - const text = decodeMcpTextReply(blocks[0]!, "json"); + const text = decodeMcpJsonText(blocks[0]!); if (!text.ok && result.isError !== true) throw new AnalysisProtocolError("JEB MCP returned malformed JSON text", { cause: text.error.cause, diff --git a/src/providers/McpToolResult.ts b/src/providers/McpToolResult.ts index 49383868e2..8227c0ab4a 100644 --- a/src/providers/McpToolResult.ts +++ b/src/providers/McpToolResult.ts @@ -27,24 +27,19 @@ export const mcpTextBlocks = ( block.type === "text" && block.text !== undefined ? [block.text] : [], ); -/** - * What a tool's single text block carries. Each tool declares it; malformed - * JSON is never reinterpreted as ordinary text. - */ -export type McpTextReplyKind = "json" | "text"; - -/** Text declared as JSON did not parse. */ +/** A text block that should carry JSON did not parse. */ export interface McpMalformedJsonText { readonly reason: "malformed_json"; readonly cause: unknown; } -/** Decode one text block as its declared reply kind. */ -export const decodeMcpTextReply = ( +/** + * Decode one text block as JSON. Malformed JSON is never reinterpreted as + * ordinary text. + */ +export const decodeMcpJsonText = ( text: string, - kind: McpTextReplyKind, ): Result => { - if (kind === "text") return ok(text); const parsed = safeParseJson(text); if (!parsed.ok) return err({ reason: "malformed_json", cause: parsed.cause }); // A parsed JSON value must satisfy the same admission rules as structured diff --git a/tests/acceptance/providers/idaEndpointFailure.test.ts b/tests/acceptance/providers/idaEndpointFailure.test.ts index 667fc795fe..e878af50d0 100644 --- a/tests/acceptance/providers/idaEndpointFailure.test.ts +++ b/tests/acceptance/providers/idaEndpointFailure.test.ts @@ -38,7 +38,7 @@ for (const encodedCredential of [false, true]) registration, JSON.stringify({ url: endpoint, - protocol: "legacy", + protocol: "native", headers: { Authorization: "Bearer fixture-secret" }, }), ); diff --git a/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts b/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts index 89e3013109..d524ce09d2 100644 --- a/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts +++ b/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts @@ -787,7 +787,7 @@ for (const [client, provider] of [ idaConfig, JSON.stringify({ url: "http://127.0.0.1:12345/mcp", - protocol: "legacy", + protocol: "native", headers: { Authorization: "Bearer fixture-credential" }, timeoutMs, }), diff --git a/tests/boundary/cli/idaDoctorRegistration.test.ts b/tests/boundary/cli/idaDoctorRegistration.test.ts index 9f5ff8c1b9..717d6a348b 100644 --- a/tests/boundary/cli/idaDoctorRegistration.test.ts +++ b/tests/boundary/cli/idaDoctorRegistration.test.ts @@ -127,7 +127,7 @@ cliTest.for([ name: `valid timeout ${String(timeoutMs)}`, registration: { command: "provider-must-not-launch", - protocol: "legacy", + protocol: "native", timeoutMs, }, constraint: undefined, @@ -137,7 +137,7 @@ cliTest.for([ registration: { command: "provider-must-not-launch", args: [], - protocol: "legacy", + protocol: "native", }, constraint: undefined, }, diff --git a/tests/boundary/mcp/idaToolEffects.test.ts b/tests/boundary/mcp/idaToolEffects.test.ts index 6169e4ae92..84a26f0edf 100644 --- a/tests/boundary/mcp/idaToolEffects.test.ts +++ b/tests/boundary/mcp/idaToolEffects.test.ts @@ -9,14 +9,15 @@ import { createTestBinarySession } from "../../fixtures/binarySession.js"; import { createIdaTarget, RecordingIdaMcp } from "../../fixtures/idaMcp.js"; import { createTestMcp } from "../../support/mcp/mcpFixture.js"; -const ATTACHED_IDA_NAVIGATION = [ - "procedure_pseudo_code", +/** Native GUI decompilation changes the active view; assembly reads do not. */ +const ATTACHED_IDA_UI = ["procedure_pseudo_code", "analyze_function"] as const; +const ATTACHED_IDA_READS = [ + ...ATTACHED_IDA_UI, "procedure_assembly", "read_function_instructions", - "analyze_function", ] as const; const IDA_NETWORK_DISCOVERY = [ - ...ATTACHED_IDA_NAVIGATION, + ...ATTACHED_IDA_READS, "list_procedures", "search_strings", "batch_decompile", @@ -67,7 +68,7 @@ it("advertises attached IDA UI and network effects in SDK and session discovery" JSON.stringify({ command: "fixture", mode: "attached", - protocol: "legacy", + protocol: "native", }), ); const config = parseConfig({ REA_IDA_MCP_CONFIG: registration }); @@ -89,7 +90,7 @@ it("advertises attached IDA UI and network effects in SDK and session discovery" const client = await mcp.connect(server); const tools = (await client.listTools()).tools; - for (const name of ATTACHED_IDA_NAVIGATION) { + for (const name of ATTACHED_IDA_READS) { const response = await client.callTool({ name, arguments: { procedure: "main" }, @@ -110,7 +111,13 @@ it("advertises attached IDA UI and network effects in SDK and session discovery" ); expect(ida).toBeDefined(); - for (const name of ATTACHED_IDA_NAVIGATION) { + for (const name of ["procedure_assembly", "read_function_instructions"]) { + const availability = status.tool_availability.groups.find(({ names }) => + names.includes(name), + ); + expect(availability?.effects, name).not.toContain("changesUiState"); + } + for (const name of ATTACHED_IDA_UI) { const capability = ida?.groups.find(({ operations }) => operations.includes(name), ); diff --git a/tests/boundary/mcp/idaTransport.test.ts b/tests/boundary/mcp/idaTransport.test.ts index 834ad80168..f2464133f7 100644 --- a/tests/boundary/mcp/idaTransport.test.ts +++ b/tests/boundary/mcp/idaTransport.test.ts @@ -273,7 +273,7 @@ it("reads native metadata resources and complete JSON text through the real SDK expect(methods).toContain("resources/read"); }); -it("accepts a legacy stdio reply over the SDK default while staying bounded", async () => { +it("accepts a large structured stdio reply over the SDK default while staying bounded", async () => { const script = String.raw` let input = ""; const send = (message) => process.stdout.write(JSON.stringify(message) + "\n"); @@ -289,7 +289,7 @@ process.stdin.on("data", (chunk) => { const result = request.method === "initialize" ? { protocolVersion: request.params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "large-reply-fixture", version: "1" } } : request.method === "tools/list" - ? { tools: [{ name: "list_strings", inputSchema: { type: "object", properties: {} } }] } + ? { tools: [{ name: "find_regex", inputSchema: { type: "object", properties: {} } }] } : { content: [{ type: "text", text: "fixture" }], structuredContent: { result: "x".repeat(11 * 1024 * 1024) } }; send({ jsonrpc: "2.0", id: request.id, result }); } @@ -300,16 +300,16 @@ process.stdin.on("data", (chunk) => { command: process.execPath, args: ["-e", script], env: {}, - mode: "attached", - protocol: "legacy", + mode: "headless", + protocol: "modern", timeoutMs: 10_000, }, {}, idaConnectionDependencies(), ); cleanups.push(() => connection.close()); - expect(await connection.connect()).toEqual(["list_strings"]); - expect(await connection.call("list_strings", {})).toEqual( + expect(await connection.connect()).toEqual(["find_regex"]); + expect(await connection.call("find_regex", {})).toEqual( "x".repeat(11 * 1024 * 1024), ); }); diff --git a/tests/boundary/providers/ida/functionIdentity.test.ts b/tests/boundary/providers/ida/functionIdentity.test.ts index 307ab4afe9..8c56ced29a 100644 --- a/tests/boundary/providers/ida/functionIdentity.test.ts +++ b/tests/boundary/providers/ida/functionIdentity.test.ts @@ -36,26 +36,15 @@ const session = async ( const { root, target } = await createIdaTarget(); roots.push(root); const producer = new RecordingIdaMcp(target, mode); - const fn = { - [mode === "attached" ? "address" : "addr"]: "0x1000", - name: "main", - ...fields, - }; - const page = { data: [fn], next_offset: null }; + const fn = { addr: "0x1000", name: "main", ...fields }; + const inventory = [{ data: [fn], next_offset: null }]; const lookup = [{ query: "main", fn, error: null }]; producer.overrideCall = (name) => { switch (name) { - case "list_functions": - return page; case "list_funcs": - return [page]; - case "get_function_by_name": - return fn; + return inventory; case "lookup_funcs": return lookup; - case "get_callers": - case "get_callees": - return []; case "callees": return [{ callees: [], more: false }]; default: @@ -68,19 +57,14 @@ const session = async ( args: [], env: {}, mode, - protocol: mode === "attached" ? "legacy" : "modern", + protocol: mode === "attached" ? "native" : "modern", timeoutMs: 1000, workspaceRoot: root, }, target, producer, ); - return { - client, - inventoryObservation: mode === "attached" ? page : [page], - lookupObservation: mode === "attached" ? fn : lookup, - lookupTool: mode === "attached" ? "get_function_by_name" : "lookup_funcs", - }; + return { client, inventoryObservation: inventory, lookupObservation: lookup }; }; describe.each(["attached", "headless"] as const)( @@ -101,12 +85,9 @@ describe.each(["attached", "headless"] as const)( expect(inventory.value.result).toEqual([ { address: "0x1000", value: "main" }, ]); - expect( - observation( - inventory.value.rawResult, - mode === "attached" ? "list_functions" : "list_funcs", - ), - ).toEqual(fixture.inventoryObservation); + expect(observation(inventory.value.rawResult, "list_funcs")).toEqual( + fixture.inventoryObservation, + ); const analyzed = await fixture.client.execute("analyze_function", { procedure: "main", @@ -118,9 +99,9 @@ describe.each(["attached", "headless"] as const)( name: "main", body: { available: false, reason: expect.any(String) }, }); - expect( - observation(analyzed.value.rawResult, fixture.lookupTool), - ).toEqual(fixture.lookupObservation); + expect(observation(analyzed.value.rawResult, "lookup_funcs")).toEqual( + fixture.lookupObservation, + ); } finally { expect((await fixture.client.close()).ok).toBe(true); } @@ -152,11 +133,7 @@ describe.each(["attached", "headless"] as const)( expect( observation( partial.raw_result, - operation === "list_procedures" - ? mode === "attached" - ? "list_functions" - : "list_funcs" - : fixture.lookupTool, + operation === "list_procedures" ? "list_funcs" : "lookup_funcs", ), ).toEqual( operation === "list_procedures" diff --git a/tests/boundary/providers/ida/idaCapabilityInventory.test.ts b/tests/boundary/providers/ida/idaCapabilityInventory.test.ts index 022faf4a00..945fd99ba3 100644 --- a/tests/boundary/providers/ida/idaCapabilityInventory.test.ts +++ b/tests/boundary/providers/ida/idaCapabilityInventory.test.ts @@ -58,7 +58,7 @@ it("retains network cleanup effects in session discovery for lifecycle tools", ( }); it("keeps retryable IDA effects in composed discovery while preserving unavailability", () => { - const ida = idaCapabilities(IDA_COMPATIBILITY_PROFILES.legacy, false); + const ida = idaCapabilities(IDA_COMPATIBILITY_PROFILES.native, false); const statusFor = (runtimeUnavailable: boolean) => ({ open: true, kind: "executable", @@ -99,7 +99,7 @@ it("keeps retryable IDA effects in composed discovery while preserving unavailab }); it.each([ - ["legacy", false], + ["native", false], ["native", true], ["modern", true], ] as const)( @@ -131,7 +131,7 @@ it.each([false, true])( kind: "executable", capabilities: providerCapabilitySets( idaCapabilities( - IDA_COMPATIBILITY_PROFILES[showUi ? "legacy" : "modern"], + IDA_COMPATIBILITY_PROFILES[showUi ? "native" : "modern"], false, ), ), @@ -139,8 +139,6 @@ it.each([false, true])( const entries = buildCapabilityInventory(input, enabledPolicy); for (const name of [ "procedure_pseudo_code", - "procedure_assembly", - "read_function_instructions", "analyze_function", "batch_decompile", "decompile_all", @@ -155,7 +153,13 @@ it.each([false, true])( annotations: { open_world: true }, }); } - for (const name of ["list_procedures", "search_strings", "trace_feature"]) { + for (const name of [ + "procedure_assembly", + "read_function_instructions", + "list_procedures", + "search_strings", + "trace_feature", + ]) { expect(entries.find((entry) => entry.name === name)).toMatchObject({ effects: { changesUiState: false, accessesNetwork: true }, annotations: { open_world: true }, @@ -170,7 +174,7 @@ it("omits effects of IDA calls hidden behind unavailable workflow prerequisites" open: true, kind: "executable", capabilities: providerCapabilitySets( - idaCapabilities(IDA_COMPATIBILITY_PROFILES.legacy, false), + idaCapabilities(IDA_COMPATIBILITY_PROFILES.native, false), ), }, enabledPolicy, @@ -197,7 +201,7 @@ it("omits effects of IDA calls hidden behind unavailable workflow prerequisites" }); it("advertises reachable IDA calls through native UI tracing", () => { - const ida = idaCapabilities(IDA_COMPATIBILITY_PROFILES.legacy, false); + const ida = idaCapabilities(IDA_COMPATIBILITY_PROFILES.native, false); const source = ida[0]; if (source === undefined) throw new Error("IDA capability fixture is empty"); const metadata = { diff --git a/tests/boundary/providers/ida/verifierRequirements.test.ts b/tests/boundary/providers/ida/verifierRequirements.test.ts index 143ca97f39..403ed4dc42 100644 --- a/tests/boundary/providers/ida/verifierRequirements.test.ts +++ b/tests/boundary/providers/ida/verifierRequirements.test.ts @@ -14,7 +14,6 @@ it.each([ flags: ["--second-procedure", "other", "--second-marker", "unique"], required: false, }, - { protocol: "legacy", flags: [], required: false }, { protocol: "modern", flags: [], required: false }, ])( "enforces native switching requirements for $protocol with $flags", diff --git a/tests/composition/idaProvider.test.ts b/tests/composition/idaProvider.test.ts index 404011c311..78e4db9a9b 100644 --- a/tests/composition/idaProvider.test.ts +++ b/tests/composition/idaProvider.test.ts @@ -36,7 +36,7 @@ const reobservesExternallyMutableState = async (): Promise => { const path = join(root, "registration.json"); await writeFile( path, - JSON.stringify({ command: "fixture", protocol: "legacy" }), + JSON.stringify({ command: "fixture", protocol: "native" }), ); const config = parseConfig({ REA_IDA_MCP_CONFIG: path }); if (!config.ok) throw config.error; @@ -94,7 +94,7 @@ const reobservesExternallyMutableState = async (): Promise => { const second = await session.execute("procedure_pseudo_code", query); expect(second.ok && second.value.result).toContain("99"); expect( - producer.calls.filter(({ name }) => name === "decompile_function"), + producer.calls.filter(({ name }) => name === "decompile"), ).toHaveLength(2); await session.close(); expect(producer.closes).toBe(1); @@ -203,7 +203,7 @@ describe("IDA provider selection cancellation", () => { const path = join(first.root, "registration.json"); await writeFile( path, - JSON.stringify({ command: "first-server", protocol: "legacy" }), + JSON.stringify({ command: "first-server", protocol: "native" }), ); const config = parseConfig({ REA_IDA_MCP_CONFIG: path }); if (!config.ok) throw config.error; @@ -235,7 +235,7 @@ describe("IDA provider selection cancellation", () => { ).toBe(true); await writeFile( path, - JSON.stringify({ command: "replacement-server", protocol: "legacy" }), + JSON.stringify({ command: "replacement-server", protocol: "native" }), ); cancelWhenPreviousCloses = true; const replacement = await session.open(second.target.path, { @@ -327,11 +327,11 @@ describe("IDA universal Mach-O target identity", () => { it.each([ { - profile: "legacy attached", - registration: { command: "fixture", protocol: "legacy" }, + profile: "native stdio attached", + registration: { command: "fixture", protocol: "native" }, }, { - profile: "native attached", + profile: "native HTTP attached", registration: { url: "http://127.0.0.1:13337/mcp", mode: "attached", @@ -378,7 +378,7 @@ describe("IDA binary_overview execution", () => { const path = join(root, "registration.json"); await writeFile( path, - JSON.stringify({ command: "fixture", protocol: "legacy" }), + JSON.stringify({ command: "fixture", protocol: "native" }), ); const config = parseConfig({ REA_IDA_MCP_CONFIG: path }); if (!config.ok) throw config.error; diff --git a/tests/conformance/ida/providerContracts.test.ts b/tests/conformance/ida/providerContracts.test.ts index 77e8287eee..de9ff7e6b7 100644 --- a/tests/conformance/ida/providerContracts.test.ts +++ b/tests/conformance/ida/providerContracts.test.ts @@ -18,11 +18,9 @@ afterEach(async () => { for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true }); }); -/** Pinned upstream tools that navigate an active IDA GUI as a side effect. */ -const GUI_NAVIGATING_TOOLS: ReadonlySet = new Set([ - "disassemble_function", - "decompile_function", -]); +/** Native GUI decompilation changes the active view; headless tools never do. */ +const guiNavigatingTool = (mode: "attached" | "headless", name: string) => + mode === "attached" && name === "decompile"; const parametersFor = ( operation: string, @@ -63,7 +61,7 @@ describe.each(["attached", "headless"] as const)( args: [], env: {}, mode, - protocol: mode === "attached" ? "legacy" : "modern", + protocol: mode === "attached" ? "native" : "modern", workspaceRoot: root, timeoutMs: 1000, }, @@ -75,14 +73,14 @@ describe.each(["attached", "headless"] as const)( const execution = await client.execute(operation, parameters); const descriptor = idaCapabilities( IDA_COMPATIBILITY_PROFILES[ - mode === "attached" ? "legacy" : "modern" + mode === "attached" ? "native" : "modern" ], true, ).find((capability) => capability.operation === operation); expect(descriptor?.effects.mayShowUi).toBe( - producer.calls.some(({ name }) => GUI_NAVIGATING_TOOLS.has(name)), + producer.calls.some(({ name }) => guiNavigatingTool(mode, name)), ); - if (mode === "headless" && operation === "procedure_callers") { + if (operation === "procedure_callers") { expect(execution.ok).toBe(false); if (!execution.ok) expect(execution.error._tag).toBe( diff --git a/tests/fixtures/idaMcp.ts b/tests/fixtures/idaMcp.ts index 84682142fc..8e6a07eb5c 100644 --- a/tests/fixtures/idaMcp.ts +++ b/tests/fixtures/idaMcp.ts @@ -32,17 +32,14 @@ export const createIdaTarget = async ( return { root, target }; }; -const legacyNames = [ - "get_metadata", - "list_functions", - "list_strings", - "get_function_by_name", - "get_function_by_address", - "decompile_function", - "disassemble_function", - "get_callers", - "get_callees", - "get_xrefs_to", +const nativeNames = [ + "list_funcs", + "lookup_funcs", + "find_regex", + "decompile", + "disasm", + "callees", + "xrefs_to", ]; const modernNames = [ "idb_open", @@ -60,7 +57,11 @@ const modernNames = [ "survey_binary", ]; -/** Stateful producer fixture at the real connection seam; no module mocking. */ +/** + * Stateful producer fixture at the real connection seam; no module mocking. + * Attached mode serves the native ida-free-mcp protocol (metadata through + * `ida://idb/metadata`); headless mode serves the database supervisor. + */ export class RecordingIdaMcp implements IdaMcpConnection { readonly calls: { name: string; @@ -95,10 +96,31 @@ export class RecordingIdaMcp implements IdaMcpConnection { } /** Tool names the fake server advertises; defaults to the profile's full set. */ tools?: readonly string[]; - readResource?: NonNullable; + readonly resources: string[] = []; + /** The recorded input metadata a native attached server reports. */ + metadata(): JsonValue { + return { + path: `${this.inputPath}.i64`, + module: "target.elf", + sha256: this.inputSha256, + base: this.imageBase, + }; + } + readResource = async ( + uri: string, + options?: { readonly signal?: AbortSignal | undefined }, + ): Promise => { + this.resources.push(uri); + await this.beforeCall?.(uri, {}); + options?.signal?.throwIfAborted(); + if (uri !== "ida://idb/metadata") + throw new Error(`Unimplemented producer resource ${uri}`); + const overridden = this.overrideCall?.(uri, {}); + return overridden === undefined ? this.metadata() : overridden; + }; async connect() { this.connects += 1; - return this.tools ?? (this.mode === "attached" ? legacyNames : modernNames); + return this.tools ?? (this.mode === "attached" ? nativeNames : modernNames); } serverInfo() { return { name: "upstream-fixture", version: "sdk-version-is-not-ida" }; @@ -140,16 +162,8 @@ export class RecordingIdaMcp implements IdaMcpConnection { return_type: "int", arguments: [], }; + const native = this.mode === "attached"; switch (name) { - case "get_metadata": - return { - path: this.inputPath, - module: "target.elf", - sha256: this.inputSha256, - base: this.imageBase, - }; - case "list_functions": - return { data: [fn], next_offset: null }; case "list_funcs": return [ { @@ -157,10 +171,6 @@ export class RecordingIdaMcp implements IdaMcpConnection { next_offset: null, }, ]; - case "get_function_by_address": - return { ...fn, address: "0x1004" }; - case "get_function_by_name": - return fn; case "lookup_funcs": if (!Array.isArray(args.queries)) throw new Error("Invalid fixture lookup queries"); @@ -169,30 +179,34 @@ export class RecordingIdaMcp implements IdaMcpConnection { fn: { addr: fn.address, name: fn.name, size: fn.size }, error: null, })); - case "decompile_function": - return this.pseudocode; case "decompile": - return { code: this.pseudocode, cursor: { done: true } }; - case "disassemble_function": - return asm; + return native + ? { + addr: fn.address, + ok: true, + pseudocode: this.pseudocode, + lines: 1, + } + : { code: this.pseudocode, cursor: { done: true } }; case "disasm": - return { asm, cursor: { done: true } }; - case "get_callers": - return [ - { address: "0x1004", name: "main", size: "0x20" }, - { address: "0x1008", name: "main", size: "0x20" }, - ]; - case "get_callees": - return [{ address: "0x2000", name: "puts", type: "external" }]; + return native + ? { + asm: { + name: asm.name, + start_ea: asm.start_ea, + lines: `main (.text @ ${asm.start_ea}):\n1000 ret`, + }, + cursor: { done: true }, + } + : { asm, cursor: { done: true } }; case "callees": return [ { callees: [{ addr: "0x2000", name: "puts", type: "external" }], more: false, + ...(native ? { error: null } : {}), }, ]; - case "get_xrefs_to": - return [{ address: "0x1004", type: "code", function: fn }]; case "xrefs_to": return [ { @@ -204,13 +218,9 @@ export class RecordingIdaMcp implements IdaMcpConnection { }, ], more: false, + ...(native ? { error: null } : {}), }, ]; - case "list_strings": - return { - data: [{ address: "0x3000", length: 5, string: "a.b\nC" }], - next_offset: null, - }; case "find_regex": return { matches: [{ addr: "0x3000", string: "a.b\nC" }],