Skip to main content

rf_mcp/
lib.rs

1//! rf-mcp — MCP (Model Context Protocol) server wrapping rop-finder
2//! (PLAN.md §6.1).
3//!
4//! stdio transport only (v1): no network attack surface. The server exposes
5//! eight tools, all returning structured JSON:
6//!
7//!   * `find_gadgets` / `find_jop_gadgets` / `find_syscall_gadgets` —
8//!     gadget scans restricted to one anchor family.
9//!   * `get_binary_info` — the CLI's `--info` payload.
10//!   * `search_gadgets_by_pattern` — regex (or substring) over gadget text.
11//!   * `run_ropgadget_command` — flag passthrough restricted to the PLAN
12//!     §6.1 allowlist.
13//!   * `build_rop_chain` — the PLAN §6.2 chain builder.
14//!   * `get_server_config` — the effective allowlist and caps, so an agent
15//!     never has to guess a path.
16//!
17//! Security model (hardened per PLAN §6.1, review-driven):
18//!   * `binary_path` is confined to a directory allowlist built *only* from
19//!     `--allow-dir` (MCP-02: there is no cwd default; the server refuses to
20//!     start without one). Confinement is enforced by [`confine`], which
21//!     opens the file from a directory handle pinned at startup and hands the
22//!     rest of the server a HANDLE, never a path — so nothing can be swapped
23//!     between the check and the read (MCP-01).
24//!   * Every rejected path returns exactly one code, `path_denied`, with no
25//!     OS error text, so the error taxonomy cannot be used to enumerate the
26//!     filesystem (MCP-07). `--verbose-path-errors` restores detail inside
27//!     allowed roots only.
28//!   * `run_ropgadget_command` rejects any flag outside the allowlist —
29//!     side-channel flags (`--dump`, `--string`, `--memstr`, `--console`)
30//!     are never accepted.
31//!   * Resource caps: `max_results` (default 1000, hard max 50000), a
32//!     per-request timeout (default 60 s), `--max-depth` (default 64,
33//!     over-large values are *rejected*, not clamped), `--max-file-bytes`
34//!     (default 256 MiB, enforced by fstat on the confined handle),
35//!     `--max-gadgets` (default 5 000 000, enforced in the engine) and
36//!     `--max-concurrent` (default 2). Every tool without exception runs
37//!     through [`guard::Guard::run`], which cancels the *work* on timeout
38//!     and JOINS it before releasing the permit (MCP-03/PERF-06), and
39//!     inside an explicit rayon pool sized by `--scan-threads`.
40//!   * Content-hash cache (SHA-256 of file + parameters): a byte-weighted
41//!     LRU with a TTL (`--cache-mem-mb`, `--cache-ttl-secs`), with an
42//!     optional authenticated on-disk spill via `--cache-dir`.
43//!   * Observability: `tracing` to **stderr only**, `--audit-log` (one
44//!     JSON object per line, mode 0600, rotated), the `get_server_stats`
45//!     tool, and the MCP `logging` capability so warnings reach an
46//!     operator who never sees stderr (MCP-09).
47//!   * Responses are sampled: up to `max_results` gadgets plus
48//!     `total_count` and `truncated`. (PLAN calls for "top-N by quality
49//!     rank"; ranking lands in Phase 5, so v1 returns the first N in the
50//!     engine's deterministic traversal order.)
51//!   * Errors are structured JSON `{error: {code, message, details?}}` with
52//!     the MCP `isError` flag; the server never panics on malformed input.
53
54// ROB-04. The char-boundary panic (`&c.bytes[i..i + 2]` on a `&str`) was
55// reachable from a poisoned cache entry through the live server. Denying
56// the two lints that permit it means the bug class cannot come back by
57// accident; the checked decoders in `rf_cache` are the way to write it.
58#![deny(clippy::indexing_slicing, clippy::string_slice)]
59
60// `confine` predates this rule and has four indexing sites of its own; the
61// attribute on the module declaration keeps them compiling without editing
62// a file this change has no other business in. Its own wave removes them.
63#[allow(clippy::indexing_slicing)]
64pub mod confine;
65
66pub mod audit;
67pub mod cache;
68pub mod checksec;
69pub mod cursor;
70pub mod find;
71pub mod guard;
72pub mod logging;
73pub mod pattern;
74pub mod resources;
75pub mod scan;
76pub mod schema;
77pub mod semantics;
78pub mod stats;
79
80use std::path::PathBuf;
81use std::sync::Arc;
82use std::time::{Duration, Instant};
83
84use rf_cache::{CachedGadget, CachedScan};
85
86use rmcp::handler::server::wrapper::Parameters;
87use rmcp::model::{CallToolResult, ContentBlock};
88use rmcp::service::RequestContext;
89use rmcp::{tool, tool_handler, tool_router, ErrorData as McpError, RoleServer, ServerHandler};
90use schemars::JsonSchema;
91use serde::{Deserialize, Serialize};
92use serde_json::{json, Value};
93use sha2::Digest;
94
95pub use audit::{AuditLog, AuditRecord};
96pub use cache::Cache;
97pub use confine::{AllowRoot, ConfinedFile};
98pub use cursor::Cursor;
99pub use guard::Guard;
100pub use logging::Notifier;
101pub use schema::{
102    ChainResponse, ErrorCode, GadgetRecord, InfoResponse, ScanResponse, ToolErrorBody, Warning,
103};
104pub use semantics::{GadgetFilter, Order, Semantics};
105pub use stats::{ServerStats, Verdict};
106
107pub const DEFAULT_MAX_RESULTS: usize = 1000;
108pub const HARD_MAX_RESULTS: usize = 50000;
109pub const DEFAULT_TIMEOUT_SECS: u64 = 60;
110pub const HARD_MAX_TIMEOUT_SECS: u64 = 300;
111/// Default `--max-depth`. A request asking for more is rejected with a
112/// `usage_error`, never silently clamped: an agent that quietly gets depth
113/// 64 when it asked for 100000 draws wrong conclusions from the result.
114pub const DEFAULT_MAX_DEPTH: usize = 64;
115/// Default `--max-file-bytes` (256 MiB), enforced by fstat on the confined
116/// handle before a single byte is read.
117pub const DEFAULT_MAX_FILE_BYTES: u64 = 256 * 1024 * 1024;
118/// Default `--max-concurrent`: how many scans may run at once.
119pub const DEFAULT_MAX_CONCURRENT: usize = 2;
120/// Default `--max-gadgets`, enforced in the engine (MCP-DESIGN fix #4 E).
121/// Cancellation alone does not bound a scan that is legitimately huge;
122/// this is what bounds RSS.
123pub const DEFAULT_MAX_GADGETS: usize = 5_000_000;
124/// Default `--cache-mem-mb`, in bytes.
125pub const DEFAULT_CACHE_MEM_BYTES: u64 = rf_cache::DEFAULT_MEM_MAX_BYTES;
126/// Default `--cache-ttl-secs`.
127pub const DEFAULT_CACHE_TTL: Duration = rf_cache::DEFAULT_MEM_TTL;
128/// Default `--cursor-ttl-secs`: how long a paged scan stays pinned against
129/// eviction so an outstanding cursor can walk it (MCP-DESIGN fix #8 B).
130pub const DEFAULT_CURSOR_TTL: Duration = cache::DEFAULT_CURSOR_TTL;
131/// Default `--probe-threshold`: consecutive `path_denied` results in one
132/// session before responses are delayed and `probing_suspected` is logged.
133pub const DEFAULT_PROBE_THRESHOLD: u64 = 20;
134/// How long a response is delayed once probing is suspected.
135pub const PROBE_DELAY: Duration = Duration::from_millis(250);
136/// Default cap on `get_binary_info`'s `sections` and `imports` arrays, so
137/// a hostile PE with a million import entries cannot produce a gigabyte of
138/// JSON (MCP-06).
139pub const DEFAULT_MAX_INFO_ITEMS: usize = 4096;
140
141/// Default cap on `get_binary_info`'s `symbols` array: symbols are OPT-IN.
142///
143/// `sections` and `imports` are bounded by the file's own structure — 30 and
144/// 46 on `elf-Linux-x64` — so `DEFAULT_MAX_INFO_ITEMS` never bites there. A
145/// symbol table is not: that same fixture has 2169, and reporting them by
146/// default took `get_binary_info`'s rendered response from 10,410 characters
147/// to 331,338 (2,602 -> 82,834 estimated tokens), which blew the 10,000-token
148/// whole-task budget `tests/mcp_workability.py` gates on by 8x on the FIRST
149/// call of the loop. The symbol table is a query target, not an overview, so
150/// an agent asks for it by name; `symbol_count` still reports the true total
151/// and a `symbols_truncated` warning names the parameter, so a default-shaped
152/// response can never be mistaken for "this ELF has no symbols".
153///
154/// `imports` — the SHN_UNDEF subset a ret2plt chain resolves against, with
155/// its GOT/PLT addresses — is unaffected and still reported by default.
156pub const DEFAULT_MAX_SYMBOLS: usize = 0;
157
158/// PLAN §6.1 flag allowlist for `run_ropgadget_command`.
159const ALLOWED_FLAGS: &[&str] = &[
160    "depth",
161    "norop",
162    "nojop",
163    "nosys",
164    "only",
165    "filter",
166    "re",
167    "range",
168    "section",
169    "base",
170    "offset",
171    "badbytes",
172    "align",
173    "multibr",
174    "json",
175    "arch",
176    "all",
177    "callPreceded",
178];
179/// Allowlisted flags that take a value (the rest are boolean switches).
180const VALUE_FLAGS: &[&str] = &[
181    "depth", "only", "filter", "re", "range", "section", "base", "offset", "badbytes", "align",
182    "arch",
183];
184
185// ---------------------------------------------------------------------------
186// Configuration & path confinement
187// ---------------------------------------------------------------------------
188
189#[derive(Debug, Clone)]
190pub struct ServerConfig {
191    /// Canonicalized allowed directories. MCP-02: EMPTY by default. The MCP
192    /// host chooses this process's working directory, so seeding the
193    /// allowlist with the cwd granted access to whatever the host happened
194    /// to pick and `--allow-dir` could never narrow it. `--allow-dir` (or
195    /// the explicit `--allow-cwd`) is now the only source.
196    pub allow_dirs: Vec<PathBuf>,
197    /// Optional on-disk cache spill directory.
198    pub cache_dir: Option<PathBuf>,
199    pub timeout: Duration,
200    pub max_results: usize,
201    /// Largest accepted `depth`. Larger values are rejected, not clamped.
202    pub max_depth: usize,
203    /// Largest binary the server will read, enforced by fstat on the
204    /// confined handle.
205    pub max_file_bytes: u64,
206    /// Concurrently running scans.
207    pub max_concurrent: usize,
208    /// Threads in the scan pool (`--scan-threads`). Default
209    /// `num_cpus - 1`, so the server never takes every core.
210    pub scan_threads: usize,
211    /// Engine gadget budget (`--max-gadgets`). `None` = unbounded.
212    pub max_gadgets: Option<usize>,
213    /// In-memory cache budget (`--cache-mem-mb`) and entry lifetime
214    /// (`--cache-ttl-secs`) — MCP-05/ROB-07.
215    pub cache_mem_bytes: u64,
216    pub cache_ttl: Duration,
217    /// How long a scan stays pinned so an outstanding cursor can page it
218    /// (`--cursor-ttl-secs`).
219    pub cursor_ttl: Duration,
220    /// `--workspace-dir`: where a paged scan's NDJSON is materialized as a
221    /// real file. Must lie OUTSIDE every allow root, which `main.rs`
222    /// enforces at startup.
223    pub workspace_dir: Option<PathBuf>,
224    /// JSONL call/denial log (`--audit-log`), and its rotation size.
225    pub audit_log: Option<PathBuf>,
226    pub audit_log_max_mb: u64,
227    /// Consecutive `path_denied` results before the probing signal trips.
228    /// 0 disables it.
229    pub probe_threshold: u64,
230    /// Cap on `get_binary_info`'s `sections`/`imports` arrays.
231    pub max_info_items: usize,
232    /// Restore per-reason path error detail INSIDE allowed roots only.
233    pub verbose_path_errors: bool,
234}
235
236impl Default for ServerConfig {
237    fn default() -> Self {
238        ServerConfig {
239            allow_dirs: Vec::new(),
240            cache_dir: None,
241            timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
242            max_results: DEFAULT_MAX_RESULTS,
243            max_depth: DEFAULT_MAX_DEPTH,
244            max_file_bytes: DEFAULT_MAX_FILE_BYTES,
245            max_concurrent: DEFAULT_MAX_CONCURRENT,
246            scan_threads: guard::default_scan_threads(),
247            max_gadgets: Some(DEFAULT_MAX_GADGETS),
248            cache_mem_bytes: DEFAULT_CACHE_MEM_BYTES,
249            cache_ttl: DEFAULT_CACHE_TTL,
250            cursor_ttl: DEFAULT_CURSOR_TTL,
251            workspace_dir: None,
252            audit_log: None,
253            audit_log_max_mb: audit::DEFAULT_AUDIT_MAX_MB,
254            probe_threshold: DEFAULT_PROBE_THRESHOLD,
255            max_info_items: DEFAULT_MAX_INFO_ITEMS,
256            verbose_path_errors: false,
257        }
258    }
259}
260
261/// Structured tool error, rendered as
262/// `{error: {code, message, retryable, details, suggestion}}`.
263///
264/// CRIT-03: `code` is the CLOSED [`ErrorCode`] set, and every field of the
265/// rendered body is always present. `kind` is a FINER tag that never
266/// reaches the client: it is what the audit log records, so collapsing
267/// `file_too_large` and `busy` into one wire code loses the operator
268/// nothing. The two spellings the audit found — `usage` in one place and
269/// `usage_error` everywhere else — cannot recur, because there is no longer
270/// a place to write a code as a free string.
271#[derive(Debug)]
272pub struct ToolError {
273    pub code: ErrorCode,
274    /// Finer-grained internal reason, for the audit log and for the two
275    /// places the server branches on it. Defaults to `code.as_str()`.
276    pub kind: &'static str,
277    pub message: String,
278    /// Machine-readable specifics (allow roots, breached limits). Never
279    /// carries an OS error string for a path outside the allowlist.
280    pub details: Option<Value>,
281    /// Whether re-sending the same request could succeed.
282    pub retryable: bool,
283    /// An arguments patch that would make the call work.
284    pub suggestion: Option<Value>,
285}
286
287impl ToolError {
288    pub(crate) fn new(code: ErrorCode, message: impl Into<String>) -> Self {
289        ToolError {
290            code,
291            kind: code.as_str(),
292            message: message.into(),
293            details: None,
294            retryable: code.default_retryable(),
295            suggestion: None,
296        }
297    }
298
299    pub(crate) fn with_details(
300        code: ErrorCode,
301        message: impl Into<String>,
302        details: Value,
303    ) -> Self {
304        ToolError {
305            details: Some(details),
306            ..ToolError::new(code, message)
307        }
308    }
309
310    /// Record a finer reason than the wire code carries.
311    #[must_use]
312    pub(crate) fn with_kind(mut self, kind: &'static str) -> Self {
313        self.kind = kind;
314        self
315    }
316
317    #[must_use]
318    pub(crate) fn retryable(mut self, yes: bool) -> Self {
319        self.retryable = yes;
320        self
321    }
322
323    #[must_use]
324    pub(crate) fn with_suggestion(mut self, suggestion: Value) -> Self {
325        self.suggestion = Some(suggestion);
326        self
327    }
328
329    /// The `timeout` a worker did not stop for. Distinguished here rather
330    /// than by a separate wire code, so the closed set stays closed.
331    #[must_use]
332    pub fn is_hard_timeout(&self) -> bool {
333        self.code == ErrorCode::Timeout && self.kind == "timeout_hard"
334    }
335
336    fn to_json(&self) -> Value {
337        json!({"error": {
338            "code": self.code,
339            "message": self.message,
340            "retryable": self.retryable,
341            "details": self.details.clone().unwrap_or_else(|| json!({})),
342            "suggestion": self.suggestion.clone().unwrap_or(Value::Null),
343        }})
344    }
345}
346
347// ---------------------------------------------------------------------------
348// Cache (content-hash → gadget list)
349// ---------------------------------------------------------------------------
350
351// `CachedGadget` and `CachedScan` are `rf_cache`'s, not this crate's —
352// see the `use` at the top of the file. The record, the checked hex
353// decoder, the `validate()` that runs on every deserialize, and the
354// on-disk half of this cache are shared with rf-cli. That sharing is the
355// point of the change: the ROB-04 char-boundary panic existed here *and*
356// at rf-cli/src/lib.rs because there were two copies of the same twenty
357// lines. The serialized shape is unchanged — the fields only rf-cli fills
358// are skipped when empty, so a gadget in a tool response still carries
359// exactly vaddr/bytes/text plus the optional arch/section/quality/class.
360
361fn sha256_hex(bytes: &[u8]) -> String {
362    let mut h = sha2::Sha256::new();
363    h.update(bytes);
364    format!("{:x}", h.finalize())
365}
366
367// [`Cache`] itself is [`cache::Cache`]: both halves bounded, the memory
368// half a byte-weighted LRU that lives in rf-cache so the CLI shares it
369// (MCP-05/ROB-07, CLI-08/PERF-12).
370
371// ---------------------------------------------------------------------------
372// Shared parameter structs
373// ---------------------------------------------------------------------------
374
375#[derive(Debug, Deserialize, Serialize, JsonSchema)]
376pub struct GadgetQuery {
377    /// Absolute path to the binary; must be inside one of the server's
378    /// allow_roots (get_server_config lists them).
379    pub binary_path: String,
380    /// Search depth (default 10).
381    pub depth: Option<usize>,
382    /// Executable section name(s) to scan; comma-separated, `*` globbing
383    /// (e.g. ".text" or ".init*,.plt").
384    pub section: Option<String>,
385    /// Rebase the image base at load time (hex string, e.g. "0x400000";
386    /// "0" for RVA-style addresses).
387    pub base: Option<String>,
388    /// Offset added to gadget addresses after any rebase (hex string).
389    pub offset: Option<String>,
390    /// Keep only gadgets containing these instructions (e.g. "pop|ret").
391    pub only: Option<String>,
392    /// Address range to scan, "0xSTART-0xEND".
393    pub range: Option<String>,
394    /// Reject gadgets whose final address contains these bytes
395    /// (e.g. "0a|0d" or "00-1f").
396    pub badbytes: Option<String>,
397    /// Maximum gadgets returned per page (default 1000, hard max 50000).
398    pub max_results: Option<usize>,
399    /// Result ordering, applied BEFORE paging. "rank" (the default) is
400    /// usability tier, then quality, then fewest instructions, then fewest
401    /// side effects, then address — it is what puts `pop rdi ; ret` at the
402    /// top instead of `adc al, 0x89 ; retf 0xc281`. Also "address",
403    /// "quality" and "text" (the pre-0.3 default). Anything else is
404    /// rejected with the valid set in the error.
405    pub order: Option<String>,
406    /// Deprecated alias for `order`, kept because it used to be the only
407    /// way to ask for anything but traversal order. Ignored when `order`
408    /// is given.
409    pub sort_by: Option<String>,
410    /// `next_cursor` from a previous page of THIS query. Re-send every
411    /// other parameter unchanged; `max_results` and `timeout_secs` may
412    /// change. A cursor from a different query returns `cursor_expired`.
413    pub cursor: Option<String>,
414    /// Keep only gadgets whose primary class is one of these
415    /// (comma-separated): reg-write, stack-pivot, mem-read, mem-write,
416    /// arithmetic, syscall, dispatcher, other.
417    pub class: Option<String>,
418    /// Keep only gadgets carrying at least one of these labels (same
419    /// vocabulary as `class`; a gadget can earn several).
420    pub label: Option<String>,
421    /// Keep only gadgets that write ALL of these registers
422    /// (comma-separated, e.g. "rdi"). Names are matched lowercase and
423    /// without a `$`/`%` sigil.
424    pub writes_reg: Option<String>,
425    /// Keep only gadgets that read ALL of these registers.
426    pub reads_reg: Option<String>,
427    /// Keep only gadgets that write NONE of these registers — "do not
428    /// clobber rsi or rdx".
429    pub preserves_regs: Option<String>,
430    /// Require the `writes_reg` registers to be loaded off the STACK (a
431    /// pop, or a stack-based load), which is what makes them controllable
432    /// from the chain payload. With no `writes_reg`, requires at least one
433    /// stack-loaded register.
434    pub from_stack: Option<bool>,
435    /// Keep only gadgets with this terminator. Comma-separated any-of,
436    /// case-insensitive: the coarse kind "ret"
437    /// (every returning form), "jmp", "call", "syscall", "none", "any"
438    /// (no constraint), or a CLS-09 class -- "bare-ret" (the plain near
439    /// return, which coarse "ret" is a superset of), "ret-imm",
440    /// "jmp-reg", "jmp-mem", "call-reg", "call-mem", "far", "other".
441    pub terminator: Option<String>,
442    /// Keep only gadgets with at most this many side effects.
443    pub max_side_effects: Option<u32>,
444    /// Keep only gadgets with at most this many instructions.
445    pub max_insns: Option<u32>,
446    /// ECO-01: keep only gadgets that SET all of these registers — write
447    /// them with a value the chain PAYLOAD decides. Strictly stronger than
448    /// `writes_reg`: `xor rdi, rdi ; ret` writes rdi and sets nothing.
449    pub set_reg: Option<String>,
450    /// ECO-01: none of these registers may be CLOBBERED — written with a
451    /// value the payload does not decide. Matched against the classifier's
452    /// `clobbers`, NOT `regs_written`: `pop rdi ; ret` survives
453    /// `no_clobber: ["rdi"]` and `mov rdi, rax ; ret` does not. Elements
454    /// may also be comma-separated.
455    pub no_clobber: Option<Vec<String>>,
456    /// ECO-01: keep only gadgets whose net stack movement is KNOWN and at
457    /// most this many bytes (the terminator's own pop included, so
458    /// `pop rdi ; ret` is 16 on x86-64). A gadget whose delta is unknown is
459    /// REJECTED, never assumed to be 0.
460    pub max_stack_delta: Option<i64>,
461    /// ECO-12: the stack-pivot preset — keep only gadgets carrying the
462    /// `stack-pivot` label.
463    pub pivot: Option<bool>,
464    /// ECO-01: ropper-style wildcard matcher over the instruction
465    /// SEQUENCE, e.g. "pop rdi; ret". `?` is one character, `%` is any run
466    /// inside one instruction (so a bare `%` is any single instruction).
467    /// The instructions must appear as a contiguous run, so
468    /// "pop rdi; ret" also matches "xor eax, eax ; pop rdi ; ret".
469    pub search: Option<String>,
470    /// Architecture slice for a fat (Universal) Mach-O, e.g. "x86_64",
471    /// "arm64", "i386". REQUIRED for a multi-slice container: without it
472    /// the scan is refused rather than concatenating slices whose virtual
473    /// address ranges overlap (CORE-03).
474    pub arch: Option<String>,
475    /// Per-request timeout in seconds (default 60, max 300).
476    pub timeout_secs: Option<u64>,
477}
478
479/// Scan architecture of a loaded binary (for on-demand classification).
480fn arch_from_bytes(bytes: &[u8]) -> Option<rf_core::Arch> {
481    use rf_core::{Image, LoadedBinary};
482    match rf_core::Binary::load(bytes).ok()? {
483        LoadedBinary::Elf(b) => Some(Image::arch(&b)),
484        LoadedBinary::Pe(b) => Some(Image::arch(&b)),
485        LoadedBinary::MachO(b) => Some(Image::arch(&b)),
486        // `.first()`, not `[0]`: a fat container with no slices is a
487        // malformed input, not a reason to abort the server.
488        LoadedBinary::Universal(u) => u.slices().first().map(Image::arch),
489        LoadedBinary::Raw(b) => Some(Image::arch(&b)),
490    }
491}
492
493// Ordering used to live here as `sort_by_quality`, which re-derived a
494// missing quality score from the cached bytes on every call. That path is
495// gone: [`semantics::classify_scan`] computes the whole classification once
496// per scan and the pinned-scan store keeps it, so nothing re-classifies
497// inside a response any more. ROB-04's char-boundary panic lived on exactly
498// that path.
499
500#[derive(Debug, Deserialize, Serialize, JsonSchema)]
501pub struct SearchQuery {
502    /// Absolute path to the binary; must be inside one of the server's
503    /// allow_roots (get_server_config lists them).
504    pub binary_path: String,
505    /// Regex matched against gadget text (e.g. "pop r.*; ret"); if the
506    /// pattern is not a valid regex it is matched as a literal substring.
507    pub pattern: String,
508    /// Search depth (default 10).
509    pub depth: Option<usize>,
510    /// Executable section name(s); comma-separated, `*` globbing.
511    pub section: Option<String>,
512    /// Rebase the image base at load time (hex string).
513    pub base: Option<String>,
514    /// Offset added to gadget addresses (hex string).
515    pub offset: Option<String>,
516    /// Address range to scan, "0xSTART-0xEND".
517    pub range: Option<String>,
518    /// Reject gadgets whose final address contains these bytes.
519    pub badbytes: Option<String>,
520    /// Maximum gadgets returned per page (default 1000, hard max 50000).
521    pub max_results: Option<usize>,
522    /// Result ordering; see find_gadgets. Default "rank".
523    pub order: Option<String>,
524    /// `next_cursor` from a previous page of THIS query.
525    pub cursor: Option<String>,
526    /// Keep only gadgets whose primary class is one of these.
527    pub class: Option<String>,
528    /// Keep only gadgets carrying at least one of these labels.
529    pub label: Option<String>,
530    /// Keep only gadgets that write ALL of these registers.
531    pub writes_reg: Option<String>,
532    /// Keep only gadgets that read ALL of these registers.
533    pub reads_reg: Option<String>,
534    /// Keep only gadgets that write NONE of these registers.
535    pub preserves_regs: Option<String>,
536    /// Require the `writes_reg` registers to come off the stack.
537    pub from_stack: Option<bool>,
538    /// Terminator kind: "ret", "jmp", "call", "syscall", "none", "any",
539    /// or a CLS-09 class ("bare-ret", "ret-imm", "jmp-reg", "jmp-mem",
540    /// "call-reg", "call-mem", "far", "other").
541    pub terminator: Option<String>,
542    pub max_side_effects: Option<u32>,
543    pub max_insns: Option<u32>,
544    /// ECO-01: keep only gadgets that SET all of these registers — write
545    /// them with a value the chain PAYLOAD decides. Strictly stronger than
546    /// `writes_reg`: `xor rdi, rdi ; ret` writes rdi and sets nothing.
547    pub set_reg: Option<String>,
548    /// ECO-01: none of these registers may be CLOBBERED — written with a
549    /// value the payload does not decide. Matched against the classifier's
550    /// `clobbers`, NOT `regs_written`: `pop rdi ; ret` survives
551    /// `no_clobber: ["rdi"]` and `mov rdi, rax ; ret` does not. Elements
552    /// may also be comma-separated.
553    pub no_clobber: Option<Vec<String>>,
554    /// ECO-01: keep only gadgets whose net stack movement is KNOWN and at
555    /// most this many bytes (the terminator's own pop included, so
556    /// `pop rdi ; ret` is 16 on x86-64). A gadget whose delta is unknown is
557    /// REJECTED, never assumed to be 0.
558    pub max_stack_delta: Option<i64>,
559    /// ECO-12: the stack-pivot preset — keep only gadgets carrying the
560    /// `stack-pivot` label.
561    pub pivot: Option<bool>,
562    /// ECO-01: ropper-style wildcard matcher over the instruction
563    /// SEQUENCE, e.g. "pop rdi; ret". `?` is one character, `%` is any run
564    /// inside one instruction (so a bare `%` is any single instruction).
565    /// The instructions must appear as a contiguous run, so
566    /// "pop rdi; ret" also matches "xor eax, eax ; pop rdi ; ret".
567    pub search: Option<String>,
568    /// Architecture slice for a fat (Universal) Mach-O, e.g. "x86_64",
569    /// "arm64", "i386". REQUIRED for a multi-slice container: without it
570    /// the scan is refused rather than concatenating slices whose virtual
571    /// address ranges overlap (CORE-03).
572    pub arch: Option<String>,
573    /// Per-request timeout in seconds (default 60, max 300).
574    pub timeout_secs: Option<u64>,
575}
576
577/// ECO-01 — the constraint search, as one call.
578///
579/// This is MCP-DESIGN's usefulness bar item 15: "set rdi from the stack,
580/// preserve rsi and rdx, at most one side effect, clean ret" expressed
581/// once and answered with a small correct set, instead of a thousand
582/// alphabetically-ordered records beginning with `adc al, 0x89 ; retf
583/// 0xc281`.
584///
585/// Every filter here is also available on `find_gadgets`; this tool exists
586/// because a *named* tool whose whole parameter list is the question is
587/// what an agent finds, and because it scans ROP+JOP+SYS together so
588/// `terminator` decides the family instead of the tool name doing it.
589#[derive(Debug, Deserialize, Serialize, JsonSchema)]
590pub struct EffectQuery {
591    /// Absolute path to the binary; must be inside one of the server's
592    /// allow_roots (get_server_config lists them).
593    pub binary_path: String,
594    /// Search depth (default 10).
595    pub depth: Option<usize>,
596
597    // ---- the constraint vocabulary (shared with the CLI's long flags) ----
598    /// The gadget must SET this register — write it with a value the chain
599    /// PAYLOAD decides. Several may be given, comma-separated, and all are
600    /// required. Strictly stronger than `writes_reg`: `xor rdi, rdi ; ret`
601    /// writes rdi and sets nothing.
602    pub set_reg: Option<String>,
603    /// The `set_reg` write must ORIGINATE on the stack — a pop, or a load
604    /// through the stack pointer — rather than in an arbitrary
605    /// computation. With no `set_reg` it falls back to `writes_reg`, and
606    /// with neither it means "at least one register comes off the stack".
607    pub from_stack: Option<bool>,
608    /// None of these registers may be CLOBBERED. Matched against the
609    /// classifier's `clobbers`, NOT `regs_written`, which is the
610    /// difference between "this gadget destroys rdi" and "this gadget
611    /// loads rdi from your payload". Elements may be comma-separated.
612    pub no_clobber: Option<Vec<String>>,
613    /// The gadget must read ALL of these registers.
614    pub reads_reg: Option<String>,
615    /// Net stack movement must be KNOWN and at most this many bytes, the
616    /// terminator's own pop included (`pop rdi ; ret` is 16 on x86-64). An
617    /// unknown delta is REJECTED, never read as 0 — `xchg rsp, rax ; ret`
618    /// must not slip into a layout budget.
619    pub max_stack_delta: Option<i64>,
620    /// At most this many side effects (instructions that earn a label).
621    pub max_side_effects: Option<u32>,
622    /// At most this many instructions.
623    pub max_insns: Option<u32>,
624    /// Terminator: the coarse kind "ret" (every returning form), "jmp",
625    /// "call", "syscall", "none", "any"; or the CLS-09 class "ret-imm",
626    /// "jmp-reg", "jmp-mem", "call-reg", "call-mem", "far", "other".
627    pub terminator: Option<String>,
628    /// Ropper-style wildcard matcher over the instruction SEQUENCE, e.g.
629    /// "pop rdi; ret". `?` is one character, `%` is any run inside one
630    /// instruction (a bare `%` is any single instruction). The pattern must
631    /// appear as a CONTIGUOUS run, so it also matches
632    /// "xor eax, eax ; pop rdi ; ret".
633    pub search: Option<String>,
634    /// ECO-12: the stack-pivot preset — only gadgets carrying the
635    /// `stack-pivot` label. Combine with `max_stack_delta` to rank pivots
636    /// by reach.
637    pub pivot: Option<bool>,
638    /// Primary class: reg-write, stack-pivot, mem-read, mem-write,
639    /// arithmetic, syscall, dispatcher, other (comma-separated).
640    pub class: Option<String>,
641    /// At least one of these labels (same vocabulary as `class`).
642    pub label: Option<String>,
643    /// The gadget must WRITE all of these registers — the v0.3 spelling,
644    /// satisfied by any write. `set_reg` is the one you usually want.
645    pub writes_reg: Option<String>,
646    /// The gadget must write NONE of these registers, matched against
647    /// `regs_written`. Coarser than `no_clobber` and kept because every
648    /// other gadget tool has it.
649    pub preserves_regs: Option<String>,
650
651    // ---- scan shaping, identical to find_gadgets ----
652    /// Executable section name(s); comma-separated, `*` globbing.
653    pub section: Option<String>,
654    /// Rebase the image base at load time (hex string).
655    pub base: Option<String>,
656    /// Offset added to gadget addresses after any rebase (hex string).
657    pub offset: Option<String>,
658    /// Address range to scan, "0xSTART-0xEND".
659    pub range: Option<String>,
660    /// Reject gadgets whose final address contains these bytes.
661    pub badbytes: Option<String>,
662    /// Maximum gadgets returned per page (default 1000, hard max 50000).
663    pub max_results: Option<usize>,
664    /// Result ordering; see find_gadgets. Default "rank".
665    pub order: Option<String>,
666    /// `next_cursor` from a previous page of THIS query.
667    pub cursor: Option<String>,
668    /// Architecture slice for a fat (Universal) Mach-O. REQUIRED for a
669    /// multi-slice container.
670    pub arch: Option<String>,
671    /// Per-request timeout in seconds (default 60, max 300).
672    pub timeout_secs: Option<u64>,
673}
674
675#[derive(Debug, Deserialize, Serialize, JsonSchema)]
676pub struct RawCommandQuery {
677    /// Absolute path to the binary; must be inside one of the server's
678    /// allow_roots (get_server_config lists them).
679    pub binary_path: String,
680    /// ROPgadget-style flags, e.g. ["--depth", "6", "--only", "pop|ret"].
681    /// Restricted to the allowlist: --depth --norop --nojop --nosys --only
682    /// --filter --re --range --section --base --offset --badbytes --align
683    /// --multibr --json. Anything else is rejected.
684    pub args: Vec<String>,
685    /// Maximum gadgets returned per page (default 1000, hard max 50000).
686    pub max_results: Option<usize>,
687    /// Result ordering; see find_gadgets. Default "rank".
688    pub order: Option<String>,
689    /// `next_cursor` from a previous page of THIS query.
690    pub cursor: Option<String>,
691    /// Keep only gadgets whose primary class is one of these.
692    pub class: Option<String>,
693    /// Keep only gadgets carrying at least one of these labels.
694    pub label: Option<String>,
695    /// Keep only gadgets that write ALL of these registers.
696    pub writes_reg: Option<String>,
697    /// Keep only gadgets that read ALL of these registers.
698    pub reads_reg: Option<String>,
699    /// Keep only gadgets that write NONE of these registers.
700    pub preserves_regs: Option<String>,
701    /// Require the `writes_reg` registers to come off the stack.
702    pub from_stack: Option<bool>,
703    /// Terminator kind: "ret", "jmp", "call", "syscall", "none", "any",
704    /// or a CLS-09 class ("bare-ret", "ret-imm", "jmp-reg", ...).
705    pub terminator: Option<String>,
706    pub max_side_effects: Option<u32>,
707    pub max_insns: Option<u32>,
708    /// ECO-01: keep only gadgets that SET all of these registers — write
709    /// them with a value the chain PAYLOAD decides. Strictly stronger than
710    /// `writes_reg`: `xor rdi, rdi ; ret` writes rdi and sets nothing.
711    pub set_reg: Option<String>,
712    /// ECO-01: none of these registers may be CLOBBERED — written with a
713    /// value the payload does not decide. Matched against the classifier's
714    /// `clobbers`, NOT `regs_written`: `pop rdi ; ret` survives
715    /// `no_clobber: ["rdi"]` and `mov rdi, rax ; ret` does not. Elements
716    /// may also be comma-separated.
717    pub no_clobber: Option<Vec<String>>,
718    /// ECO-01: keep only gadgets whose net stack movement is KNOWN and at
719    /// most this many bytes (the terminator's own pop included, so
720    /// `pop rdi ; ret` is 16 on x86-64). A gadget whose delta is unknown is
721    /// REJECTED, never assumed to be 0.
722    pub max_stack_delta: Option<i64>,
723    /// ECO-12: the stack-pivot preset — keep only gadgets carrying the
724    /// `stack-pivot` label.
725    pub pivot: Option<bool>,
726    /// ECO-01: ropper-style wildcard matcher over the instruction
727    /// SEQUENCE, e.g. "pop rdi; ret". `?` is one character, `%` is any run
728    /// inside one instruction (so a bare `%` is any single instruction).
729    /// The instructions must appear as a contiguous run, so
730    /// "pop rdi; ret" also matches "xor eax, eax ; pop rdi ; ret".
731    pub search: Option<String>,
732    /// Per-request timeout in seconds (default 60, max 300).
733    pub timeout_secs: Option<u64>,
734}
735
736/// `get_gadgets` — resolve stable ids back to full records.
737///
738/// This is what lets an agent say "build a chain from g_ab12 and g_cd34"
739/// rather than re-sending gadget text and hoping the server parses it the
740/// same way.
741#[derive(Debug, Deserialize, Serialize, JsonSchema)]
742pub struct IdsQuery {
743    /// Absolute path to the binary; must be inside one of the server's
744    /// allow_roots (get_server_config lists them).
745    pub binary_path: String,
746    /// Stable gadget ids, as returned in `gadgets[].id` (e.g.
747    /// "g_ab12cd34ef56gh78"). Ids that do not resolve are reported in
748    /// `warnings` rather than failing the call.
749    pub ids: Vec<String>,
750    /// Search depth the ids were found at (default 10). An id from a
751    /// depth-10 scan will not resolve in a depth-4 one.
752    pub depth: Option<usize>,
753    /// Rebase the image base at load time (hex string). Must match the
754    /// scan the ids came from: an id is independent of every scan
755    /// parameter EXCEPT `base`, which relabels the whole address space.
756    pub base: Option<String>,
757    /// Offset added to gadget addresses after any rebase (hex string).
758    pub offset: Option<String>,
759    /// Executable section name(s); comma-separated, `*` globbing.
760    pub section: Option<String>,
761    /// Architecture slice for a fat (Universal) Mach-O.
762    pub arch: Option<String>,
763    /// Per-request timeout in seconds (default 60, max 300).
764    pub timeout_secs: Option<u64>,
765}
766
767/// CLI-05 / ECO-02 — `find_string`.
768#[derive(Debug, Deserialize, Serialize, JsonSchema)]
769pub struct StringQuery {
770    /// Absolute path to the binary; must be inside one of the server's
771    /// allow_roots (get_server_config lists them).
772    pub binary_path: String,
773    /// The pattern, as a BYTE regex (ROPgadget's `--string` semantics), so
774    /// "/bin/sh" is a literal and "m..n" is four bytes. Matched only
775    /// against MAPPED sections.
776    pub string: String,
777    /// ROPgadget's `--memstr` instead of `--string`: locate each CHARACTER
778    /// of `string` separately and report only the FIRST place each one
779    /// occurs, searching executable sections before data ones. This is how
780    /// you assemble a string you cannot find contiguously. Default false.
781    pub memstr: Option<bool>,
782    /// Rebase the image base before reporting addresses (hex string, e.g.
783    /// "0x400000"; "0" for RVAs).
784    pub base: Option<String>,
785    /// Offset added to reported addresses after any rebase (hex string).
786    pub offset: Option<String>,
787    /// Restrict the search to this address range, "0xSTART-0xEND". It can
788    /// only ever NARROW the mapped windows, never widen them.
789    pub range: Option<String>,
790    /// Maximum hits returned per page (default 1000, hard max 50000).
791    pub max_results: Option<usize>,
792    /// `next_cursor` from a previous page of THIS query.
793    pub cursor: Option<String>,
794    /// Architecture slice for a fat (Universal) Mach-O. REQUIRED for a
795    /// multi-slice container, whose slices' addresses overlap.
796    pub arch: Option<String>,
797    /// Per-request timeout in seconds (default 60, max 300).
798    pub timeout_secs: Option<u64>,
799}
800
801/// CLI-05 / ECO-02 — `find_bytes`.
802#[derive(Debug, Deserialize, Serialize, JsonSchema)]
803pub struct BytesQuery {
804    /// Absolute path to the binary; must be inside one of the server's
805    /// allow_roots (get_server_config lists them).
806    pub binary_path: String,
807    /// The byte sequence as hex, e.g. "c9c3" or "c9 c3". `??` matches any
808    /// one byte, so "ff??e0" finds `jmp rax` through `jmp r15`. A nibble
809    /// wildcard is refused rather than silently widened.
810    pub opcode: String,
811    /// Rebase the image base before reporting addresses (hex string).
812    pub base: Option<String>,
813    /// Offset added to reported addresses after any rebase (hex string).
814    pub offset: Option<String>,
815    /// Restrict the search to this address range, "0xSTART-0xEND".
816    pub range: Option<String>,
817    /// Maximum hits returned per page (default 1000, hard max 50000).
818    pub max_results: Option<usize>,
819    /// `next_cursor` from a previous page of THIS query.
820    pub cursor: Option<String>,
821    /// Architecture slice for a fat (Universal) Mach-O. REQUIRED for a
822    /// multi-slice container.
823    pub arch: Option<String>,
824    /// Per-request timeout in seconds (default 60, max 300).
825    pub timeout_secs: Option<u64>,
826}
827
828/// ECO-06 — `get_mitigations`.
829#[derive(Debug, Deserialize, Serialize, JsonSchema)]
830pub struct MitigationsQuery {
831    /// Absolute path to the binary; must be inside one of the server's
832    /// allow_roots (get_server_config lists them).
833    pub binary_path: String,
834    /// Per-request timeout in seconds (default 60, max 300).
835    pub timeout_secs: Option<u64>,
836}
837
838#[derive(Debug, Deserialize, Serialize, JsonSchema)]
839pub struct InfoQuery {
840    /// Absolute path to the binary; must be inside one of the server's
841    /// allow_roots (get_server_config lists them).
842    pub binary_path: String,
843    /// Rebase the image base before reporting addresses (hex string).
844    pub base: Option<String>,
845    /// Maximum sections reported (default 4096). A larger array is
846    /// truncated and `warnings` carries `sections_truncated`.
847    pub max_sections: Option<usize>,
848    /// Maximum imports reported (default 4096). A larger array is
849    /// truncated and `warnings` carries `imports_truncated`.
850    pub max_imports: Option<usize>,
851    /// Maximum ELF symbols reported. Symbols are OPT-IN: the default is 0
852    /// because a symbol table is unbounded by the file's structure (2169 on
853    /// elf-Linux-x64) where `sections` and `imports` are not, and returning
854    /// it by default cost 80k tokens on the first call of a task. Pass a
855    /// number to get them, up to max_info_items (4096). `symbol_count`
856    /// always reports the true total and `warnings` carries
857    /// `symbols_truncated`, so a short list is never indistinguishable from
858    /// a binary with few symbols. `imports` is NOT affected by this.
859    pub max_symbols: Option<usize>,
860    /// Per-request timeout in seconds (default 60, max 300).
861    pub timeout_secs: Option<u64>,
862}
863
864#[derive(Debug, Deserialize, Serialize, JsonSchema)]
865pub struct ChainQuery {
866    /// Absolute path to the binary; must be inside one of the server's
867    /// allow_roots (get_server_config lists them).
868    pub binary_path: String,
869    /// Chain target: "linux-execve" (ELF x86/x64) or
870    /// "windows-virtualprotect" (PE x86/x64).
871    pub target: String,
872    /// Search depth (default 10).
873    pub depth: Option<usize>,
874    /// Rebase the image base at load time (hex string, e.g. "0x400000").
875    pub base: Option<String>,
876    /// Offset added to gadget and data-section addresses (hex string).
877    pub offset: Option<String>,
878    /// Reject chain words whose packed value contains these bytes
879    /// (e.g. "0a|0d" or "00-1f").
880    pub badbytes: Option<String>,
881    /// CFG/CET-aware scan: keep only endbr64/endbr32-entering gadgets.
882    pub cfg_aware: Option<bool>,
883    /// windows-virtualprotect: runtime address of the API (hex). Primary
884    /// resolution path; without it the PE must import the API (IAT).
885    pub api_addr: Option<String>,
886    /// windows-virtualprotect: which API to call — "VirtualProtect"
887    /// (default) or "VirtualAlloc". Picks the IAT import to resolve and
888    /// the argument recipe; the two do not take the same four arguments.
889    pub api_name: Option<String>,
890    /// windows-virtualprotect: runtime shellcode address (hex; default:
891    /// the binary's writable .data section).
892    pub shellcode_addr: Option<String>,
893    /// windows-virtualprotect: dwSize argument (hex; default 0x1000).
894    pub shellcode_size: Option<String>,
895    /// windows-virtualprotect (x64): what the alignment invariant may
896    /// assume about the chain's first word — "return_address" (default)
897    /// or "aligned". Echoed back in `assumptions`.
898    pub chain_base: Option<String>,
899    /// flNewProtect / flProtect (hex; default 0x40 =
900    /// PAGE_EXECUTE_READWRITE) for windows-virtualprotect, or
901    /// linux-mprotect's `prot` (default 7 = PROT_READ|WRITE|EXEC).
902    pub prot: Option<String>,
903    /// linux-syscall: the syscall number to invoke, and the syscall the
904    /// linux-srop frame carries. Decimal, or hex with an explicit "0x".
905    pub syscall: Option<String>,
906    /// linux-syscall / linux-srop: argument registers, e.g.
907    /// "rdi=0x404000,rsi=0x1000,rdx=7" (values are hex).
908    pub syscall_args: Option<String>,
909    /// CHWIN-08: pivot the stack pointer here before the chain body runs
910    /// (hex). The chain is then in two pieces — `assumptions.pivot_words`
911    /// leading words go at the overflow point, the rest at this address.
912    pub chain_pivot: Option<String>,
913    /// CHWIN-08: shellcode bytes (hex, e.g. "9090cc") to WRITE into the
914    /// region at shellcode_addr with write-what-where gadgets instead of
915    /// assuming they are already there.
916    pub stage: Option<String>,
917    /// Architecture slice for a fat (Universal) Mach-O, e.g. "x86_64",
918    /// "arm64", "i386". REQUIRED for a multi-slice container: without it
919    /// the scan is refused rather than concatenating slices whose virtual
920    /// address ranges overlap (CORE-03).
921    pub arch: Option<String>,
922    /// Per-request timeout in seconds (default 60, max 300).
923    pub timeout_secs: Option<u64>,
924}
925
926// ---------------------------------------------------------------------------
927// Request shaping helpers (unit-tested)
928// ---------------------------------------------------------------------------
929
930fn clamp_max_results(req: Option<usize>, default: usize) -> usize {
931    req.unwrap_or(default).clamp(1, HARD_MAX_RESULTS)
932}
933
934fn clamp_timeout(req: Option<u64>, default: Duration) -> Duration {
935    req.map(|s| Duration::from_secs(s.clamp(1, HARD_MAX_TIMEOUT_SECS)))
936        .unwrap_or(default)
937}
938
939/// Parsed + validated `run_ropgadget_command` arguments.
940#[derive(Debug)]
941pub struct ParsedArgs {
942    pub request: rf_api::ScanRequest,
943    /// --re post-filter (regex over gadget text). This one really is a
944    /// post-filter in ROPgadget too (options.py:22-33).
945    pub re: Option<String>,
946}
947
948/// ANCH-02 - parse `--align` the way ROPgadget's argparse does.
949///
950/// ROPgadget declares `--align` as `type=int`, i.e. DECIMAL. rf-mcp used to
951/// hand the value to `rf_api::parse_hex`, which strips an optional `0x` and
952/// then always parses base 16, so `--align 16` meant 0x16 = 22 - a
953/// different, and for a power-of-two request nonsensical, alignment.
954/// Decimal first; hexadecimal only when the caller writes an explicit `0x`,
955/// which no ROPgadget user would but an MCP client echoing an address
956/// literal might.
957pub fn parse_align(v: &str) -> Result<usize, String> {
958    let t = v.trim();
959    if let Some(hex) = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) {
960        if hex.is_empty() {
961            return Err(format!("invalid --align {v:?}: no digits after 0x"));
962        }
963        return usize::from_str_radix(hex, 16).map_err(|e| format!("invalid --align {v:?}: {e}"));
964    }
965    t.parse::<usize>()
966        .map_err(|e| format!("invalid --align {v:?}: {e}"))
967}
968
969/// Validate `args` against the PLAN §6.1 allowlist and map them onto a
970/// [`rf_api::ScanRequest`]. Anything outside the allowlist is rejected.
971pub fn parse_ropgadget_args(args: &[String]) -> Result<ParsedArgs, ToolError> {
972    let mut req = rf_api::ScanRequest::default();
973    let mut re = None;
974    let mut i = 0;
975    while i < args.len() {
976        let Some(arg) = args.get(i) else { break };
977        let Some(stripped) = arg.strip_prefix("--") else {
978            return Err(usage_flag(format!(
979                "unexpected positional argument {arg:?}; only --flags are accepted"
980            )));
981        };
982        let (name, inline_val) = match stripped.split_once('=') {
983            Some((n, v)) => (n, Some(v.to_string())),
984            None => (stripped, None),
985        };
986        if !ALLOWED_FLAGS.contains(&name) {
987            return Err(usage_flag(format!(
988                "flag --{name} is not allowed; allowlist: {}",
989                ALLOWED_FLAGS
990                    .iter()
991                    .map(|f| format!("--{f}"))
992                    .collect::<Vec<_>>()
993                    .join(" ")
994            )));
995        }
996        let takes_value = VALUE_FLAGS.contains(&name);
997        let value = if takes_value {
998            match inline_val {
999                Some(v) => Some(v),
1000                None => {
1001                    i += 1;
1002                    let Some(v) = args.get(i) else {
1003                        return Err(usage_flag(format!("flag --{name} requires a value")));
1004                    };
1005                    if v.starts_with("--") {
1006                        return Err(usage_flag(format!(
1007                            "flag --{name} requires a value (got {v:?})"
1008                        )));
1009                    }
1010                    Some(v.clone())
1011                }
1012            }
1013        } else {
1014            if inline_val.is_some() {
1015                return Err(usage_flag(format!("flag --{name} does not take a value")));
1016            }
1017            None
1018        };
1019        match name {
1020            "depth" => {
1021                req.depth = value.unwrap().parse().map_err(|_| {
1022                    ToolError::new(ErrorCode::UsageError, "invalid --depth value".to_string())
1023                })?;
1024            }
1025            "norop" => req.rop = false,
1026            "nojop" => req.jop = false,
1027            "nosys" => req.sys = false,
1028            "multibr" => req.multibr = true,
1029            "json" => {} // MCP responses are always JSON
1030            "only" => req.only = value,
1031            "filter" => req.filter = value,
1032            "range" => req.range = value,
1033            "section" => req.section.extend(split_sections(value.as_deref())),
1034            "base" => req.base = value,
1035            "offset" => req.offset = value,
1036            "badbytes" => req.badbytes = value,
1037            "re" => re = value,
1038            "arch" => req.arch = value,
1039            "all" => req.all = true,
1040            "callPreceded" => req.call_preceded = true,
1041            "align" => {
1042                // ANCH-02: a real engine option, not an address post-filter.
1043                let v = value.unwrap();
1044                req.align =
1045                    Some(parse_align(&v).map_err(|e| ToolError::new(ErrorCode::UsageError, e))?);
1046            }
1047            _ => unreachable!("allowlist checked above"),
1048        }
1049        i += 1;
1050    }
1051    Ok(ParsedArgs { request: req, re })
1052}
1053
1054/// Collect the semantic filter parameters out of a query.
1055///
1056/// `GadgetQuery`, `SearchQuery`, `RawCommandQuery` and `EffectQuery` carry
1057/// the same fields under the same names — the nine CLS-08 ones plus v0.4's
1058/// `set_reg` / `no_clobber` / `max_stack_delta` / `pivot` / `search`
1059/// (ECO-01, ECO-12) — so one spelling covers all four without a trait whose
1060/// only job is to re-export fourteen getters. Keeping them uniform is what
1061/// makes `find_gadgets_by_effect` a preset over the same predicate rather
1062/// than a second, divergent filter.
1063macro_rules! raw_filter {
1064    ($q:expr) => {
1065        semantics::RawFilter {
1066            class: $q.class.as_deref(),
1067            label: $q.label.as_deref(),
1068            writes_reg: $q.writes_reg.as_deref(),
1069            reads_reg: $q.reads_reg.as_deref(),
1070            preserves_regs: $q.preserves_regs.as_deref(),
1071            from_stack: $q.from_stack,
1072            terminator: $q.terminator.as_deref(),
1073            max_side_effects: $q.max_side_effects,
1074            max_insns: $q.max_insns,
1075            set_reg: $q.set_reg.as_deref(),
1076            no_clobber: $q.no_clobber.as_deref().unwrap_or(&[]),
1077            max_stack_delta: $q.max_stack_delta,
1078            pivot: $q.pivot,
1079            search: $q.search.as_deref(),
1080        }
1081    };
1082}
1083
1084fn split_sections(section: Option<&str>) -> Vec<String> {
1085    section
1086        .map(|s| {
1087            s.split(',')
1088                .map(|x| x.trim().to_string())
1089                .filter(|x| !x.is_empty())
1090                .collect()
1091        })
1092        .unwrap_or_default()
1093}
1094
1095fn query_to_request(q: &GadgetQuery, rop: bool, jop: bool, sys: bool) -> rf_api::ScanRequest {
1096    rf_api::ScanRequest {
1097        depth: q.depth.unwrap_or(10),
1098        rop,
1099        jop,
1100        sys,
1101        multibr: false,
1102        only: q.only.clone(),
1103        filter: None,
1104        range: q.range.clone(),
1105        badbytes: q.badbytes.clone(),
1106        offset: q.offset.clone(),
1107        base: q.base.clone(),
1108        section: split_sections(q.section.as_deref()),
1109        thumb: false,
1110        cfg_aware: false,
1111        align: None,
1112        call_preceded: false,
1113        all: false,
1114        noinstr: false,
1115        arch: q.arch.clone(),
1116        max_gadgets: None,
1117        max_memory: None,
1118        // The MCP server never runs the bug-for-bug ROPgadget fallback: an
1119        // agent cannot inspect the output to notice that most of it is
1120        // fabricated, so a fat Mach-O without `arch` is always refused.
1121        compat: false,
1122    }
1123}
1124
1125// ---------------------------------------------------------------------------
1126// The server
1127// ---------------------------------------------------------------------------
1128
1129/// Everything [`RopFinderMcp::run_find`] needs, so the two search tools
1130/// differ by a `mode` and a pattern rather than by twelve arguments.
1131struct FindRequest {
1132    binary_path: String,
1133    mode: find::Mode,
1134    /// The pattern as the caller wrote it, echoed back in `query`.
1135    query: String,
1136    base: Option<String>,
1137    offset: Option<String>,
1138    range: Option<String>,
1139    arch: Option<String>,
1140    max_results: Option<usize>,
1141    cursor: Option<String>,
1142    params_hash: String,
1143    timeout_secs: Option<u64>,
1144}
1145
1146/// Address padding width for a search hit, in bytes.
1147///
1148/// ROPgadget's search modes pad to 8 hex digits on `CS_MODE_32` and 16
1149/// otherwise (core.py:113), which is the pointer size everywhere except a
1150/// RAW arm/thumb blob, whose capstone mode is `CS_MODE_ARM`/`CS_MODE_THUMB`
1151/// rather than `CS_MODE_32` — so those print 16 digits despite 4-byte
1152/// pointers (raw.py:54-67). Reproduced so a hit's address column matches
1153/// the CLI's and the oracle's.
1154fn search_addr_size(target: &rf_api::Target, arch: rf_core::Arch) -> usize {
1155    if matches!(target, rf_api::Target::Raw(_))
1156        && matches!(arch, rf_core::Arch::Arm | rf_core::Arch::ArmThumb)
1157    {
1158        return 8;
1159    }
1160    arch.addr_size()
1161}
1162
1163/// Post-scan options applied over the cached gadget set.
1164struct PostOpts {
1165    /// Regex/substring filter over gadget text (`--re`).
1166    ///
1167    /// `--align` used to live here as an address post-filter. It does not
1168    /// any more (ANCH-02): dropping unaligned addresses out of an align=1
1169    /// scan is not what ROPgadget's `--align` does - the oracle also
1170    /// multiplies the backward depth stride by N, so post-filtering a
1171    /// depth-10 align-1 run can never expose a gadget reaching more than 9
1172    /// bytes back. `--align` is now `ScanRequest::align`, which reaches
1173    /// `rf_scan::ScanOptions::align` and steps the scan itself.
1174    re: Option<String>,
1175    /// Ordering applied before paging. Default [`Order::Rank`].
1176    order: Order,
1177    /// The semantic predicate (CLS-08).
1178    filter: GadgetFilter,
1179    /// `cursor` as the client sent it, still to be validated.
1180    cursor: Option<String>,
1181    /// Fingerprint of the parameters that decide the result set, so a
1182    /// cursor from another query is refused rather than spliced in.
1183    params_hash: String,
1184    /// Response page size (`max_results`), clamped to the server cap.
1185    max_results: Option<usize>,
1186    /// Per-request timeout, clamped to the server cap.
1187    timeout_secs: Option<u64>,
1188    /// `get_gadgets` only: resolve exactly these stable ids, in this order.
1189    ids: Option<Vec<String>>,
1190}
1191
1192impl Default for PostOpts {
1193    fn default() -> Self {
1194        PostOpts {
1195            re: None,
1196            order: Order::Rank,
1197            filter: GadgetFilter::default(),
1198            cursor: None,
1199            params_hash: String::new(),
1200            max_results: None,
1201            timeout_secs: None,
1202            ids: None,
1203        }
1204    }
1205}
1206
1207#[derive(Clone)]
1208pub struct RopFinderMcp {
1209    config: Arc<ServerConfig>,
1210    cache: Arc<Cache>,
1211    /// Allow roots with their directory handles pinned for the lifetime of
1212    /// the process (MCP-01).
1213    roots: Arc<Vec<AllowRoot>>,
1214    /// MCP-03/PERF-06: the concurrency bound, the cancellation bridge and
1215    /// the scan thread pool. Every tool goes through it.
1216    guard: Arc<Guard>,
1217    stats: Arc<ServerStats>,
1218    /// MCP-09: the JSONL call/denial log, when `--audit-log` was given.
1219    audit: Option<Arc<AuditLog>>,
1220    /// MCP-09: warn/error forwarded as `notifications/message`, because
1221    /// MCP hosts discard the server's stderr.
1222    notifier: Arc<Notifier>,
1223    /// One uuid per process, stamped on every audit line.
1224    session: Arc<str>,
1225}
1226
1227impl RopFinderMcp {
1228    /// Build the server, opening and pinning every `config.allow_dirs`
1229    /// entry. Fails if a root cannot be opened, if the scan pool cannot be
1230    /// built, or if `--audit-log` cannot be written — an audit log the
1231    /// operator asked for and did not get is worse than none.
1232    pub fn new(config: ServerConfig) -> std::io::Result<Self> {
1233        let mut roots = Vec::with_capacity(config.allow_dirs.len());
1234        for d in &config.allow_dirs {
1235            let root = AllowRoot::open(d)?;
1236            if roots.iter().any(|r: &AllowRoot| r.id() == root.id()) {
1237                continue;
1238            }
1239            roots.push(root);
1240        }
1241        let session: Arc<str> = Arc::from(uuid::Uuid::new_v4().to_string().as_str());
1242        let audit = match &config.audit_log {
1243            None => None,
1244            Some(p) => Some(Arc::new(AuditLog::open(
1245                p,
1246                config.audit_log_max_mb,
1247                session.to_string(),
1248            )?)),
1249        };
1250        let cache = Cache::new(
1251            config.cache_dir.clone(),
1252            rf_cache::MemLimits {
1253                max_bytes: config.cache_mem_bytes,
1254                ttl: config.cache_ttl,
1255            },
1256            config.cursor_ttl,
1257        );
1258        let stats = Arc::new(ServerStats::default());
1259        let guard = Guard::new(config.max_concurrent, config.scan_threads, stats.clone())
1260            .map_err(std::io::Error::other)?;
1261        Ok(RopFinderMcp {
1262            config: Arc::new(config),
1263            cache: Arc::new(cache),
1264            roots: Arc::new(roots),
1265            guard: Arc::new(guard),
1266            stats,
1267            audit,
1268            notifier: Arc::new(Notifier::new()),
1269            session,
1270        })
1271    }
1272
1273    /// The session uuid stamped on every audit line.
1274    #[must_use]
1275    pub fn session_id(&self) -> &str {
1276        &self.session
1277    }
1278
1279    /// Counters, for tests and for `get_server_stats`.
1280    #[must_use]
1281    pub fn stats(&self) -> &ServerStats {
1282        &self.stats
1283    }
1284
1285    #[must_use]
1286    pub fn notifier(&self) -> &Notifier {
1287        &self.notifier
1288    }
1289
1290    /// Open `binary_path` confined to the pinned allow roots.
1291    fn open_confined(&self, binary_path: &str) -> Result<ConfinedFile, ToolError> {
1292        confine::open_confined_with(
1293            &self.roots,
1294            binary_path,
1295            self.config.max_file_bytes,
1296            self.config.verbose_path_errors,
1297        )
1298    }
1299
1300    /// MCP-03 interim: reject an over-large `depth` instead of clamping it.
1301    fn check_depth(&self, depth: Option<usize>) -> Result<usize, ToolError> {
1302        let d = depth.unwrap_or(10);
1303        if d > self.config.max_depth {
1304            return Err(ToolError::with_details(
1305                ErrorCode::UsageError,
1306                format!(
1307                    "depth {d} exceeds the server's max_depth of {}; \
1308                     re-send with depth <= {}",
1309                    self.config.max_depth, self.config.max_depth
1310                ),
1311                json!({"limit": "max_depth",
1312                       "limit_value": self.config.max_depth,
1313                       "got": d}),
1314            ));
1315        }
1316        Ok(d)
1317    }
1318
1319    /// The effective configuration an agent is entitled to know, so it
1320    /// never has to guess a path (which is what made the error taxonomy
1321    /// worth probing in the first place — MCP-07).
1322    ///
1323    /// It also publishes the two enumerations CRIT-03 closed: every `order`
1324    /// and every `ErrorCode`. An agent that can read the taxonomy does not
1325    /// have to discover it by provoking failures.
1326    fn config_response(&self) -> schema::ConfigResponse {
1327        schema::ConfigResponse {
1328            allow_roots: self.root_paths(),
1329            max_depth: self.config.max_depth as u64,
1330            max_file_bytes: self.config.max_file_bytes,
1331            max_results: self.config.max_results as u64,
1332            hard_max_results: HARD_MAX_RESULTS as u64,
1333            max_concurrent: self.config.max_concurrent as u64,
1334            scan_threads: self.guard.scan_threads() as u64,
1335            max_gadgets: self.config.max_gadgets.map(|g| g as u64),
1336            max_sections: self.config.max_info_items as u64,
1337            max_imports: self.config.max_info_items as u64,
1338            timeout_secs: self.config.timeout.as_secs(),
1339            cache: self.config.cache_dir.is_some(),
1340            cache_mem_max_bytes: self.config.cache_mem_bytes,
1341            cache_ttl_secs: self.config.cache_ttl.as_secs(),
1342            cursor_ttl_secs: self.config.cursor_ttl.as_secs(),
1343            workspace_dir: self
1344                .config
1345                .workspace_dir
1346                .as_ref()
1347                .map(|p| p.display().to_string()),
1348            audit_log: self.audit.is_some(),
1349            probe_threshold: self.config.probe_threshold,
1350            orders: semantics::ORDER_NAMES
1351                .iter()
1352                .map(|s| (*s).to_string())
1353                .collect(),
1354            error_codes: ErrorCode::all()
1355                .iter()
1356                .map(|c| c.as_str().to_string())
1357                .collect(),
1358            version: env!("CARGO_PKG_VERSION").to_string(),
1359        }
1360    }
1361
1362    /// The effective allow roots, in operator-facing form.
1363    pub fn root_paths(&self) -> Vec<String> {
1364        self.roots
1365            .iter()
1366            .map(|r| r.display_path().display().to_string())
1367            .collect()
1368    }
1369
1370    /// [`query_to_request`] with the request-boundary depth check applied.
1371    fn gadget_request(
1372        &self,
1373        q: &GadgetQuery,
1374        rop: bool,
1375        jop: bool,
1376        sys: bool,
1377    ) -> Result<rf_api::ScanRequest, ToolError> {
1378        let depth = self.check_depth(q.depth)?;
1379        let mut req = query_to_request(q, rop, jop, sys);
1380        req.depth = depth;
1381        Ok(req)
1382    }
1383
1384    /// A future that resolves when the client sends
1385    /// `notifications/cancelled` for this request.
1386    ///
1387    /// rmcp cancels `RequestContext::ct`; [`guard::Guard::run`] bridges that
1388    /// to the engine's [`rf_scan::CancelToken`]. Before this the server
1389    /// accepted the notification and did nothing with it, and the
1390    /// depth-100000 request that had already been cancelled was at
1391    /// 54,873 MB RSS thirteen seconds later.
1392    fn cancel_signal(ctx: &RequestContext<RoleServer>) -> guard::CancelSignal {
1393        let ct = ctx.ct.clone();
1394        Box::pin(async move {
1395            ct.cancelled().await;
1396        })
1397    }
1398
1399    /// Start a tool call: register the peer for operator notifications,
1400    /// count the request, and open the audit record that will be written
1401    /// exactly once whatever happens next.
1402    fn begin(
1403        &self,
1404        ctx: &RequestContext<RoleServer>,
1405        tool: &'static str,
1406        params_hash: String,
1407    ) -> (AuditRecord, Instant) {
1408        self.notifier.register(&ctx.peer);
1409        self.stats.record_request(tool);
1410        let req_id = ctx.id.to_string();
1411        tracing::debug!(tool, req_id = %req_id, "tool call");
1412        (AuditRecord::new(req_id, tool, params_hash), Instant::now())
1413    }
1414
1415    /// Finish a tool call: classify the outcome, maintain the probing
1416    /// signal, write the ONE audit line, and render the response.
1417    async fn finish<T: Serialize>(
1418        &self,
1419        mut rec: AuditRecord,
1420        started: Instant,
1421        out: Result<T, ToolError>,
1422    ) -> Result<CallToolResult, McpError> {
1423        let verdict = match &out {
1424            Ok(_) => Verdict::Ok,
1425            Err(e) => {
1426                // The audit records the FINE reason (`file_too_large`,
1427                // `timeout_hard`, `busy`), not the closed wire code, so
1428                // collapsing the taxonomy for the agent costs the operator
1429                // nothing.
1430                rec.code = Some(e.kind.to_string());
1431                Verdict::for_code(e.kind)
1432            }
1433        };
1434        rec.verdict = verdict.as_str();
1435        let suspected = self
1436            .stats
1437            .record_verdict(verdict, self.config.probe_threshold);
1438        rec.probing_suspected = suspected;
1439        rec.duration_ms = started.elapsed().as_millis().min(u64::MAX as u128) as u64;
1440
1441        // The operator, who never sees stderr, is told about the two
1442        // conditions that mean something is wrong with the server or with
1443        // the client driving it.
1444        if let Err(e) = &out {
1445            if e.is_hard_timeout() {
1446                self.notifier.error(
1447                    "worker_wedged",
1448                    "a cancelled scan did not stop within the hard-join window",
1449                    json!({"tool": rec.tool, "wedged_total": self.stats.wedged_now()}),
1450                );
1451            }
1452        }
1453        if suspected {
1454            self.notifier.warn(
1455                "path_probing",
1456                "consecutive path_denied results suggest an agent is enumerating the filesystem",
1457                json!({"denied_consecutive": self.stats.denied_consecutive_now(),
1458                       "threshold": self.config.probe_threshold,
1459                       "requested": rec.binary}),
1460            );
1461        }
1462
1463        if let Some(log) = &self.audit {
1464            log.write(&rec);
1465        }
1466
1467        // MCP-09: once probing is suspected every response is delayed, so
1468        // a filesystem walk costs the caller wall-clock time. A legitimate
1469        // agent has read get_server_config and generates no denials, so it
1470        // never pays this.
1471        if suspected {
1472            tokio::time::sleep(PROBE_DELAY).await;
1473        }
1474
1475        match out {
1476            Ok(v) => tool_ok(&v),
1477            Err(e) => tool_error(e),
1478        }
1479    }
1480
1481    /// Run a scan with confinement + caps + cache, on the shared guard,
1482    /// then filter, order and page the result (CLS-08, CRIT-03,
1483    /// MCP-DESIGN fix #8).
1484    ///
1485    /// MCP-03/PERF-06: `guard.run` cancels the WORK on timeout and joins
1486    /// it before releasing the permit. The three ad-hoc
1487    /// `tokio::time::timeout(_, spawn_blocking(_))` blocks this replaces
1488    /// abandoned the await and left the scan running.
1489    async fn run_scan(
1490        &self,
1491        ctx: &RequestContext<RoleServer>,
1492        rec: &mut AuditRecord,
1493        req: rf_api::ScanRequest,
1494        binary_path: &str,
1495        post: PostOpts,
1496    ) -> Result<ScanResponse, ToolError> {
1497        let PostOpts {
1498            re: post_re,
1499            order,
1500            filter,
1501            cursor: cursor_in,
1502            params_hash,
1503            max_results,
1504            timeout_secs,
1505            ids,
1506        } = post;
1507        // MCP-01: an open HANDLE, not a name, crosses into the worker.
1508        rec.binary = Some(binary_path.to_string());
1509        let confined = self.open_confined(binary_path)?;
1510        // Inside a root: log the root-relative label, not the caller's
1511        // spelling of the path.
1512        rec.binary = Some(confined.label.clone());
1513        let binary_label = confined.label.clone();
1514        let declared_len = confined.len;
1515        let max = clamp_max_results(max_results, self.config.max_results);
1516        let timeout = clamp_timeout(timeout_secs, self.config.timeout);
1517        let cache = self.cache.clone();
1518        let max_file_bytes = self.config.max_file_bytes;
1519        let max_gadgets = self.config.max_gadgets;
1520        let workspace = self.config.workspace_dir.clone();
1521
1522        let work =
1523            move |cancel: rf_scan::CancelToken| -> Result<(ScanResponse, ScanFacts), ToolError> {
1524                let bytes = confined.read_all(max_file_bytes)?;
1525                let file_hash = sha256_hex(&bytes);
1526                // CLI-01/ENG-05, the MCP half: every parameter that can change
1527                // the output is in the key, or two different requests share an
1528                // entry and one of them is served the other's answer. `align`
1529                // and `arch` change WHAT IS SCANNED (ANCH-02, CORE-03);
1530                // `max_gadgets`/`max_memory` TRUNCATE a result, so a bounded
1531                // scan must never be served for an unbounded query; `compat`
1532                // decides whether a multi-slice container is scanned at all.
1533                // `rf_cache::make_key` folds in the key-schema version, so the
1534                // next addition to this list makes old entries MISS.
1535                //
1536                // `rec=3` is this crate's own record version, and it is here
1537                // because v0.3 started storing `delay_slot` in the MCP cache
1538                // record. A v0.2 entry has the field absent, which deserializes
1539                // to `false` — and `false` is a MEANINGFUL value on MIPS. The
1540                // discriminator makes every pre-0.3 entry miss rather than
1541                // report a wrong delay slot.
1542                let key = rf_cache::make_key(
1543                    &file_hash,
1544                    &format!(
1545                        "depth={}|rop={}|jop={}|sys={}|multibr={}|only={}|filter={}|range={}|\
1546                     badbytes={}|offset={}|section={:?}|thumb={}|base={}|cfg_aware={}|\
1547                     align={:?}|arch={}|all={}|noinstr={}|call_preceded={}|\
1548                     max_gadgets={:?}|max_memory={:?}|compat={}|rec=3",
1549                        req.depth,
1550                        req.rop,
1551                        req.jop,
1552                        req.sys,
1553                        req.multibr,
1554                        req.only.as_deref().unwrap_or(""),
1555                        req.filter.as_deref().unwrap_or(""),
1556                        req.range.as_deref().unwrap_or(""),
1557                        req.badbytes.as_deref().unwrap_or(""),
1558                        req.offset.as_deref().unwrap_or(""),
1559                        req.section,
1560                        req.thumb,
1561                        req.base.as_deref().unwrap_or(""),
1562                        req.cfg_aware,
1563                        req.align,
1564                        req.arch.as_deref().unwrap_or(""),
1565                        req.all,
1566                        req.noinstr,
1567                        req.call_preceded,
1568                        req.max_gadgets.or(max_gadgets),
1569                        req.max_memory,
1570                        req.compat,
1571                    ),
1572                );
1573                // The id is computed over the address with `--offset` undone,
1574                // so it does not change when the caller shifts the reported
1575                // addresses.
1576                let offset = match &req.offset {
1577                    Some(o) => rf_api::parse_hex(o, "--offset")
1578                        .map_err(|e| ToolError::new(ErrorCode::UsageError, e))?,
1579                    None => 0,
1580                };
1581                let class_arch = arch_from_bytes(&bytes);
1582                let mut warnings: Vec<Warning> = Vec::new();
1583
1584                // Three ways to get the gadget set, cheapest first. The pinned
1585                // store is what a cursor's next page hits: it holds the scan
1586                // AND its semantics, so paging a 40,872-gadget walk does not
1587                // reclassify the set once per page.
1588                let (scan, sems, cache_status) = if let Some(p) = cache.pinned(&key) {
1589                    // A pinned entry is a cache hit that also kept its semantics; the
1590                    // difference is invisible to the caller and observable to an
1591                    // operator as `cache.pinned_entries`.
1592                    (p.scan, p.sems, "hit")
1593                } else if let Some(hit) = cache.get(&key) {
1594                    let sems = Arc::new(semantics::classify_scan(
1595                        &hit, &file_hash, offset, class_arch,
1596                    ));
1597                    cache.pin(&key, hit.clone(), sems.clone());
1598                    (hit, sems, "hit")
1599                } else {
1600                    let product =
1601                        scan::scan_bytes_cancellable(&bytes, &req, &cancel, max_gadgets, None)
1602                            .map_err(scan::ScanFail::to_tool_error)?;
1603                    let arch = product.universal_arch.map(rf_api::arch_name);
1604                    let addr_size = product.addr_size;
1605                    let selected = product.selected_sections;
1606                    let id_ctx = semantics::IdContext {
1607                        binary_sha256: &file_hash,
1608                        offset,
1609                    };
1610                    // CLS-08: classify ONCE, here, and keep all of it. The old
1611                    // code classified in exactly this loop and then stored two
1612                    // fields of the result.
1613                    let classifier = class_arch.map(rf_classify::Classifier::new);
1614                    let mut gadgets = Vec::with_capacity(product.gadgets.len());
1615                    let mut built = Vec::with_capacity(product.gadgets.len());
1616                    for g in &product.gadgets {
1617                        let cls = classifier.as_ref().map(|c| c.classify(g));
1618                        gadgets.push(CachedGadget {
1619                            vaddr: rf_api::fmt_addr(g.vaddr, addr_size),
1620                            bytes: g.bytes_hex(),
1621                            text: g.text(),
1622                            arch: arch.map(str::to_string),
1623                            section: selected
1624                                .as_deref()
1625                                .and_then(|s| rf_api::section_of(s, g.vaddr.wrapping_sub(offset))),
1626                            quality: cls.as_ref().map(|c| c.quality),
1627                            class: cls.as_ref().map(|c| c.primary.name().to_string()),
1628                            // CRIT-03: `delay_slot` is computed by the engine
1629                            // and was dropped at every output boundary, so a
1630                            // MIPS gadget reached the agent with no sign that
1631                            // its last instruction runs BEFORE the branch.
1632                            delay_slot: g.delay_slot,
1633                            ..CachedGadget::default()
1634                        });
1635                        built.push(semantics::from_scan_gadget(g, cls, &id_ctx));
1636                    }
1637                    let arc = cache.put(
1638                        &key,
1639                        CachedScan {
1640                            gadgets,
1641                            fallback_names: product.fallback_names,
1642                            ..CachedScan::default()
1643                        },
1644                    );
1645                    let sems = Arc::new(built);
1646                    cache.pin(&key, arc.clone(), sems.clone());
1647                    (arc, sems, "miss")
1648                };
1649
1650                // ---- select -------------------------------------------------
1651                let mut idx: Vec<usize> = match &ids {
1652                    Some(want) => {
1653                        let mut by_id: std::collections::HashMap<&str, usize> =
1654                            std::collections::HashMap::with_capacity(sems.len());
1655                        for (i, s) in sems.iter().enumerate() {
1656                            by_id.entry(s.id.as_str()).or_insert(i);
1657                        }
1658                        let mut out = Vec::with_capacity(want.len());
1659                        let mut missing: Vec<&str> = Vec::new();
1660                        for id in want {
1661                            match by_id.get(id.as_str()) {
1662                                Some(&i) => out.push(i),
1663                                None => missing.push(id.as_str()),
1664                            }
1665                        }
1666                        if !missing.is_empty() {
1667                            warnings.push(
1668                                Warning::truncation(
1669                                    "ids_not_found",
1670                                    "gadgets",
1671                                    out.len(),
1672                                    want.len(),
1673                                )
1674                                .with_detail(missing.join(",")),
1675                            );
1676                        }
1677                        out
1678                    }
1679                    None => (0..scan.gadgets.len()).collect(),
1680                };
1681                // The only surviving text post-filter is --re, which is a
1682                // post-filter in ROPgadget too. --align is an engine option
1683                // (ANCH-02) and has already been applied by the scan above.
1684                if let Some(re) = &post_re {
1685                    match regex::Regex::new(re) {
1686                        Ok(re) => idx
1687                            .retain(|&i| scan.gadgets.get(i).is_some_and(|g| re.is_match(&g.text))),
1688                        Err(_) => idx.retain(|&i| {
1689                            scan.gadgets
1690                                .get(i)
1691                                .is_some_and(|g| g.text.contains(re.as_str()))
1692                        }),
1693                    }
1694                }
1695                if !filter.is_empty() {
1696                    idx.retain(|&i| sems.get(i).is_some_and(|s| filter.matches(s)));
1697                }
1698                semantics::sort_indices(&mut idx, order, &scan, &sems);
1699
1700                // ---- page ---------------------------------------------------
1701                let total = idx.len() as u64;
1702                let start = match &cursor_in {
1703                    Some(raw) => Cursor::decode(raw, &key, order.as_str(), &params_hash)?.offset,
1704                    None => 0,
1705                };
1706                let page: Vec<usize> = idx
1707                    .iter()
1708                    .skip(usize::try_from(start).unwrap_or(usize::MAX))
1709                    .take(max)
1710                    .copied()
1711                    .collect();
1712                let gadgets: Vec<GadgetRecord> = page
1713                    .iter()
1714                    .filter_map(|&i| Some(GadgetRecord::build(scan.gadgets.get(i)?, sems.get(i)?)))
1715                    .collect();
1716                let returned = gadgets.len() as u64;
1717                let truncated = start.saturating_add(returned) < total;
1718
1719                // ---- warnings ------------------------------------------------
1720                if scan.fallback_names {
1721                    warnings.push(Warning::new(
1722                        "fallback_section_names",
1723                        "the binary has no section names; synthetic PT_LOAD#n names were matched \
1724                     instead, so `section` values are positional rather than real",
1725                    ));
1726                }
1727                if let Some(slice) = scan.gadgets.first().and_then(|g| g.arch.clone()) {
1728                    warnings.push(
1729                        Warning::new(
1730                            "universal_slice_selected",
1731                            "this is one slice of a fat (Universal) Mach-O; addresses are that \
1732                         slice's",
1733                        )
1734                        .with_detail(slice),
1735                    );
1736                }
1737                if gadgets.iter().any(|g| g.low_confidence) {
1738                    warnings.push(Warning::new(
1739                        "low_confidence_classification",
1740                        "some gadgets were classified from disassembly text rather than decoder \
1741                     metadata; treat class/labels/regs on those as advisory",
1742                    ));
1743                }
1744                if truncated {
1745                    warnings.push(Warning::truncation(
1746                        "truncated",
1747                        "gadgets",
1748                        usize::try_from(returned).unwrap_or(usize::MAX),
1749                        usize::try_from(total).unwrap_or(usize::MAX),
1750                    ));
1751                }
1752
1753                // ---- resources -----------------------------------------------
1754                let paged = total > returned;
1755                let resource_uri = paged.then(|| resources::scan_uri(&key));
1756                let workspace_file = match (&workspace, paged) {
1757                    (Some(dir), true) => {
1758                        resources::ensure_file(dir, &key, || resources::render_ndjson(&scan, &sems))
1759                            .map(|p| p.display().to_string())
1760                    }
1761                    _ => None,
1762                };
1763
1764                let facts = ScanFacts {
1765                    sha256: file_hash.clone(),
1766                    bytes_read: bytes.len() as u64,
1767                    cache: cache_status,
1768                    total_count: total,
1769                    returned,
1770                };
1771                Ok((
1772                    ScanResponse {
1773                        gadgets,
1774                        total_count: total,
1775                        returned,
1776                        offset: start,
1777                        truncated,
1778                        next_cursor: Cursor::next(
1779                            &key,
1780                            order.as_str(),
1781                            &params_hash,
1782                            start,
1783                            returned,
1784                            total,
1785                        ),
1786                        order: order.as_str().to_string(),
1787                        binary_sha256: file_hash,
1788                        binary_label,
1789                        cache: cache_status.to_string(),
1790                        cache_key: key,
1791                        fallback_section_names: scan.fallback_names,
1792                        warnings,
1793                        resource_uri,
1794                        workspace_file,
1795                    },
1796                    facts,
1797                ))
1798            };
1799
1800        let out = self
1801            .guard
1802            .run(Some(Self::cancel_signal(ctx)), timeout, work)
1803            .await;
1804        match out {
1805            Ok((v, facts)) => {
1806                facts.apply(rec);
1807                self.stats.add_bytes_read(facts.bytes_read);
1808                Ok(v)
1809            }
1810            Err(e) => {
1811                // The read never completed, so nothing was read; the
1812                // declared size is still worth recording for a timeout.
1813                rec.bytes_read = 0;
1814                tracing::debug!(code = e.kind, declared_len, "tool call failed");
1815                Err(e)
1816            }
1817        }
1818    }
1819
1820    /// CLI-05 / ECO-02 — the body of `find_string` and `find_bytes`.
1821    ///
1822    /// Everything a gadget scan gets, a search gets: the same confined
1823    /// handle, the same guard (so it is cancellable, timed out and
1824    /// semaphore-bounded), the same cursor contract and the same NDJSON
1825    /// resource (ECO-09). What it does NOT get is the file: every byte it
1826    /// examines comes out of a [`rf_core::Section`] the loader
1827    /// materialised, which is the property that makes exposing this
1828    /// through the MCP safe at all (see [`crate::find`]).
1829    async fn run_find(
1830        &self,
1831        ctx: &RequestContext<RoleServer>,
1832        rec: &mut AuditRecord,
1833        opts: FindRequest,
1834    ) -> Result<find::SearchHitsResponse, ToolError> {
1835        let FindRequest {
1836            binary_path,
1837            mode,
1838            query,
1839            base,
1840            offset,
1841            range,
1842            arch,
1843            max_results,
1844            cursor: cursor_in,
1845            params_hash,
1846            timeout_secs,
1847        } = opts;
1848
1849        // A bad pattern is the caller's mistake, so it is diagnosed BEFORE
1850        // a file is opened, a permit is taken or a byte is read.
1851        let byte_pattern = match mode {
1852            find::Mode::Opcode => Some(find::BytePattern::parse(&query)?),
1853            _ => None,
1854        };
1855
1856        rec.binary = Some(binary_path.clone());
1857        let confined = self.open_confined(&binary_path)?;
1858        rec.binary = Some(confined.label.clone());
1859        let binary_label = confined.label.clone();
1860        let base_value = base
1861            .as_deref()
1862            .map(|b| rf_api::parse_hex(b, "base"))
1863            .transpose()
1864            .map_err(|e| ToolError::new(ErrorCode::UsageError, e))?;
1865        let offset_value = offset
1866            .as_deref()
1867            .map(|o| rf_api::parse_hex(o, "offset"))
1868            .transpose()
1869            .map_err(|e| ToolError::new(ErrorCode::UsageError, e))?
1870            .unwrap_or(0);
1871        let range_value = range
1872            .as_deref()
1873            .map(rf_api::parse_range)
1874            .transpose()
1875            .map_err(|e| ToolError::new(ErrorCode::UsageError, e))?
1876            .flatten();
1877        let page = clamp_max_results(max_results, self.config.max_results);
1878        let timeout = clamp_timeout(timeout_secs, self.config.timeout);
1879        let max_file_bytes = self.config.max_file_bytes;
1880        let workspace = self.config.workspace_dir.clone();
1881        let cache = self.cache.clone();
1882
1883        let work = move |_cancel: rf_scan::CancelToken| -> Result<
1884            (find::SearchHitsResponse, ScanFacts),
1885            ToolError,
1886        > {
1887            let bytes = confined.read_all(max_file_bytes)?;
1888            let file_hash = sha256_hex(&bytes);
1889            let target = rf_api::load_target(&bytes, None).map_err(scan_err_to_tool)?;
1890            // CORE-03: a fat container is refused rather than searched as a
1891            // concatenation, exactly as a scan of one is.
1892            let selected = rf_api::resolve_arch(&target, arch.as_deref(), false)
1893                .map_err(scan_err_to_tool)?;
1894            let slice = match (&target, selected) {
1895                (rf_api::Target::Universal(u), Some(a)) => {
1896                    Some(u.select(a).map_err(|e| {
1897                        ToolError::new(ErrorCode::UsageError, e.to_string())
1898                    })?)
1899                }
1900                _ => None,
1901            };
1902            let view = rf_api::build_view_selected(&target, selected);
1903            let image_base = view.base;
1904            let delta = base_value.map_or(0, |b| b.wrapping_sub(image_base));
1905            let opts = find::SearchOpts {
1906                delta,
1907                offset: offset_value,
1908                range: range_value,
1909                addr_size: search_addr_size(&target, rf_core::Image::arch(&view)),
1910                // Collect up to the hard cap so `total_count` and the
1911                // cursor walk agree; the PAGE is `max_results`.
1912                max_hits: HARD_MAX_RESULTS,
1913            };
1914            let windows = match mode {
1915                find::Mode::String => find::data_windows(&target, slice, delta),
1916                find::Mode::Opcode => find::exec_windows(&target, slice, delta),
1917                // core.py:202-227 — exec sections first, then data.
1918                find::Mode::MemStr => {
1919                    let mut w = find::exec_windows(&target, slice, delta);
1920                    w.extend(find::data_windows(&target, slice, delta));
1921                    w
1922                }
1923            };
1924            let sections_searched = find::window_names(&windows);
1925            let mut warnings: Vec<Warning> = Vec::new();
1926            if windows.is_empty() {
1927                warnings.push(Warning::new(
1928                    "no_mapped_sections",
1929                    "this container exposes no mapped section of the kind this search reads, \
1930                     so the answer is empty by construction rather than by absence",
1931                ));
1932            }
1933
1934            let (all_hits, total) = match (mode, &byte_pattern) {
1935                (find::Mode::String, _) => find::find_string(&windows, &query, &opts)?,
1936                (find::Mode::MemStr, _) => find::find_memstr(&windows, &query, &opts),
1937                (find::Mode::Opcode, Some(p)) => find::find_opcode(&windows, p, &opts),
1938                // `byte_pattern` is built above for exactly this mode.
1939                (find::Mode::Opcode, None) => {
1940                    return Err(ToolError::new(
1941                        ErrorCode::Internal,
1942                        "the opcode pattern was not compiled",
1943                    ))
1944                }
1945            };
1946            if total > all_hits.len() as u64 {
1947                warnings.push(Warning::truncation(
1948                    "hits_capped",
1949                    "hits",
1950                    all_hits.len(),
1951                    usize::try_from(total).unwrap_or(usize::MAX),
1952                ));
1953            }
1954
1955            // The cursor key names this exact result set: the file, the
1956            // mode and every parameter that decides which bytes were read.
1957            let key = format!(
1958                "s{}",
1959                rf_cache::sha256_hex(
1960                    format!(
1961                        "{file_hash}|{}|{query}|base={base_value:?}|offset={offset_value}|\
1962                         range={range_value:?}|arch={}",
1963                        mode.as_str(),
1964                        arch.as_deref().unwrap_or("")
1965                    )
1966                    .as_bytes()
1967                )
1968            );
1969            let walkable = all_hits.len() as u64;
1970            let start = match &cursor_in {
1971                Some(raw) => Cursor::decode(raw, &key, "address", &params_hash)?.offset,
1972                None => 0,
1973            };
1974            let hits: Vec<find::Hit> = all_hits
1975                .iter()
1976                .skip(usize::try_from(start).unwrap_or(usize::MAX))
1977                .take(page)
1978                .cloned()
1979                .collect();
1980            let returned = hits.len() as u64;
1981            let truncated = start.saturating_add(returned) < total;
1982            if truncated {
1983                warnings.push(Warning::truncation(
1984                    "truncated",
1985                    "hits",
1986                    usize::try_from(returned).unwrap_or(usize::MAX),
1987                    usize::try_from(total).unwrap_or(usize::MAX),
1988                ));
1989            }
1990
1991            // ECO-09: a paged answer also names the WHOLE set as NDJSON,
1992            // pinned in the same bounded store a paged scan uses.
1993            let paged = walkable > returned;
1994            let (resource_uri, workspace_file) = if paged {
1995                let ndjson = find::render_ndjson(&all_hits);
1996                cache.pin_text(&key, &ndjson);
1997                let file = workspace
1998                    .as_deref()
1999                    .and_then(|dir| resources::ensure_file(dir, &key, || ndjson.clone()))
2000                    .map(|p| p.display().to_string());
2001                (Some(resources::search_uri(&key)), file)
2002            } else {
2003                (None, None)
2004            };
2005
2006            let facts = ScanFacts {
2007                sha256: file_hash.clone(),
2008                bytes_read: bytes.len() as u64,
2009                cache: "none",
2010                total_count: total,
2011                returned,
2012            };
2013            Ok((
2014                find::SearchHitsResponse {
2015                    hits,
2016                    mode: mode.as_str().to_string(),
2017                    query: query.clone(),
2018                    total_count: total,
2019                    returned,
2020                    offset: start,
2021                    truncated,
2022                    next_cursor: Cursor::next(
2023                        &key,
2024                        "address",
2025                        &params_hash,
2026                        start,
2027                        returned,
2028                        walkable,
2029                    ),
2030                    sections_searched,
2031                    binary_sha256: file_hash,
2032                    binary_label,
2033                    warnings,
2034                    resource_uri,
2035                    workspace_file,
2036                },
2037                facts,
2038            ))
2039        };
2040
2041        match self
2042            .guard
2043            .run(Some(Self::cancel_signal(ctx)), timeout, work)
2044            .await
2045        {
2046            Ok((v, facts)) => {
2047                facts.apply(rec);
2048                self.stats.add_bytes_read(facts.bytes_read);
2049                Ok(v)
2050            }
2051            Err(e) => {
2052                rec.bytes_read = 0;
2053                Err(e)
2054            }
2055        }
2056    }
2057
2058    /// ECO-06 — the body of `get_mitigations`.
2059    async fn run_mitigations(
2060        &self,
2061        ctx: &RequestContext<RoleServer>,
2062        rec: &mut AuditRecord,
2063        q: &MitigationsQuery,
2064    ) -> Result<checksec::MitigationsResponse, ToolError> {
2065        rec.binary = Some(q.binary_path.clone());
2066        let confined = self.open_confined(&q.binary_path)?;
2067        rec.binary = Some(confined.label.clone());
2068        let label = confined.label.clone();
2069        let timeout = clamp_timeout(q.timeout_secs, self.config.timeout);
2070        let max_file_bytes = self.config.max_file_bytes;
2071
2072        let work = move |_cancel: rf_scan::CancelToken| -> Result<
2073            (checksec::MitigationsResponse, ScanFacts),
2074            ToolError,
2075        > {
2076            let bytes = confined.read_all(max_file_bytes)?;
2077            let file_hash = sha256_hex(&bytes);
2078            let target = rf_api::load_target(&bytes, None).map_err(scan_err_to_tool)?;
2079            let out = checksec::report(&target, file_hash.clone(), label);
2080            let facts = ScanFacts {
2081                sha256: file_hash,
2082                bytes_read: bytes.len() as u64,
2083                cache: "none",
2084                total_count: 0,
2085                returned: 0,
2086            };
2087            Ok((out, facts))
2088        };
2089
2090        match self
2091            .guard
2092            .run(Some(Self::cancel_signal(ctx)), timeout, work)
2093            .await
2094        {
2095            Ok((v, facts)) => {
2096                rec.binary_sha256 = Some(facts.sha256.clone());
2097                rec.bytes_read = facts.bytes_read;
2098                rec.cache = Some("none");
2099                self.stats.add_bytes_read(facts.bytes_read);
2100                Ok(v)
2101            }
2102            Err(e) => Err(e),
2103        }
2104    }
2105
2106    /// `get_binary_info` (MCP-06): the one tool that used to have neither a
2107    /// timeout nor a cap, and that did its whole-file read plus goblin
2108    /// parse INLINE on the async runtime, occupying a tokio worker.
2109    async fn run_info(
2110        &self,
2111        ctx: &RequestContext<RoleServer>,
2112        rec: &mut AuditRecord,
2113        q: &InfoQuery,
2114    ) -> Result<InfoResponse, ToolError> {
2115        rec.binary = Some(q.binary_path.clone());
2116        let confined = self.open_confined(&q.binary_path)?;
2117        rec.binary = Some(confined.label.clone());
2118        let base = q
2119            .base
2120            .as_deref()
2121            .map(|b| rf_api::parse_hex(b, "--base"))
2122            .transpose()
2123            .map_err(|e| ToolError::new(ErrorCode::UsageError, e))?;
2124        let timeout = clamp_timeout(q.timeout_secs, self.config.timeout);
2125        let max_file_bytes = self.config.max_file_bytes;
2126        let cap = self.config.max_info_items;
2127        let max_sections = q.max_sections.unwrap_or(cap).clamp(1, cap);
2128        let max_imports = q.max_imports.unwrap_or(cap).clamp(1, cap);
2129        let max_symbols = q.max_symbols.unwrap_or(DEFAULT_MAX_SYMBOLS).min(cap);
2130
2131        let work =
2132            move |_cancel: rf_scan::CancelToken| -> Result<(InfoResponse, ScanFacts), ToolError> {
2133                let bytes = confined.read_all(max_file_bytes)?;
2134                let file_hash = sha256_hex(&bytes);
2135                let mut v = rf_api::info_bytes(&bytes, None, base).map_err(scan_err_to_tool)?;
2136                let warnings = truncate_info(&mut v, max_sections, max_imports, max_symbols);
2137                let out = InfoResponse::from_value(v, file_hash.clone(), warnings);
2138                let facts = ScanFacts {
2139                    sha256: file_hash,
2140                    bytes_read: bytes.len() as u64,
2141                    cache: "none",
2142                    total_count: 0,
2143                    returned: 0,
2144                };
2145                Ok((out, facts))
2146            };
2147
2148        match self
2149            .guard
2150            .run(Some(Self::cancel_signal(ctx)), timeout, work)
2151            .await
2152        {
2153            Ok((v, facts)) => {
2154                rec.binary_sha256 = Some(facts.sha256.clone());
2155                rec.bytes_read = facts.bytes_read;
2156                rec.cache = Some("none");
2157                self.stats.add_bytes_read(facts.bytes_read);
2158                Ok(v)
2159            }
2160            Err(e) => Err(e),
2161        }
2162    }
2163
2164    /// Build a ROP chain with confinement + the shared guard. Unlike scans,
2165    /// chain builds are not cache-backed (a chain is a single compact
2166    /// artifact, and its inputs — the scan — would have to be re-validated
2167    /// anyway).
2168    async fn run_chain(
2169        &self,
2170        ctx: &RequestContext<RoleServer>,
2171        rec: &mut AuditRecord,
2172        q: ChainQuery,
2173    ) -> Result<ChainResponse, ToolError> {
2174        if !rf_api::chain_targets().contains(&q.target.as_str()) {
2175            return Err(ToolError::new(
2176                ErrorCode::UsageError,
2177                format!(
2178                    "unknown chain target {:?}; supported: {}",
2179                    q.target,
2180                    rf_api::chain_targets().join(", ")
2181                ),
2182            ));
2183        }
2184        let depth = self.check_depth(q.depth)?;
2185        rec.binary = Some(q.binary_path.clone());
2186        let confined = self.open_confined(&q.binary_path)?;
2187        rec.binary = Some(confined.label.clone());
2188        let label = confined.label.clone();
2189        let timeout = clamp_timeout(q.timeout_secs, self.config.timeout);
2190        let max_file_bytes = self.config.max_file_bytes;
2191        let req = chain_scan_request(&q, depth, self.config.max_gadgets);
2192        let spec = chain_spec(&q);
2193        // ECO-02: the target's parameters are validated by the SAME
2194        // functions the CLI uses, before the scan, so an unknown api_name /
2195        // chain_base / syscall_args value is a usage error on both surfaces
2196        // with the same accepted set (tests/capability_matrix.py gates it).
2197        if spec.target == "windows-virtualprotect" {
2198            rf_api::win_opts(&spec).map_err(scan_err_to_tool)?;
2199        } else {
2200            rf_api::linux_opts(&spec).map_err(scan_err_to_tool)?;
2201        }
2202
2203        // NOTE (MCP-03, residual): `rf_api::chain_bytes` runs its own scan
2204        // and has no token seam, so a chain build is bounded by the
2205        // timeout and the join rather than interrupted mid-scan. `depth`
2206        // is already capped at `--max-depth`, and a worker that does not
2207        // stop within the hard-join window is reported as `timeout_hard`
2208        // and counted in `wedged_total` rather than silently orphaned.
2209        // The seam closes when rf-cli grows `chain_bytes_cancellable`
2210        // (MCP-DESIGN fix #4 part C).
2211        let binary_label = label.clone();
2212        let offset_hex = q.offset.clone();
2213        let work =
2214            move |_cancel: rf_scan::CancelToken| -> Result<(ChainResponse, ScanFacts), ToolError> {
2215                let bytes = confined.read_all(max_file_bytes)?;
2216                let file_hash = sha256_hex(&bytes);
2217                let outcome =
2218                    rf_api::chain_bytes(&bytes, None, &req, &spec).map_err(scan_err_to_tool)?;
2219                let offset = match &offset_hex {
2220                    Some(o) => rf_api::parse_hex(o, "--offset")
2221                        .map_err(|e| ToolError::new(ErrorCode::UsageError, e))?,
2222                    None => 0,
2223                };
2224                let facts = ScanFacts {
2225                    sha256: file_hash.clone(),
2226                    bytes_read: bytes.len() as u64,
2227                    cache: "bypass",
2228                    total_count: outcome.chain.words.len() as u64,
2229                    returned: outcome.chain.words.len() as u64,
2230                };
2231                let out = chain_response(&outcome, file_hash, binary_label, offset);
2232                Ok((out, facts))
2233            };
2234
2235        match self
2236            .guard
2237            .run(Some(Self::cancel_signal(ctx)), timeout, work)
2238            .await
2239        {
2240            Ok((v, facts)) => {
2241                facts.apply(rec);
2242                self.stats.add_bytes_read(facts.bytes_read);
2243                Ok(v)
2244            }
2245            Err(e) => Err(e),
2246        }
2247    }
2248
2249    /// `ECO-04`: the feasibility report. Never fails for a reason the
2250    /// binary is responsible for — an infeasible chain is a `feasible:
2251    /// false` document with the requirement that failed, what was tried,
2252    /// and which parameter changes the server MEASURED would help.
2253    async fn run_plan(
2254        &self,
2255        ctx: &RequestContext<RoleServer>,
2256        rec: &mut AuditRecord,
2257        q: ChainQuery,
2258    ) -> Result<schema::PlanResponse, ToolError> {
2259        if !rf_api::chain_targets().contains(&q.target.as_str()) {
2260            return Err(ToolError::new(
2261                ErrorCode::UsageError,
2262                format!(
2263                    "unknown chain target {:?}; supported: {}",
2264                    q.target,
2265                    rf_api::chain_targets().join(", ")
2266                ),
2267            ));
2268        }
2269        let depth = self.check_depth(q.depth)?;
2270        rec.binary = Some(q.binary_path.clone());
2271        let confined = self.open_confined(&q.binary_path)?;
2272        rec.binary = Some(confined.label.clone());
2273        let label = confined.label.clone();
2274        let timeout = clamp_timeout(q.timeout_secs, self.config.timeout);
2275        let max_file_bytes = self.config.max_file_bytes;
2276        let req = chain_scan_request(&q, depth, self.config.max_gadgets);
2277        let spec = chain_spec(&q);
2278        if spec.target == "windows-virtualprotect" {
2279            rf_api::win_opts(&spec).map_err(scan_err_to_tool)?;
2280        } else {
2281            rf_api::linux_opts(&spec).map_err(scan_err_to_tool)?;
2282        }
2283        let binary_label = label.clone();
2284        let offset_hex = q.offset.clone();
2285        let work = move |_cancel: rf_scan::CancelToken| -> Result<
2286            (schema::PlanResponse, ScanFacts),
2287            ToolError,
2288        > {
2289            let bytes = confined.read_all(max_file_bytes)?;
2290            let file_hash = sha256_hex(&bytes);
2291            let offset = match &offset_hex {
2292                Some(o) => rf_api::parse_hex(o, "--offset")
2293                    .map_err(|e| ToolError::new(ErrorCode::UsageError, e))?,
2294                None => 0,
2295            };
2296            let outcome =
2297                rf_api::plan_chain_bytes(&bytes, None, &req, &spec).map_err(scan_err_to_tool)?;
2298            let out = plan_response(&outcome, file_hash.clone(), binary_label, offset);
2299            let facts = ScanFacts {
2300                sha256: file_hash,
2301                bytes_read: bytes.len() as u64,
2302                cache: "bypass",
2303                total_count: out.requirements.len() as u64,
2304                returned: out.satisfied_requirements.len() as u64,
2305            };
2306            Ok((out, facts))
2307        };
2308        match self
2309            .guard
2310            .run(Some(Self::cancel_signal(ctx)), timeout, work)
2311            .await
2312        {
2313            Ok((v, facts)) => {
2314                facts.apply(rec);
2315                self.stats.add_bytes_read(facts.bytes_read);
2316                Ok(v)
2317            }
2318            Err(e) => Err(e),
2319        }
2320    }
2321}
2322
2323/// What a worker learned that the audit line needs and the response body
2324/// does not carry in a fixed place.
2325struct ScanFacts {
2326    sha256: String,
2327    bytes_read: u64,
2328    cache: &'static str,
2329    total_count: u64,
2330    returned: u64,
2331}
2332
2333impl ScanFacts {
2334    fn apply(&self, rec: &mut AuditRecord) {
2335        rec.binary_sha256 = Some(self.sha256.clone());
2336        rec.bytes_read = self.bytes_read;
2337        rec.cache = Some(self.cache);
2338        rec.total_count = Some(self.total_count);
2339        rec.returned = Some(self.returned);
2340    }
2341}
2342
2343/// MCP-06: cap `sections` and `imports`, returning the `warnings` entries.
2344///
2345/// A hostile PE with a million import entries must not be able to make the
2346/// server serialize a gigabyte of JSON into an agent's context. Truncation
2347/// is announced rather than silent: an agent that sees
2348/// `imports_truncated` knows the list is partial, where a silently short
2349/// list would be indistinguishable from a binary with few imports.
2350fn truncate_info(
2351    v: &mut Value,
2352    max_sections: usize,
2353    max_imports: usize,
2354    max_symbols: usize,
2355) -> Vec<Warning> {
2356    let mut warnings = Vec::new();
2357    let Some(obj) = v.as_object_mut() else {
2358        return warnings;
2359    };
2360    for (field, cap, code) in [
2361        ("sections", max_sections, "sections_truncated"),
2362        ("imports", max_imports, "imports_truncated"),
2363        // ECO-06: `symbol_count` is deliberately NOT truncated with the
2364        // array, so the response always states how many there really were.
2365        ("symbols", max_symbols, "symbols_truncated"),
2366    ] {
2367        let Some(Value::Array(a)) = obj.get_mut(field) else {
2368            continue;
2369        };
2370        let total = a.len();
2371        if total > cap {
2372            a.truncate(cap);
2373            let mut w = Warning::truncation(code, field, cap, total);
2374            if field == "symbols" {
2375                // The symbols default is 0 (see DEFAULT_MAX_SYMBOLS), so this
2376                // warning is the ONLY thing telling an agent the table exists
2377                // and how to ask for it. Say so rather than leaving `returned:
2378                // 0` to be read as "there are none".
2379                w.detail = Some(
2380                    "symbols are opt-in: pass max_symbols (up to 4096) to include them.                      `imports` (the SHN_UNDEF subset, with GOT/PLT) is reported regardless."
2381                        .to_string(),
2382                );
2383            }
2384            warnings.push(w);
2385        }
2386    }
2387    warnings
2388}
2389
2390/// `ChainQuery` is `Deserialize` but not `Clone` (it is a wire type, and
2391/// deriving `Clone` on it would put a second copy of every future field in
2392/// the schema's derive chain). `build_rop_chain` needs one extra copy to
2393/// re-probe with, so the copy is spelled out here where a new field makes
2394/// it a compile error rather than a silently dropped parameter.
2395fn clone_query(q: &ChainQuery) -> ChainQuery {
2396    ChainQuery {
2397        binary_path: q.binary_path.clone(),
2398        target: q.target.clone(),
2399        depth: q.depth,
2400        base: q.base.clone(),
2401        offset: q.offset.clone(),
2402        badbytes: q.badbytes.clone(),
2403        cfg_aware: q.cfg_aware,
2404        api_addr: q.api_addr.clone(),
2405        api_name: q.api_name.clone(),
2406        shellcode_addr: q.shellcode_addr.clone(),
2407        shellcode_size: q.shellcode_size.clone(),
2408        chain_base: q.chain_base.clone(),
2409        prot: q.prot.clone(),
2410        syscall: q.syscall.clone(),
2411        syscall_args: q.syscall_args.clone(),
2412        chain_pivot: q.chain_pivot.clone(),
2413        stage: q.stage.clone(),
2414        arch: q.arch.clone(),
2415        timeout_secs: q.timeout_secs,
2416    }
2417}
2418
2419/// The `ScanRequest` a chain build / plan runs its scan with. One place,
2420/// so `build_rop_chain` and `plan_chain` cannot answer about two different
2421/// gadget universes.
2422fn chain_scan_request(
2423    q: &ChainQuery,
2424    depth: usize,
2425    max_gadgets: Option<usize>,
2426) -> rf_api::ScanRequest {
2427    rf_api::ScanRequest {
2428        depth,
2429        rop: true,
2430        jop: true,
2431        sys: true,
2432        multibr: false,
2433        only: None,
2434        filter: None,
2435        range: None,
2436        badbytes: q.badbytes.clone(),
2437        offset: q.offset.clone(),
2438        base: q.base.clone(),
2439        section: Vec::new(),
2440        thumb: false,
2441        cfg_aware: q.cfg_aware.unwrap_or(false),
2442        align: None,
2443        call_preceded: false,
2444        all: false,
2445        noinstr: false,
2446        arch: q.arch.clone(),
2447        max_gadgets,
2448        max_memory: None,
2449        compat: false,
2450    }
2451}
2452
2453/// The `ChainSpec` for a query. Shared by `build_rop_chain` and
2454/// `plan_chain`, and identical field for field to what the CLI builds from
2455/// its flags (ECO-02).
2456fn chain_spec(q: &ChainQuery) -> rf_api::ChainSpec {
2457    rf_api::ChainSpec {
2458        target: q.target.clone(),
2459        api_addr: q.api_addr.clone(),
2460        api_name: q.api_name.clone(),
2461        shellcode_addr: q.shellcode_addr.clone(),
2462        shellcode_size: q.shellcode_size.clone(),
2463        chain_base: q.chain_base.clone(),
2464        prot: q.prot.clone(),
2465        syscall: q.syscall.clone(),
2466        syscall_args: q.syscall_args.clone(),
2467        pivot: q.chain_pivot.clone(),
2468        stage: q.stage.clone(),
2469    }
2470}
2471
2472/// `ECO-04`: the plan, with every satisfying gadget carrying the same
2473/// stable id `find_gadgets` handed out — so `get_gadgets` resolves it.
2474fn plan_response(
2475    outcome: &rf_api::ChainPlanOutcome,
2476    binary_sha256: String,
2477    binary_label: String,
2478    offset: u64,
2479) -> schema::PlanResponse {
2480    let mut plan = outcome.plan.clone();
2481    let sha = binary_sha256.clone();
2482    plan.attach_gadget_ids(|vaddr| {
2483        outcome
2484            .gadget_bytes(vaddr)
2485            .map(|b| schema::gadget_id(&sha, vaddr.wrapping_sub(offset), b))
2486    });
2487    schema::PlanResponse::from_plan(&plan, binary_sha256, binary_label)
2488}
2489
2490/// Build the chain response, giving every referenced gadget the same stable
2491/// id `find_gadgets` would.
2492///
2493/// The chain IR carries only `{vaddr, text}` per gadget, and an id needs the
2494/// gadget's BYTES — so they are recovered from the scan the chain was built
2495/// from, which `rf_api::chain_bytes` hands back. Where a gadget cannot be
2496/// matched the id is `null` rather than fabricated.
2497fn chain_response(
2498    outcome: &rf_api::ChainOutcome,
2499    binary_sha256: String,
2500    binary_label: String,
2501    offset: u64,
2502) -> ChainResponse {
2503    let chain = &outcome.chain;
2504    let by_vaddr: std::collections::HashMap<u64, &[u8]> = outcome
2505        .outcome
2506        .result
2507        .gadgets
2508        .iter()
2509        .map(|g| (g.vaddr, g.bytes.as_slice()))
2510        .collect();
2511    let gadgets = chain
2512        .gadgets
2513        .iter()
2514        .map(|g| schema::ChainGadgetRef {
2515            vaddr: format!("0x{:x}", g.vaddr),
2516            vaddr_u64: g.vaddr,
2517            text: g.text.clone(),
2518            id: by_vaddr
2519                .get(&g.vaddr)
2520                .map(|b| schema::gadget_id(&binary_sha256, g.vaddr.wrapping_sub(offset), b)),
2521        })
2522        .collect();
2523    let words = chain
2524        .words
2525        .iter()
2526        .map(|w| schema::ChainWordRecord {
2527            value: format!("0x{:x}", w.value),
2528            kind: match w.kind {
2529                rf_chain::WordKind::GadgetAddr => "gadget_addr",
2530                rf_chain::WordKind::Immediate => "immediate",
2531                rf_chain::WordKind::DataAddr => "data_addr",
2532                rf_chain::WordKind::CodeAddr => "code_addr",
2533                rf_chain::WordKind::Padding => "padding",
2534            }
2535            .to_string(),
2536            comment: w.comment.clone(),
2537            source_gadget: w.source_gadget.map(|i| i as u64),
2538        })
2539        .collect();
2540    ChainResponse {
2541        assumptions: outcome
2542            .assumptions
2543            .as_ref()
2544            .map(|a| schema::ChainAssumptions {
2545                api_name: a.api_name.clone(),
2546                pivot_addr: a.pivot_addr.map(|v| format!("0x{v:x}")),
2547                pivot_words: a.pivot_words as u64,
2548                chain_base_parity: a.chain_base_parity.to_string(),
2549                chain_base_mod16: a.chain_base_mod16,
2550                shellcode_addr: format!("0x{:x}", a.shellcode_addr),
2551                old_protect_addr: a.old_protect_addr.map(|v| format!("0x{v:x}")),
2552            }),
2553        chain: schema::ChainIr {
2554            arch: chain.arch.clone(),
2555            description: chain.description.clone(),
2556            script_comment: chain.script_comment.clone(),
2557            word_size: chain.word_size as u64,
2558            words,
2559            gadgets,
2560        },
2561        python: chain.to_python(),
2562        arch: chain.arch.clone(),
2563        description: chain.description.clone(),
2564        word_count: chain.words.len() as u64,
2565        binary_sha256,
2566        binary_label,
2567        warnings: Vec::new(),
2568    }
2569}
2570
2571/// SHA-256 of a tool's parameters, minus `binary_path` (which is logged in
2572/// its own field). Two identical queries against different binaries share
2573/// a `params_hash`, which is what makes the audit log greppable.
2574fn params_hash<T: serde::Serialize>(q: &T) -> String {
2575    let mut v = serde_json::to_value(q).unwrap_or(Value::Null);
2576    if let Some(o) = v.as_object_mut() {
2577        o.remove("binary_path");
2578    }
2579    sha256_hex(v.to_string().as_bytes())
2580}
2581
2582/// CRIT-03: map rf-cli's three failure kinds onto the closed wire set.
2583///
2584/// `binary_error` becomes `unsupported_binary`; `chain_error` becomes
2585/// `not_found`, because every chain failure the builders produce is "this
2586/// binary does not contain a gadget I need". The precise reason survives in
2587/// the message and in the audit line's `kind`.
2588fn scan_err_to_tool(e: rf_api::ScanError) -> ToolError {
2589    match e {
2590        rf_api::ScanError::Usage(m) => ToolError::new(ErrorCode::UsageError, m),
2591        rf_api::ScanError::Binary(m) => {
2592            ToolError::new(ErrorCode::UnsupportedBinary, m).with_kind("binary_error")
2593        }
2594        rf_api::ScanError::Chain(m) => {
2595            ToolError::with_details(ErrorCode::NotFound, m, json!({"what": "chain_gadget"}))
2596                .with_kind("chain_error")
2597        }
2598    }
2599}
2600
2601/// A `usage_error` for a flag the allowlist refused, tagged `invalid_flag`
2602/// in the audit log so the operator still sees which kind it was.
2603fn usage_flag(message: String) -> ToolError {
2604    ToolError::new(ErrorCode::UsageError, message).with_kind("invalid_flag")
2605}
2606
2607fn tool_error(err: ToolError) -> Result<CallToolResult, McpError> {
2608    let body = err.to_json();
2609    let mut r = CallToolResult::error(vec![ContentBlock::text(body.to_string())]);
2610    r.structured_content = Some(body);
2611    Ok(r)
2612}
2613
2614/// Render a typed response. Serialization of these structs cannot fail —
2615/// they are owned scalars, strings and vectors with no map keys that are
2616/// not strings — but a `Null` body would still be a valid JSON document, so
2617/// the fallback is an `internal` error rather than a silent empty result.
2618fn tool_ok<T: Serialize>(value: &T) -> Result<CallToolResult, McpError> {
2619    let Ok(v) = serde_json::to_value(value) else {
2620        return tool_error(ToolError::new(
2621            ErrorCode::Internal,
2622            "the response could not be serialized",
2623        ));
2624    };
2625    let mut r = CallToolResult::success(vec![ContentBlock::text(v.to_string())]);
2626    r.structured_content = Some(v);
2627    Ok(r)
2628}
2629
2630#[tool_router]
2631impl RopFinderMcp {
2632    /// Find ROP gadgets (return-oriented; ends in ret-like control flow).
2633    #[tool(
2634        description = "Find ROP gadgets in a binary (ret-terminated). Results are RANKED by \
2635        default (order=\"rank\": usability tier, then quality, then fewest instructions, then \
2636        fewest side effects, then address), so the first page is the useful gadgets rather \
2637        than the alphabetical head; order=\"address\"|\"quality\"|\"text\" are also accepted. \
2638        Every record carries a stable id, the classification (class, labels, regs_written, \
2639        regs_read, regs_from_stack, side_effects, terminator, usability) and delay_slot. \
2640        Filter server-side with class/label/writes_reg/reads_reg/preserves_regs/from_stack/\
2641        terminator/max_side_effects/max_insns instead of pulling gadgets into context. Page \
2642        with next_cursor. binary_path must be an absolute path inside one of the server's \
2643        allow_roots (call get_server_config to list them); anything else returns path_denied. \
2644        depth above max_depth is rejected, not clamped. A request that exceeds timeout_secs is \
2645        STOPPED, not orphaned, and notifications/cancelled stops it too.",
2646        output_schema = crate::schema::scan_output_schema()
2647    )]
2648    async fn find_gadgets(
2649        &self,
2650        Parameters(q): Parameters<GadgetQuery>,
2651        ctx: RequestContext<RoleServer>,
2652    ) -> Result<CallToolResult, McpError> {
2653        let (mut rec, t0) = self.begin(&ctx, "find_gadgets", params_hash(&q));
2654        let out = self
2655            .gadget_scan(&ctx, &mut rec, &q, true, false, false)
2656            .await;
2657        self.finish(rec, t0, out).await
2658    }
2659
2660    /// Find JOP gadgets (jump-oriented; ends in jmp/call).
2661    #[tool(
2662        description = "Find JOP gadgets in a binary (jmp/call-terminated). Same parameters, \
2663        ranking, filters, cursor and caps as find_gadgets.",
2664        output_schema = crate::schema::scan_output_schema()
2665    )]
2666    async fn find_jop_gadgets(
2667        &self,
2668        Parameters(q): Parameters<GadgetQuery>,
2669        ctx: RequestContext<RoleServer>,
2670    ) -> Result<CallToolResult, McpError> {
2671        let (mut rec, t0) = self.begin(&ctx, "find_jop_gadgets", params_hash(&q));
2672        let out = self
2673            .gadget_scan(&ctx, &mut rec, &q, false, true, false)
2674            .await;
2675        self.finish(rec, t0, out).await
2676    }
2677
2678    /// Find SYS gadgets (syscall/int/sysenter entry points).
2679    #[tool(
2680        description = "Find SYS gadgets in a binary (syscall/sysenter/int). Same parameters, \
2681        ranking, filters, cursor and caps as find_gadgets.",
2682        output_schema = crate::schema::scan_output_schema()
2683    )]
2684    async fn find_syscall_gadgets(
2685        &self,
2686        Parameters(q): Parameters<GadgetQuery>,
2687        ctx: RequestContext<RoleServer>,
2688    ) -> Result<CallToolResult, McpError> {
2689        let (mut rec, t0) = self.begin(&ctx, "find_syscall_gadgets", params_hash(&q));
2690        let out = self
2691            .gadget_scan(&ctx, &mut rec, &q, false, false, true)
2692            .await;
2693        self.finish(rec, t0, out).await
2694    }
2695
2696    /// ECO-01 / ECO-12 — the constraint search, as one call.
2697    #[tool(
2698        description = "Find gadgets by their EFFECT, not their text: \"set rdi from the stack, \
2699        preserve rsi and rdx, at most one side effect, a clean ret\" is one call. Constraints: \
2700        set_reg (the register is written with a value YOUR PAYLOAD decides — stronger than \
2701        writes_reg, which `xor rdi, rdi` also satisfies), from_stack (that write must come off \
2702        the stack), no_clobber (matched against the classifier's `clobbers`, so `pop rdi` \
2703        survives no_clobber:[\"rdi\"] and `mov rdi, rax` does not), reads_reg, \
2704        max_stack_delta (net rsp movement, terminator included; a gadget whose delta is UNKNOWN \
2705        is rejected, never assumed 0), max_side_effects, max_insns, terminator \
2706        (ret|jmp|call|syscall|none|any, or the finer bare-ret|ret-imm|jmp-reg|jmp-mem|call-reg|call-mem|\
2707        far|other), search (ropper-style wildcards over the instruction sequence, e.g. \
2708        \"pop rdi; ret\"; `?` is one character, `%` any run), pivot (the stack-pivot preset), \
2709        plus class/label/writes_reg/preserves_regs. Scans ROP+JOP+SYS together, so `terminator` \
2710        chooses the family. EVERY result carries an `explanation` object — sets, reads, \
2711        clobbers, stack_delta, terminator and a one-line `why` — so a choice can be justified \
2712        without re-deriving semantics from gadget text. Ranked, paged with next_cursor, and a \
2713        paged result names an NDJSON resource with the whole set.",
2714        output_schema = crate::schema::scan_output_schema()
2715    )]
2716    async fn find_gadgets_by_effect(
2717        &self,
2718        Parameters(q): Parameters<EffectQuery>,
2719        ctx: RequestContext<RoleServer>,
2720    ) -> Result<CallToolResult, McpError> {
2721        let (mut rec, t0) = self.begin(&ctx, "find_gadgets_by_effect", params_hash(&q));
2722        let out = async {
2723            let depth = self.check_depth(q.depth)?;
2724            let req = rf_api::ScanRequest {
2725                depth,
2726                // All three families: the question is about the effect, and
2727                // `terminator` is how a caller narrows it. A `jmp-reg`
2728                // constraint on a ROP-only scan would silently return
2729                // nothing.
2730                rop: true,
2731                jop: true,
2732                sys: true,
2733                multibr: false,
2734                only: None,
2735                filter: None,
2736                range: q.range.clone(),
2737                badbytes: q.badbytes.clone(),
2738                offset: q.offset.clone(),
2739                base: q.base.clone(),
2740                section: split_sections(q.section.as_deref()),
2741                thumb: false,
2742                cfg_aware: false,
2743                align: None,
2744                call_preceded: false,
2745                all: false,
2746                noinstr: false,
2747                arch: q.arch.clone(),
2748                max_gadgets: None,
2749                max_memory: None,
2750                compat: false,
2751            };
2752            let filter = GadgetFilter::parse(&raw_filter!(q))?;
2753            if filter.is_empty() {
2754                return Err(ToolError::with_details(
2755                    ErrorCode::UsageError,
2756                    "find_gadgets_by_effect was given no constraint; it would return the whole \
2757                     scan. Pass at least one of set_reg, from_stack, no_clobber, reads_reg, \
2758                     writes_reg, preserves_regs, max_stack_delta, max_side_effects, max_insns, \
2759                     terminator, search, pivot, class or label — or call find_gadgets if an \
2760                     unfiltered ranked list is what you want",
2761                    json!({"parameter": "set_reg"}),
2762                ));
2763            }
2764            self.run_scan(
2765                &ctx,
2766                &mut rec,
2767                req,
2768                &q.binary_path,
2769                PostOpts {
2770                    order: Order::parse(q.order.as_deref().unwrap_or("rank"))?,
2771                    filter,
2772                    cursor: q.cursor.clone(),
2773                    params_hash: cursor::params_fingerprint(&q),
2774                    max_results: q.max_results,
2775                    timeout_secs: q.timeout_secs,
2776                    ..Default::default()
2777                },
2778            )
2779            .await
2780        }
2781        .await;
2782        self.finish(rec, t0, out).await
2783    }
2784
2785    /// CLI-05 / ECO-02 — strings inside the mapped image.
2786    #[tool(
2787        description = "Find a string in the binary's MAPPED DATA sections — where \"/bin/sh\" \
2788        lives, and at what address. `string` is a BYTE regex (ROPgadget's --string semantics), \
2789        so \"/bin/sh\" is a literal and \"m..n\" matches four bytes. Set memstr:true for \
2790        ROPgadget's --memstr instead: each CHARACTER is located separately and only its first \
2791        occurrence is reported, searching executable sections before data ones, which is how \
2792        you assemble a string the binary does not contain contiguously. Each hit gives vaddr, \
2793        section, length, an escaped preview, the raw hex, and whether the section is writable \
2794        and executable — `writable` is what tells you an address is usable as scratch space. \
2795        SCOPE, and it is enforced rather than promised: only bytes inside sections the loader \
2796        MAPS are ever examined. There is no file-offset mode; headers, symbol and string \
2797        tables and debug data are unreachable because they are in no mapped section, and \
2798        `range` can only narrow the windows. `sections_searched` in the response names exactly \
2799        what was read. Paged with next_cursor; a paged result also names an NDJSON resource.",
2800        output_schema = crate::schema::search_output_schema()
2801    )]
2802    async fn find_string(
2803        &self,
2804        Parameters(q): Parameters<StringQuery>,
2805        ctx: RequestContext<RoleServer>,
2806    ) -> Result<CallToolResult, McpError> {
2807        let (mut rec, t0) = self.begin(&ctx, "find_string", params_hash(&q));
2808        let params_fp = cursor::params_fingerprint(&q);
2809        let mode = if q.memstr.unwrap_or(false) {
2810            find::Mode::MemStr
2811        } else {
2812            find::Mode::String
2813        };
2814        let out = self
2815            .run_find(
2816                &ctx,
2817                &mut rec,
2818                FindRequest {
2819                    binary_path: q.binary_path.clone(),
2820                    mode,
2821                    query: q.string.clone(),
2822                    base: q.base.clone(),
2823                    offset: q.offset.clone(),
2824                    range: q.range.clone(),
2825                    arch: q.arch.clone(),
2826                    max_results: q.max_results,
2827                    cursor: q.cursor.clone(),
2828                    params_hash: params_fp,
2829                    timeout_secs: q.timeout_secs,
2830                },
2831            )
2832            .await;
2833        self.finish(rec, t0, out).await
2834    }
2835
2836    /// CLI-05 / ECO-02 — a byte sequence inside the mapped executable image.
2837    #[tool(
2838        description = "Find a byte sequence in the binary's MAPPED EXECUTABLE regions — the \
2839        same regions find_gadgets walks. `opcode` is hex (\"c9c3\", or \"c9 c3\"), and `??` \
2840        matches any one byte, so \"ff??e0\" finds `jmp rax` through `jmp r15`. A one-nibble \
2841        wildcard is refused rather than silently widened. Each hit gives vaddr, section, \
2842        length, an escaped preview, the raw hex and the section's writable/executable flags. \
2843        SCOPE: only bytes inside mapped executable sections are examined — there is no \
2844        file-offset mode and nothing outside a section is reachable; `sections_searched` names \
2845        exactly what was read, and `range` can only narrow it. Paged with next_cursor; a paged \
2846        result also names an NDJSON resource with the whole match set.",
2847        output_schema = crate::schema::search_output_schema()
2848    )]
2849    async fn find_bytes(
2850        &self,
2851        Parameters(q): Parameters<BytesQuery>,
2852        ctx: RequestContext<RoleServer>,
2853    ) -> Result<CallToolResult, McpError> {
2854        let (mut rec, t0) = self.begin(&ctx, "find_bytes", params_hash(&q));
2855        let params_fp = cursor::params_fingerprint(&q);
2856        let out = self
2857            .run_find(
2858                &ctx,
2859                &mut rec,
2860                FindRequest {
2861                    binary_path: q.binary_path.clone(),
2862                    mode: find::Mode::Opcode,
2863                    query: q.opcode.clone(),
2864                    base: q.base.clone(),
2865                    offset: q.offset.clone(),
2866                    range: q.range.clone(),
2867                    arch: q.arch.clone(),
2868                    max_results: q.max_results,
2869                    cursor: q.cursor.clone(),
2870                    params_hash: params_fp,
2871                    timeout_secs: q.timeout_secs,
2872                },
2873            )
2874            .await;
2875        self.finish(rec, t0, out).await
2876    }
2877
2878    /// ECO-06 — checksec, for an agent.
2879    #[tool(
2880        description = "Report the binary's exploit mitigations, so an agent can decide whether \
2881        ROP is even the right technique before it scans. ELF: nx (PT_GNU_STACK), pie \
2882        (ET_DYN + DF_1_PIE/PT_INTERP/DT_DEBUG, distinguishing a PIE executable from a shared \
2883        object), relro, canary, fortify, rpath, runpath. PE: aslr, dep, high_entropy_va, \
2884        guard_cf and cet_compat as SEPARATE answers read from separate directories (CFG \
2885        validates indirect CALL targets and does NOT check a ret; only cet_compat means a \
2886        shadow stack), safe_seh, force_integrity. Mach-O: pie, nx_stack, nx_heap, \
2887        code_signature, hardened_runtime — per SLICE for a fat container, in `slices`, because \
2888        the slices genuinely disagree. Every entry is {name, enabled, evidence, detail} where \
2889        `enabled` is true, false, or the string \"unknown\" — never false standing in for \
2890        \"could not tell\" — and `evidence` names the header field that decided it, or the \
2891        one whose absence made it unknown. The order is the loader's and is meaningful; `name` \
2892        is the stable key. No scan is performed.",
2893        output_schema = crate::schema::mitigations_output_schema()
2894    )]
2895    async fn get_mitigations(
2896        &self,
2897        Parameters(q): Parameters<MitigationsQuery>,
2898        ctx: RequestContext<RoleServer>,
2899    ) -> Result<CallToolResult, McpError> {
2900        let (mut rec, t0) = self.begin(&ctx, "get_mitigations", params_hash(&q));
2901        let out = self.run_mitigations(&ctx, &mut rec, &q).await;
2902        self.finish(rec, t0, out).await
2903    }
2904
2905    /// Resolve stable gadget ids back to full records.
2906    #[tool(
2907        description = "Resolve stable gadget ids (the `id` field of any gadget record, e.g. \
2908        \"g_ab12cd34ef56gh78\") back to full records, so a plan can name gadgets instead of \
2909        re-sending their text. Rescans the binary at `depth` (default 10) and matches by id; \
2910        an id is independent of every scan parameter except `base`, so pass the same `base` \
2911        the ids came from. Ids that do not resolve are reported in warnings.ids_not_found \
2912        rather than failing the call. Results are returned in the order the ids were given.",
2913        output_schema = crate::schema::scan_output_schema()
2914    )]
2915    async fn get_gadgets(
2916        &self,
2917        Parameters(q): Parameters<IdsQuery>,
2918        ctx: RequestContext<RoleServer>,
2919    ) -> Result<CallToolResult, McpError> {
2920        let (mut rec, t0) = self.begin(&ctx, "get_gadgets", params_hash(&q));
2921        let out = async {
2922            if q.ids.is_empty() {
2923                return Err(ToolError::new(
2924                    ErrorCode::UsageError,
2925                    "ids must not be empty; pass the `id` field of gadgets you already have",
2926                ));
2927            }
2928            let depth = self.check_depth(q.depth)?;
2929            let req = rf_api::ScanRequest {
2930                depth,
2931                rop: true,
2932                jop: true,
2933                sys: true,
2934                multibr: false,
2935                only: None,
2936                filter: None,
2937                range: None,
2938                badbytes: None,
2939                offset: q.offset.clone(),
2940                base: q.base.clone(),
2941                section: split_sections(q.section.as_deref()),
2942                thumb: false,
2943                cfg_aware: false,
2944                align: None,
2945                call_preceded: false,
2946                all: false,
2947                noinstr: false,
2948                arch: q.arch.clone(),
2949                max_gadgets: None,
2950                max_memory: None,
2951                compat: false,
2952            };
2953            self.run_scan(
2954                &ctx,
2955                &mut rec,
2956                req,
2957                &q.binary_path,
2958                PostOpts {
2959                    order: Order::Ids,
2960                    ids: Some(q.ids.clone()),
2961                    params_hash: cursor::params_fingerprint(&q),
2962                    max_results: Some(q.ids.len().clamp(1, HARD_MAX_RESULTS)),
2963                    timeout_secs: q.timeout_secs,
2964                    ..Default::default()
2965                },
2966            )
2967            .await
2968        }
2969        .await;
2970        self.finish(rec, t0, out).await
2971    }
2972
2973    /// Binary metadata without scanning (the CLI's --info payload).
2974    #[tool(
2975        description = "Get binary metadata as JSON: format, arch, endianness, addr_size, \
2976        image_base, entry, sections (name/vaddr/size/executable/writable), PE imports \
2977        (iat_vaddr is the IAT slot the loader patches; hint_name_vaddr is the \
2978        IMAGE_IMPORT_BY_NAME record; an ELF import instead carries addr/got/plt/type/binding, which         is what a ret2plt chain resolves against), the ELF symbol table (`symbols`, OPT-IN: pass max_symbols to get it; symbol_count is always the true total, and null means this format's symbols are not read at all), fat Mach-O slices,         binary_sha256 and warnings. The \
2979        shape is fixed: an ELF reports slices: [] and a fat Mach-O reports sections: []. Exploit \
2980        mitigations are NOT here: call get_mitigations, which types them and keeps the loader's \
2981        order. No scan is performed. Bounded like every other tool: timeout_secs (default 60), \
2982        --max-file-bytes, and max_sections/max_imports (default 4096 each) and max_symbols (default 0, max 4096) — a truncated \
2983        array is announced in warnings, never silently short.",
2984        output_schema = crate::schema::info_output_schema()
2985    )]
2986    async fn get_binary_info(
2987        &self,
2988        Parameters(q): Parameters<InfoQuery>,
2989        ctx: RequestContext<RoleServer>,
2990    ) -> Result<CallToolResult, McpError> {
2991        let (mut rec, t0) = self.begin(&ctx, "get_binary_info", params_hash(&q));
2992        let out = self.run_info(&ctx, &mut rec, &q).await;
2993        self.finish(rec, t0, out).await
2994    }
2995
2996    /// The effective allowlist and caps, so an agent never has to guess.
2997    #[tool(
2998        description = "Report the server's effective configuration: allow_roots (the only \
2999        directories binary_path may name), max_depth, max_file_bytes, max_results, \
3000        max_concurrent, scan_threads, max_gadgets, timeout_secs, cursor_ttl_secs, whether an \
3001        on-disk cache and a workspace directory are enabled, the complete list of `order` \
3002        values, the complete list of error codes, and the server version. Call this first: \
3003        paths outside allow_roots are refused with a single path_denied code that \
3004        deliberately reveals nothing about the target, and a run of refusals is treated as \
3005        filesystem probing.",
3006        output_schema = crate::schema::config_output_schema()
3007    )]
3008    async fn get_server_config(
3009        &self,
3010        ctx: RequestContext<RoleServer>,
3011    ) -> Result<CallToolResult, McpError> {
3012        let (rec, t0) = self.begin(&ctx, "get_server_config", String::new());
3013        let out = Ok(self.config_response());
3014        self.finish(rec, t0, out).await
3015    }
3016
3017    /// MCP-09: the counters an operator needs to see the server's health.
3018    #[tool(
3019        description = "Report this session's counters: requests_total and requests_by_tool, \
3020        ok/denied/timeout/cancelled/error totals, denied_consecutive and probing_suspected \
3021        (a run of path_denied results is the signal that an agent is enumerating the \
3022        filesystem), wedged_total (workers that did not stop within 5 s of being \
3023        cancelled), busy_total, inflight, bytes_read_total, and the cache's \
3024        hit/miss/eviction/tamper counters with its live cache_bytes against \
3025        cache_mem_max_bytes.",
3026        output_schema = crate::schema::stats_output_schema()
3027    )]
3028    async fn get_server_stats(
3029        &self,
3030        ctx: RequestContext<RoleServer>,
3031    ) -> Result<CallToolResult, McpError> {
3032        let (rec, t0) = self.begin(&ctx, "get_server_stats", String::new());
3033        let out = self.stats_response();
3034        self.finish(rec, t0, out).await
3035    }
3036
3037    /// Regex/substring search over the gadget text of a full scan.
3038    #[tool(
3039        description = "Search gadgets by pattern: regex matched against gadget text \
3040        (e.g. \"pop r.*; ret\"); invalid regexes fall back to literal substring match. Runs a \
3041        full ROP+JOP+SYS scan, then filters. Same ranking, semantic filters, cursor and caps \
3042        as find_gadgets.",
3043        output_schema = crate::schema::scan_output_schema()
3044    )]
3045    async fn search_gadgets_by_pattern(
3046        &self,
3047        Parameters(q): Parameters<SearchQuery>,
3048        ctx: RequestContext<RoleServer>,
3049    ) -> Result<CallToolResult, McpError> {
3050        let (mut rec, t0) = self.begin(&ctx, "search_gadgets_by_pattern", params_hash(&q));
3051        let out = async {
3052            let depth = self.check_depth(q.depth)?;
3053            let req = rf_api::ScanRequest {
3054                depth,
3055                rop: true,
3056                jop: true,
3057                sys: true,
3058                multibr: false,
3059                only: None,
3060                filter: None,
3061                range: q.range.clone(),
3062                badbytes: q.badbytes.clone(),
3063                offset: q.offset.clone(),
3064                base: q.base.clone(),
3065                section: split_sections(q.section.as_deref()),
3066                thumb: false,
3067                cfg_aware: false,
3068                align: None,
3069                call_preceded: false,
3070                all: false,
3071                noinstr: false,
3072                arch: q.arch.clone(),
3073                max_gadgets: None,
3074                max_memory: None,
3075                compat: false,
3076            };
3077            self.run_scan(
3078                &ctx,
3079                &mut rec,
3080                req,
3081                &q.binary_path,
3082                PostOpts {
3083                    re: Some(q.pattern.clone()),
3084                    order: Order::parse(q.order.as_deref().unwrap_or("rank"))?,
3085                    filter: GadgetFilter::parse(&raw_filter!(q))?,
3086                    cursor: q.cursor.clone(),
3087                    params_hash: cursor::params_fingerprint(&q),
3088                    max_results: q.max_results,
3089                    timeout_secs: q.timeout_secs,
3090                    ids: None,
3091                },
3092            )
3093            .await
3094        }
3095        .await;
3096        self.finish(rec, t0, out).await
3097    }
3098
3099    /// Build a Linux execve("/bin/sh") ROP chain (ELF x86/x64 only).
3100    #[tool(
3101        description = "Build a ROP chain. target must be \"linux-execve\" (ELF x86/x64 only, \
3102        ported from ROPgadget's ropmaker: x86 int 0x80 / x64 syscall, \"/bin//sh\" written \
3103        to a writable section), \"linux-mprotect\" (the NX answer: page-aligns the region \
3104        and calls mprotect), \"linux-syscall\" (any syscall -- pass `syscall` and \
3105        `syscall_args`), \"linux-ret2libc\" (calls `api_addr` with \"/bin//sh\": SysV arg1 \
3106        in rdi on x64, cdecl stack argument on x86), \"linux-srop\" (x86-64: rt_sigreturn \
3107        plus a sigcontext frame, so only `pop rax` and a trap are needed) or \
3108        \"windows-virtualprotect\". Every one of those has been EXECUTED under the emulator \
3109        harness on a shipped fixture; call plan_chain first to find out whether THIS binary \
3110        can host the one you want. Returns the chain IR as JSON \
3111        (words with kinds gadget_addr / immediate / data_addr / code_addr / padding plus the \
3112        referenced gadget table, each entry carrying the same stable id find_gadgets \
3113        returns), the equivalent python exploit script, arch, description and word_count. A \
3114        binary that lacks a required gadget fails with not_found. Chain builds bypass the \
3115        gadget cache.",
3116        output_schema = crate::schema::chain_output_schema()
3117    )]
3118    async fn build_rop_chain(
3119        &self,
3120        Parameters(q): Parameters<ChainQuery>,
3121        ctx: RequestContext<RoleServer>,
3122    ) -> Result<CallToolResult, McpError> {
3123        let (mut rec, t0) = self.begin(&ctx, "build_rop_chain", params_hash(&q));
3124        let probe = ChainQuery { ..clone_query(&q) };
3125        let out = match self.run_chain(&ctx, &mut rec, q).await {
3126            Ok(v) => Ok(v),
3127            // ECO-04: one contract. A refusal carries the SAME document
3128            // plan_chain returns, in `details.plan`, so a caller never has
3129            // to parse a prose sentence to find out which requirement
3130            // failed or what would fix it. The message is unchanged.
3131            Err(e) if matches!(e.code, ErrorCode::NotFound | ErrorCode::UsageError) => {
3132                let mut probe_rec = rec.clone();
3133                let detail = self.run_plan(&ctx, &mut probe_rec, probe).await.ok();
3134                Err(match detail {
3135                    Some(plan) => {
3136                        // MERGE, never replace: `details.what` /
3137                        // `details.limit` are part of the CRIT-03 error
3138                        // contract and other callers branch on them.
3139                        let mut d = match e.details.clone() {
3140                            Some(Value::Object(m)) => m,
3141                            _ => serde_json::Map::new(),
3142                        };
3143                        d.insert(
3144                            "plan".to_string(),
3145                            serde_json::to_value(&plan).unwrap_or(Value::Null),
3146                        );
3147                        ToolError {
3148                            details: Some(Value::Object(d)),
3149                            ..e
3150                        }
3151                    }
3152                    None => e,
3153                })
3154            }
3155            Err(e) => Err(e),
3156        };
3157        self.finish(rec, t0, out).await
3158    }
3159
3160    /// ECO-04: feasibility, not a chain.
3161    #[tool(
3162        description = "Ask whether this binary can host a ROP chain for `target`, and if not,         exactly why. ALWAYS succeeds: infeasibility is a result. Returns {feasible,         requirements[{id, description, satisfied, strategies_tried[{pattern, candidates}],         relaxations[{param, from, to, would_help}]}], satisfied_requirements[{id, gadget_id,         vaddr}], assumptions{chain_base_parity, write_target, needs_leak}}. Requirement ids         are stable (set_rdx, write_primitive, api_transfer, syscall_trap, stack_align).         `candidates` counts the gadgets the builder could actually USE for that strategy         (clean-tailed, and modelled by the constraint layer), so 0 means the strategy had         nothing to work with, while a non-zero count with satisfied:false means something         else rejected them. `would_help` is         MEASURED, not guessed: the server re-scans at double depth and with multibr and         re-runs the same probe. Every gadget_id resolves through get_gadgets.         build_rop_chain returns this same document in its error details when it refuses.",
3163        output_schema = crate::schema::plan_output_schema()
3164    )]
3165    async fn plan_chain(
3166        &self,
3167        Parameters(q): Parameters<ChainQuery>,
3168        ctx: RequestContext<RoleServer>,
3169    ) -> Result<CallToolResult, McpError> {
3170        let (mut rec, t0) = self.begin(&ctx, "plan_chain", params_hash(&q));
3171        let out = self.run_plan(&ctx, &mut rec, q).await;
3172        self.finish(rec, t0, out).await
3173    }
3174
3175    /// Flag passthrough restricted to the PLAN §6.1 allowlist.
3176    #[tool(
3177        description = "Run a ROPgadget-style scan with explicit flags. args is a list like \
3178        [\"--depth\", \"6\", \"--only\", \"pop|ret\"]. Allowlist: --depth --norop --nojop \
3179        --nosys --only --filter --re --range --section --base --offset --badbytes --align \
3180        --multibr --json --arch --all --callPreceded; anything else (--string, --dump, \
3181        --console, ...) is rejected. --align is ROPgadget's real scan-time alignment \
3182        (decimal, as in ROPgadget's argparse; write 0x.. only if you mean hex), not an \
3183        address post-filter. --arch names a fat Mach-O slice and is REQUIRED for a \
3184        multi-slice binary. The result is ordered, filtered and paged exactly like \
3185        find_gadgets.",
3186        output_schema = crate::schema::scan_output_schema()
3187    )]
3188    async fn run_ropgadget_command(
3189        &self,
3190        Parameters(q): Parameters<RawCommandQuery>,
3191        ctx: RequestContext<RoleServer>,
3192    ) -> Result<CallToolResult, McpError> {
3193        let (mut rec, t0) = self.begin(&ctx, "run_ropgadget_command", params_hash(&q));
3194        let out = async {
3195            let parsed = parse_ropgadget_args(&q.args)?;
3196            // --depth is unbounded in ROPgadget's own CLI, so the
3197            // passthrough is exactly where `--depth 100000` arrived.
3198            self.check_depth(Some(parsed.request.depth))?;
3199            self.run_scan(
3200                &ctx,
3201                &mut rec,
3202                parsed.request,
3203                &q.binary_path,
3204                PostOpts {
3205                    re: parsed.re,
3206                    order: Order::parse(q.order.as_deref().unwrap_or("rank"))?,
3207                    filter: GadgetFilter::parse(&raw_filter!(q))?,
3208                    cursor: q.cursor.clone(),
3209                    params_hash: cursor::params_fingerprint(&q),
3210                    max_results: q.max_results,
3211                    timeout_secs: q.timeout_secs,
3212                    ids: None,
3213                },
3214            )
3215            .await
3216        }
3217        .await;
3218        self.finish(rec, t0, out).await
3219    }
3220}
3221
3222impl RopFinderMcp {
3223    /// The body shared by `find_gadgets` / `find_jop_gadgets` /
3224    /// `find_syscall_gadgets`, which differ only in the anchor family.
3225    async fn gadget_scan(
3226        &self,
3227        ctx: &RequestContext<RoleServer>,
3228        rec: &mut AuditRecord,
3229        q: &GadgetQuery,
3230        rop: bool,
3231        jop: bool,
3232        sys: bool,
3233    ) -> Result<ScanResponse, ToolError> {
3234        let req = self.gadget_request(q, rop, jop, sys)?;
3235        // `sort_by` is the pre-0.3 spelling and accepted only as a fallback
3236        // for `order`, so an agent written against the old surface keeps
3237        // working and one written against the new one is never surprised by
3238        // a stale parameter it did not send.
3239        let order = Order::parse(
3240            q.order
3241                .as_deref()
3242                .or(q.sort_by.as_deref())
3243                .unwrap_or("rank"),
3244        )?;
3245        let filter = GadgetFilter::parse(&raw_filter!(q))?;
3246        self.run_scan(
3247            ctx,
3248            rec,
3249            req,
3250            &q.binary_path,
3251            PostOpts {
3252                order,
3253                filter,
3254                cursor: q.cursor.clone(),
3255                params_hash: cursor::params_fingerprint(q),
3256                max_results: q.max_results,
3257                timeout_secs: q.timeout_secs,
3258                ..Default::default()
3259            },
3260        )
3261        .await
3262    }
3263
3264    /// `get_server_stats`, as the declared type.
3265    fn stats_response(&self) -> Result<schema::StatsResponse, ToolError> {
3266        let v = self.stats.snapshot(self.cache.stats_json());
3267        serde_json::from_value(v).map_err(|e| {
3268            ToolError::new(
3269                ErrorCode::Internal,
3270                format!("the counters do not match the declared schema: {e}"),
3271            )
3272        })
3273    }
3274}
3275
3276// rmcp deprecated the `logging` capability in 2.0 (SEP-2577) while still
3277// implementing it, and it is the only channel that reaches an MCP
3278// operator — stderr, the alternative, is what hosts discard, which is
3279// MCP-09 itself. Scoped to this impl.
3280#[allow(deprecated)]
3281#[tool_handler(name = "rop-finder-mcp", version = "1.0.0")]
3282impl ServerHandler for RopFinderMcp {
3283    /// `instructions` is built at runtime rather than baked into the macro
3284    /// so it can name the *effective* allowlist. An agent that is told the
3285    /// roots has no reason to guess paths, which is what turned the old
3286    /// error taxonomy into a filesystem oracle (MCP-07).
3287    fn get_info(&self) -> rmcp::model::ServerInfo {
3288        rmcp::model::ServerInfo::new(
3289            rmcp::model::ServerCapabilities::builder()
3290                .enable_tools()
3291                // MCP-09: the operator never sees this process's stderr, so
3292                // warnings that matter to them — a tampered cache entry, a
3293                // wedged worker, suspected path probing — are forwarded as
3294                // notifications/message. Declaring the capability is what
3295                // makes a host deliver them.
3296                .enable_logging()
3297                // A paged scan also names an NDJSON resource holding the
3298                // WHOLE ordered set. An agent with its own tools greps one
3299                // file instead of making 41 tool calls.
3300                .enable_resources()
3301                .build(),
3302        )
3303        .with_server_info(rmcp::model::Implementation::new(
3304            "rop-finder-mcp",
3305            env!("CARGO_PKG_VERSION"),
3306        ))
3307        .with_instructions(self.instructions())
3308    }
3309
3310    /// `logging/setLevel`. Declaring the capability without honouring the
3311    /// level would leave a host unable to turn the stream down.
3312    async fn set_level(
3313        &self,
3314        request: rmcp::model::SetLevelRequestParams,
3315        _ctx: RequestContext<RoleServer>,
3316    ) -> Result<(), McpError> {
3317        self.notifier.set_level(request.level);
3318        Ok(())
3319    }
3320
3321    /// The scans currently pinned, each as one NDJSON resource.
3322    ///
3323    /// The list is the pinned-scan store, so it names exactly the results a
3324    /// `resources/read` can still serve. It carries no path and no file
3325    /// content — only the cache key, which the client was already told.
3326    async fn list_resources(
3327        &self,
3328        _request: Option<rmcp::model::PaginatedRequestParams>,
3329        _ctx: RequestContext<RoleServer>,
3330    ) -> Result<rmcp::model::ListResourcesResult, McpError> {
3331        let resources = self
3332            .cache
3333            .pinned_keys()
3334            .into_iter()
3335            .map(|(key, count)| {
3336                // A search key is minted as `s<hex>` by run_find; a scan key
3337                // is `rf_cache::make_key`'s `v<n>-<hex>--<hex>`. The two
3338                // namespaces are disjoint by construction, and each URI form
3339                // is parsed only by its own reader.
3340                if key.starts_with('s') && !key.contains("--") {
3341                    rmcp::model::Resource::new(resources::search_uri(&key), format!("search {key}"))
3342                        .with_mime_type(resources::NDJSON_MIME)
3343                        .with_description(format!(
3344                            "{count} search hits, one JSON object per line, in address order"
3345                        ))
3346                } else {
3347                    rmcp::model::Resource::new(resources::scan_uri(&key), format!("scan {key}"))
3348                        .with_mime_type(resources::NDJSON_MIME)
3349                        .with_description(format!(
3350                            "{count} gadget records, one JSON object per line, in rank order"
3351                        ))
3352                }
3353            })
3354            .collect();
3355        Ok(rmcp::model::ListResourcesResult::with_all_items(resources))
3356    }
3357
3358    /// Serve `ropfinder://scan/<cache_key>/gadgets.ndjson`.
3359    ///
3360    /// The URI is parsed into a cache key by [`resources::cache_key_of`],
3361    /// which accepts only `[A-Za-z0-9-]`, and the key is looked up in the
3362    /// pinned store — it is never joined to a path here, and there is no
3363    /// path in a URI to begin with. A key that is not pinned is
3364    /// `resource_not_found`, never a rescan: reading a resource must not be
3365    /// a way to make the server do unbounded work outside the guard.
3366    async fn read_resource(
3367        &self,
3368        request: rmcp::model::ReadResourceRequestParams,
3369        _ctx: RequestContext<RoleServer>,
3370    ) -> Result<rmcp::model::ReadResourceResponse, McpError> {
3371        let uri = request.uri.clone();
3372        // ECO-09: two namespaces, each parsed by its own reader, so a scan
3373        // key can never be served as a search body or the reverse.
3374        let text = if let Some(key) = resources::search_key_of(&uri) {
3375            let Some(body) = self.cache.pinned_text(key) else {
3376                return Err(McpError::resource_not_found(
3377                    "that search is no longer held; re-run it to get a fresh resource_uri",
3378                    Some(json!({"uri": uri, "cursor_ttl_secs": self.config.cursor_ttl.as_secs()})),
3379                ));
3380            };
3381            body.to_string()
3382        } else {
3383            let Some(key) = resources::cache_key_of(&uri) else {
3384                return Err(McpError::resource_not_found(
3385                    "not a rop-finder resource; the forms are \
3386                     ropfinder://scan/<cache_key>/gadgets.ndjson and \
3387                     ropfinder://search/<key>/hits.ndjson",
3388                    Some(json!({"uri": uri})),
3389                ));
3390            };
3391            let Some(p) = self.cache.pinned(key) else {
3392                return Err(McpError::resource_not_found(
3393                    "that scan is no longer held; re-run the scan to get a fresh resource_uri",
3394                    Some(json!({"uri": uri, "cursor_ttl_secs": self.config.cursor_ttl.as_secs()})),
3395                ));
3396            };
3397            resources::render_ndjson(&p.scan, &p.sems)
3398        };
3399        Ok(rmcp::model::ReadResourceResult::new(vec![
3400            rmcp::model::ResourceContents::TextResourceContents {
3401                uri,
3402                mime_type: Some(resources::NDJSON_MIME.to_string()),
3403                text,
3404                meta: None,
3405            },
3406        ])
3407        .into())
3408    }
3409}
3410
3411impl RopFinderMcp {
3412    /// The initialize-time `instructions` string, including the effective
3413    /// allowlist and caps.
3414    pub fn instructions(&self) -> String {
3415        let roots = self.root_paths();
3416        let allowed = if roots.is_empty() {
3417            "(none — every binary_path will be refused)".to_string()
3418        } else {
3419            roots.join(", ")
3420        };
3421        format!(
3422            "ROP/JOP/SYS gadget search via rop-finder, plus Linux execve ROP chain \
3423             generation (build_rop_chain, ELF x86/x64).\n\
3424             binary_path MUST be an absolute path inside one of these directories: {allowed}. \
3425             Anything else — including a path that merely starts with one of those strings, a \
3426             relative path, or one containing \"..\" — is refused with a single `path_denied` \
3427             code that deliberately reveals nothing about the target, so probing for files is \
3428             pointless. Call get_server_config for the machine-readable allowlist and caps.\n\
3429             Caps: depth <= {} (larger values are REJECTED, not clamped), binaries <= {} bytes, \
3430             max_results default {} (hard max {}), {} scan(s) at a time, default timeout {} s.\n\
3431             Gadget results are RANKED by default (order=\"rank\"), carry a stable `id` you can \
3432             pass back to get_gadgets, and are paged with `next_cursor`. Prefer the server-side \
3433             filters — class, label, writes_reg, reads_reg, preserves_regs, from_stack, \
3434             terminator, max_side_effects, max_insns, and v0.4's set_reg, no_clobber, \
3435             max_stack_delta, pivot and search — over reading gadgets to filter them \
3436             yourself. find_gadgets_by_effect takes all of them at once and returns an \
3437             `explanation` with every gadget. find_string and find_bytes locate strings and \
3438             byte sequences, and read ONLY bytes inside MAPPED sections — never a file offset. \
3439             get_mitigations is checksec: nx/pie/relro/canary or aslr/dep/guard_cf/cet_compat, \
3440             each with its evidence, and \"unknown\" where the file does not say. A paged scan \
3441             or search also names an NDJSON resource holding the whole set.\n\
3442             Every tool declares an outputSchema; every response has a FIXED field set, with \
3443             null rather than a missing key. Errors are {{error: {{code, message, retryable, \
3444             details, suggestion}}}} and `code` is one of: {}.",
3445            self.config.max_depth,
3446            self.config.max_file_bytes,
3447            self.config.max_results,
3448            HARD_MAX_RESULTS,
3449            self.config.max_concurrent,
3450            self.config.timeout.as_secs(),
3451            ErrorCode::all()
3452                .iter()
3453                .map(|c| c.as_str())
3454                .collect::<Vec<_>>()
3455                .join(", "),
3456        )
3457    }
3458}
3459
3460#[cfg(test)]
3461mod tests {
3462
3463    // Panicking on a bad index is the desired behaviour in a test; the
3464    // crate-level deny exists to keep it out of the server.
3465    #![allow(clippy::indexing_slicing)]
3466
3467    use super::*;
3468
3469    /// The `#[tool_handler]` attribute takes a string literal — it cannot call
3470    /// `env!()` — so the version there can silently drift from the crate's. It did:
3471    /// the handshake reported 0.1.0 while `--version` said 1.0.0, which is what an
3472    /// MCP host displays to the operator. `with_server_info` now uses
3473    /// `env!("CARGO_PKG_VERSION")`; this makes the literal drifting a build failure.
3474    #[test]
3475    fn tool_handler_version_literal_matches_the_crate_version() {
3476        assert_eq!(
3477            "1.0.0",
3478            env!("CARGO_PKG_VERSION"),
3479            "bump the version literal in #[tool_handler(...)] to match Cargo.toml"
3480        );
3481    }
3482
3483    /// Unique temp dir per test, cleaned up on drop.
3484    struct TempDir(PathBuf);
3485    impl TempDir {
3486        fn new(tag: &str) -> Self {
3487            let raw =
3488                std::env::temp_dir().join(format!("rf-mcp-test-{}-{}", tag, std::process::id()));
3489            let _ = std::fs::remove_dir_all(&raw);
3490            std::fs::create_dir_all(&raw).unwrap();
3491            TempDir(raw.canonicalize().unwrap())
3492        }
3493        fn canon(&self) -> &PathBuf {
3494            &self.0
3495        }
3496    }
3497    impl Drop for TempDir {
3498        fn drop(&mut self) {
3499            let _ = std::fs::remove_dir_all(&self.0);
3500        }
3501    }
3502
3503    fn args(v: &[&str]) -> Vec<String> {
3504        v.iter().map(|s| s.to_string()).collect()
3505    }
3506
3507    // -----------------------------------------------------------------
3508    // ANCH-02 - --align is an engine option, parsed as DECIMAL
3509    // -----------------------------------------------------------------
3510
3511    /// ROPgadget's `--align` is argparse `type=int`. rf-mcp parsed it with
3512    /// `rf_api::parse_hex`, which always parses base 16, so `--align 16`
3513    /// meant 0x16 = 22 and `--align 10` meant 16. Decimal first; hex only
3514    /// with an explicit `0x`.
3515    #[test]
3516    fn align_is_parsed_as_decimal_first_hex_only_with_a_prefix() {
3517        assert_eq!(parse_align("16").unwrap(), 16);
3518        assert_eq!(parse_align("0x10").unwrap(), 16);
3519        assert_eq!(parse_align("0X10").unwrap(), 16);
3520        assert_eq!(parse_align(" 4 ").unwrap(), 4);
3521        assert_eq!(parse_align("10").unwrap(), 10);
3522        assert_eq!(parse_align("0").unwrap(), 0);
3523        for bad in ["", "0x", "-4", "abcd", "0xzz", "4.5"] {
3524            assert!(parse_align(bad).is_err(), "{bad:?} must not parse");
3525        }
3526        // The old behaviour, spelled out so a regression is unmistakable:
3527        // parse_hex("16") is 22, and that is what this test forbids.
3528        assert_eq!(rf_api::parse_hex("16", "x").unwrap(), 22);
3529        assert_ne!(parse_align("16").unwrap() as u64, 22);
3530    }
3531
3532    /// The parsed value reaches `ScanRequest::align`, i.e. the ENGINE's
3533    /// alignment stepping, and no post-filter survives to re-implement it.
3534    /// Post-filtering an align=1 depth-10 scan can only ever expose gadgets
3535    /// reaching 9 bytes back, which is why it under-reported by ~53%.
3536    #[test]
3537    fn align_reaches_the_engine_not_a_post_filter() {
3538        let p = parse_ropgadget_args(&args(&["--align", "16"])).unwrap();
3539        assert_eq!(p.request.align, Some(16));
3540        let p = parse_ropgadget_args(&args(&["--align=4"])).unwrap();
3541        assert_eq!(p.request.align, Some(4));
3542        // A bad value is a usage error, not a silent 0.
3543        let e = parse_ropgadget_args(&args(&["--align", "nope"])).unwrap_err();
3544        assert_eq!(e.code, ErrorCode::UsageError);
3545    }
3546
3547    /// CORE-03 mirrored onto the MCP surface: `--arch` selects a fat
3548    /// Mach-O slice, and the new engine switches are reachable.
3549    #[test]
3550    fn arch_all_and_call_preceded_are_allowlisted_and_plumbed() {
3551        let p =
3552            parse_ropgadget_args(&args(&["--arch", "arm64", "--all", "--callPreceded"])).unwrap();
3553        assert_eq!(p.request.arch.as_deref(), Some("arm64"));
3554        assert!(p.request.all);
3555        assert!(p.request.call_preceded);
3556        // The MCP server never opts into ROPgadget's fat-Mach-O
3557        // concatenation: an agent cannot see that the output is fabricated.
3558        assert!(!p.request.compat);
3559    }
3560
3561    /// MCP-02: the default configuration allows NOTHING. Seeding the
3562    /// allowlist with the process cwd is what made `--allow-dir` unable to
3563    /// narrow anything; a default of "nothing" fails closed instead.
3564    #[test]
3565    fn default_config_allows_nothing() {
3566        let c = ServerConfig::default();
3567        assert!(c.allow_dirs.is_empty());
3568        assert_eq!(c.max_depth, DEFAULT_MAX_DEPTH);
3569        assert_eq!(c.max_concurrent, DEFAULT_MAX_CONCURRENT);
3570        assert_eq!(c.max_file_bytes, DEFAULT_MAX_FILE_BYTES);
3571        assert!(!c.verbose_path_errors);
3572
3573        let server = RopFinderMcp::new(c).unwrap();
3574        assert!(server.root_paths().is_empty());
3575        // Every path is refused, with the one code and no OS text.
3576        let err = server.open_confined("/etc/shadow").unwrap_err();
3577        assert_eq!(err.code, ErrorCode::PathDenied);
3578        assert!(!err.message.contains("os error"), "{err:?}");
3579    }
3580
3581    /// MCP-03 interim: an over-large depth is REJECTED, not clamped, so an
3582    /// agent cannot mistake a depth-64 result for a depth-100000 one.
3583    #[test]
3584    fn depth_over_max_is_rejected_not_clamped() {
3585        let server = RopFinderMcp::new(ServerConfig::default()).unwrap();
3586        assert_eq!(server.check_depth(None).unwrap(), 10);
3587        assert_eq!(server.check_depth(Some(64)).unwrap(), 64);
3588        let err = server.check_depth(Some(100_000)).unwrap_err();
3589        assert_eq!(err.code, ErrorCode::UsageError);
3590        let d = err.details.expect("structured details");
3591        assert_eq!(d["limit"], "max_depth");
3592        assert_eq!(d["limit_value"], 64);
3593        assert_eq!(d["got"], 100_000);
3594        // usize::MAX, the value the audit actually sent, is rejected too.
3595        assert_eq!(
3596            server.check_depth(Some(usize::MAX)).unwrap_err().code,
3597            ErrorCode::UsageError
3598        );
3599    }
3600
3601    /// Duplicate `--allow-dir` entries naming the same directory collapse
3602    /// to one root, so the published allowlist is not misleading.
3603    #[test]
3604    fn duplicate_roots_collapse() {
3605        let t = TempDir::new("dup-roots");
3606        let c = ServerConfig {
3607            allow_dirs: vec![t.canon().clone(), t.canon().clone()],
3608            ..Default::default()
3609        };
3610        let server = RopFinderMcp::new(c).unwrap();
3611        assert_eq!(server.root_paths().len(), 1);
3612    }
3613
3614    /// The allowlist and the caps are published, so a legitimate agent
3615    /// never has to guess a path (MCP-07's pressure valve).
3616    #[test]
3617    fn server_config_and_instructions_publish_the_allowlist() {
3618        let t = TempDir::new("publish");
3619        let c = ServerConfig {
3620            allow_dirs: vec![t.canon().clone()],
3621            ..Default::default()
3622        };
3623        let server = RopFinderMcp::new(c).unwrap();
3624        let cfg = serde_json::to_value(server.config_response()).unwrap();
3625        for key in [
3626            "allow_roots",
3627            "max_depth",
3628            "max_file_bytes",
3629            "max_results",
3630            "max_concurrent",
3631            "cache",
3632            "cursor_ttl_secs",
3633            "orders",
3634            "error_codes",
3635            "version",
3636        ] {
3637            assert!(cfg.get(key).is_some(), "missing {key} in {cfg}");
3638        }
3639        assert_eq!(cfg["allow_roots"].as_array().unwrap().len(), 1);
3640        assert_eq!(cfg["cache"], false);
3641        // CRIT-03: the two taxonomies are PUBLISHED, so an agent never has
3642        // to discover them by provoking failures.
3643        assert_eq!(cfg["orders"], json!(["rank", "address", "quality", "text"]));
3644        assert_eq!(cfg["error_codes"].as_array().unwrap().len(), 9);
3645        let root = server.root_paths()[0].clone();
3646        assert!(server.instructions().contains(&root));
3647        assert!(server.instructions().contains("get_server_config"));
3648        assert!(server.instructions().contains("cursor_expired"));
3649    }
3650
3651    #[test]
3652    fn allowlist_accepts_documented_flags() {
3653        let p = parse_ropgadget_args(&args(&[
3654            "--depth",
3655            "6",
3656            "--norop",
3657            "--nojop",
3658            "--nosys",
3659            "--multibr",
3660            "--json",
3661            "--only",
3662            "pop|ret",
3663            "--filter",
3664            "leave",
3665            "--re",
3666            "pop.*ret",
3667            "--range",
3668            "0x1000-0x2000",
3669            "--section",
3670            ".text,.plt",
3671            "--base",
3672            "0x400000",
3673            "--offset",
3674            "0x1000",
3675            "--badbytes",
3676            "0a|0d",
3677            "--align",
3678            "0x10",
3679        ]))
3680        .unwrap();
3681        assert_eq!(p.request.depth, 6);
3682        assert!(!p.request.rop && !p.request.jop && !p.request.sys && p.request.multibr);
3683        assert_eq!(p.request.only.as_deref(), Some("pop|ret"));
3684        assert_eq!(p.request.filter.as_deref(), Some("leave"));
3685        assert_eq!(p.request.range.as_deref(), Some("0x1000-0x2000"));
3686        assert_eq!(p.request.section, vec![".text", ".plt"]);
3687        assert_eq!(p.request.base.as_deref(), Some("0x400000"));
3688        assert_eq!(p.request.offset.as_deref(), Some("0x1000"));
3689        assert_eq!(p.request.badbytes.as_deref(), Some("0a|0d"));
3690        assert_eq!(p.re.as_deref(), Some("pop.*ret"));
3691        // ANCH-02: --align is an ENGINE option now, and an explicit 0x
3692        // prefix still means hexadecimal.
3693        assert_eq!(p.request.align, Some(16));
3694        // --flag=value form also works
3695        let p = parse_ropgadget_args(&args(&["--depth=8"])).unwrap();
3696        assert_eq!(p.request.depth, 8);
3697    }
3698
3699    #[test]
3700    fn allowlist_rejects_side_channel_and_unknown_flags() {
3701        for bad in ["--string", "--dump", "--console", "--memstr", "--unknown"] {
3702            let err = parse_ropgadget_args(&args(&[bad])).unwrap_err();
3703            assert_eq!(err.code, ErrorCode::UsageError, "{bad}");
3704            assert_eq!(err.kind, "invalid_flag", "{bad}");
3705            assert!(err.message.contains("--depth"), "lists allowlist: {err:?}");
3706        }
3707        // even with a value
3708        let err = parse_ropgadget_args(&args(&["--string", "password"])).unwrap_err();
3709        assert_eq!(err.kind, "invalid_flag");
3710        // positional argument
3711        let err = parse_ropgadget_args(&args(&["/etc/passwd"])).unwrap_err();
3712        assert_eq!(err.kind, "invalid_flag");
3713        // missing value
3714        let err = parse_ropgadget_args(&args(&["--depth"])).unwrap_err();
3715        assert_eq!(err.kind, "invalid_flag");
3716        // boolean flag with value
3717        let err = parse_ropgadget_args(&args(&["--norop=1"])).unwrap_err();
3718        assert_eq!(err.kind, "invalid_flag");
3719        // bad depth value
3720        let err = parse_ropgadget_args(&args(&["--depth", "x"])).unwrap_err();
3721        assert_eq!(err.code, ErrorCode::UsageError);
3722    }
3723
3724    #[test]
3725    fn caps_are_clamped() {
3726        assert_eq!(clamp_max_results(None, 1000), 1000);
3727        assert_eq!(clamp_max_results(Some(5), 1000), 5);
3728        assert_eq!(clamp_max_results(Some(999_999), 1000), HARD_MAX_RESULTS);
3729        assert_eq!(clamp_max_results(Some(0), 1000), 1);
3730        assert_eq!(
3731            clamp_timeout(Some(999_999), Duration::from_secs(60)),
3732            Duration::from_secs(HARD_MAX_TIMEOUT_SECS)
3733        );
3734        assert_eq!(
3735            clamp_timeout(None, Duration::from_secs(60)),
3736            Duration::from_secs(60)
3737        );
3738    }
3739
3740    /// The default order is `rank`, and it is the tier — not R12's quality
3741    /// score — that puts a usable gadget first. `sort_by: "quality"` used to
3742    /// be the only ordering, and its top of the list was `ret`,
3743    /// `add esp, 0x8 ; ret`, `retf 0x2bbc`.
3744    #[test]
3745    fn rank_beats_quality_at_putting_a_usable_gadget_first() {
3746        let mk = |vaddr: &str, bytes: &str, text: &str| CachedGadget {
3747            vaddr: vaddr.into(),
3748            bytes: bytes.into(),
3749            text: text.into(),
3750            ..CachedGadget::default()
3751        };
3752        let scan = CachedScan {
3753            gadgets: vec![
3754                mk(
3755                    "0x1000",
3756                    "504801d859c3",
3757                    "push rax ; add rax, rbx ; pop rcx ; ret",
3758                ),
3759                mk("0x2000", "58c3", "pop rax ; ret"),
3760                mk("0x3000", "c3", "ret"),
3761                mk("0x0500", "5fc3", "pop rdi ; ret"),
3762                mk("0x4000", "cabc2b", "retf 0x2bbc"),
3763            ],
3764            ..CachedScan::default()
3765        };
3766        let sems = semantics::classify_scan(&scan, "00", 0, Some(rf_core::Arch::X64));
3767        let order_of = |o: Order| {
3768            let mut idx: Vec<usize> = (0..scan.gadgets.len()).collect();
3769            semantics::sort_indices(&mut idx, o, &scan, &sems);
3770            idx.iter()
3771                .map(|&i| scan.gadgets[i].vaddr.as_str())
3772                .collect::<Vec<_>>()
3773        };
3774        // Rank: the two stack loads first (tier 3, lower vaddr wins the
3775        // tie), then the multi-effect gadget (tier 2), then `retf 0x2bbc`
3776        // — CLS-13 makes its immediate a stack adjustment, so it has one
3777        // side effect and a non-bare terminator: tier 1 — and last the
3778        // bare `ret`, which does nothing at all (tier 0).
3779        assert_eq!(
3780            order_of(Order::Rank),
3781            ["0x0500", "0x2000", "0x1000", "0x4000", "0x3000"]
3782        );
3783        // Address and text are total and independent of it.
3784        assert_eq!(
3785            order_of(Order::Address),
3786            ["0x0500", "0x1000", "0x2000", "0x3000", "0x4000"]
3787        );
3788        // Quality alone cannot separate `ret` from `pop rdi ; ret` well
3789        // enough to be a default: a bare `ret` outranks the multi-effect
3790        // gadget on it, which is why the tier exists.
3791        let q = order_of(Order::Quality);
3792        assert_eq!(q[0], "0x0500", "{q:?}");
3793        assert!(
3794            q.iter().position(|v| *v == "0x3000").unwrap()
3795                < q.iter().position(|v| *v == "0x1000").unwrap(),
3796            "{q:?}"
3797        );
3798    }
3799
3800    fn one_ret() -> CachedScan {
3801        CachedScan {
3802            gadgets: vec![CachedGadget {
3803                vaddr: "0x1".into(),
3804                bytes: "c3".into(),
3805                text: "ret".into(),
3806                ..CachedGadget::default()
3807            }],
3808            ..CachedScan::default()
3809        }
3810    }
3811
3812    #[test]
3813    fn cache_roundtrip_mem_and_disk() {
3814        let t = TempDir::new("cache");
3815        let cache = Cache::new(
3816            Some(t.canon().clone()),
3817            rf_cache::MemLimits::default(),
3818            DEFAULT_CURSOR_TTL,
3819        );
3820        cache.put("k1", one_ret());
3821        assert_eq!(cache.get("k1").unwrap().gadgets.len(), 1);
3822        // persisted to disk, authenticated
3823        assert!(t.canon().join("k1.rfc").is_file());
3824        // a fresh cache over the same dir reads the disk entry
3825        let cold = Cache::new(
3826            Some(t.canon().clone()),
3827            rf_cache::MemLimits::default(),
3828            DEFAULT_CURSOR_TTL,
3829        );
3830        assert!(cold.get("k1").is_some());
3831        assert!(cold.get("absent").is_none());
3832        assert_eq!(cold.disk_stats().unwrap().tampered, 0);
3833    }
3834
3835    /// MCP-04. The audit served a fabricated
3836    /// `pop rdi ; ret @ 0xdeadbeefcafe0000` through the live server by
3837    /// writing one 0644 JSON file. Now: a miss, a counter, no result.
3838    #[test]
3839    fn a_poisoned_disk_entry_is_a_miss_not_a_result() {
3840        let t = TempDir::new("poison");
3841        {
3842            let cache = Cache::new(
3843                Some(t.canon().clone()),
3844                rf_cache::MemLimits::default(),
3845                DEFAULT_CURSOR_TTL,
3846            );
3847            cache.put("k1", one_ret());
3848        }
3849        let fabricated = br#"{"version":2,"gadgets":[{"vaddr":"0xdeadbeefcafe0000","bytes":"5fc3","text":"pop rdi ; ret"}],"fallback_names":false}"#;
3850        // Bare JSON, the shape the pre-v0.2 cache accepted...
3851        std::fs::write(t.canon().join("k1.rfc"), fabricated).unwrap();
3852        let cache = Cache::new(
3853            Some(t.canon().clone()),
3854            rf_cache::MemLimits::default(),
3855            DEFAULT_CURSOR_TTL,
3856        );
3857        assert!(cache.get("k1").is_none());
3858        assert_eq!(cache.disk_stats().unwrap().tampered, 1);
3859
3860        // ...and framed with a wrong tag, so only the HMAC rejects it.
3861        let mut framed = Vec::from(b"RFCACHE\x02".as_slice());
3862        framed.extend_from_slice(&[0u8; 32]);
3863        framed.extend_from_slice(fabricated);
3864        std::fs::write(t.canon().join("k1.rfc"), &framed).unwrap();
3865        let cache = Cache::new(
3866            Some(t.canon().clone()),
3867            rf_cache::MemLimits::default(),
3868            DEFAULT_CURSOR_TTL,
3869        );
3870        assert!(cache.get("k1").is_none());
3871        assert_eq!(cache.disk_stats().unwrap().tampered, 1);
3872    }
3873
3874    /// ROB-04 as it reached this crate: `"€€"` in a cached `bytes` field
3875    /// panicked the server at `gadget_from_cached`. It is a miss now, and
3876    /// the reclassification path that used it cannot panic either.
3877    #[test]
3878    fn a_non_ascii_bytes_field_never_panics() {
3879        let t = TempDir::new("charboundary");
3880        {
3881            let cache = Cache::new(
3882                Some(t.canon().clone()),
3883                rf_cache::MemLimits::default(),
3884                DEFAULT_CURSOR_TTL,
3885            );
3886            cache.put("k1", one_ret());
3887        }
3888        let key = std::fs::read(t.canon().join(".cachekey")).unwrap();
3889        let body = r#"{"version":2,"gadgets":[{"vaddr":"0x1","bytes":"€€","text":"ret"}],"fallback_names":false}"#;
3890        let mut msg = Vec::from(b"k1\0".as_slice());
3891        msg.extend_from_slice(body.as_bytes());
3892        let mut framed = Vec::from(b"RFCACHE\x02".as_slice());
3893        framed.extend_from_slice(&rf_cache::hmac_sha256(&key, &msg));
3894        framed.extend_from_slice(body.as_bytes());
3895        std::fs::write(t.canon().join("k1.rfc"), &framed).unwrap();
3896
3897        let cache = Cache::new(
3898            Some(t.canon().clone()),
3899            rf_cache::MemLimits::default(),
3900            DEFAULT_CURSOR_TTL,
3901        );
3902        assert!(cache.get("k1").is_none(), "authenticated but unusable");
3903        assert_eq!(cache.disk_stats().unwrap().malformed, 1);
3904        assert_eq!(cache.disk_stats().unwrap().tampered, 0);
3905
3906        // The same value straight through the reclassification path.
3907        let g = CachedGadget {
3908            vaddr: "0x1".into(),
3909            bytes: "€€".into(),
3910            text: "ret".into(),
3911            ..CachedGadget::default()
3912        };
3913        assert!(g.to_scan_gadget().is_none());
3914        // ...and straight through the classification path, which is where
3915        // the reconstruction now happens: an id, no class, sorts last.
3916        let poisoned = CachedScan {
3917            gadgets: vec![g],
3918            ..CachedScan::default()
3919        };
3920        let sems = semantics::classify_scan(&poisoned, "00", 0, Some(rf_core::Arch::X64));
3921        assert_eq!(sems.len(), 1);
3922        assert!(sems[0].class.is_none());
3923        assert!(sems[0].id.starts_with("g_"));
3924    }
3925}