use std::path::Path;
use std::sync::{Arc, Mutex, MutexGuard};
use rmcp::ErrorData;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::{ServerHandler, tool, tool_handler, tool_router};
use crate::{FunctionFilter, Project, parse_addr, parse_xref_kind};
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct RawParams {
pub arch: Option<String>,
pub base: Option<String>,
pub entry: Option<String>,
}
fn open(
binary: &str,
db: Option<&str>,
raw: Option<&RawParams>,
fat_arch: Option<&str>,
) -> Result<Project, ErrorData> {
let raw_opts = raw_options(raw)?;
let db_path;
let db_ref = match db {
Some(d) => {
db_path = Path::new(d).to_path_buf();
Some(db_path.as_path())
}
None => None,
};
crate::open_mapped(Path::new(binary), db_ref, raw_opts, fat_arch).map_err(|e| match e {
crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
other => ErrorData::internal_error(other.to_string(), None),
})
}
fn raw_options(raw: Option<&RawParams>) -> Result<Option<crate::loader::RawOptions>, ErrorData> {
let (present, arch, base, entry) = match raw {
None => (false, None, None, None),
Some(r) => (
true,
r.arch.as_deref(),
r.base.as_deref(),
r.entry.as_deref(),
),
};
crate::parse_raw_options(present, arch, base, entry).map_err(|e| match e {
crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
other => ErrorData::internal_error(other.to_string(), None),
})
}
fn ok(value: serde_json::Value) -> Result<String, ErrorData> {
serde_json::to_string(&value)
.map_err(|e| ErrorData::internal_error(format!("serialize result: {e}"), None))
}
fn opt_addr(s: Option<String>) -> Result<Option<u64>, ErrorData> {
s.map(|v| parse_addr(&v))
.transpose()
.map_err(|e| ErrorData::invalid_params(e.to_string(), None))
}
fn all_params<T>(p: Parameters<T>) -> T {
p.0
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct BinaryParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct StringsParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub start: Option<usize>,
pub offset: Option<usize>,
pub limit: Option<usize>,
pub pattern: Option<String>,
pub min_len: Option<usize>,
pub section: Option<String>,
pub include_code: Option<bool>,
pub decode: Option<String>,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct FunctionsParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub query: Option<String>,
pub caller: Option<String>,
pub callee: Option<String>,
pub range_lo: Option<String>,
pub range_hi: Option<String>,
pub offset: Option<usize>,
pub limit: Option<usize>,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct AddrParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub addr: String,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct BlocksParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub addr: String,
pub offset: Option<usize>,
pub limit: Option<usize>,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct BlockInsnsParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub addr: String,
pub block: String,
pub offset: Option<usize>,
pub limit: Option<usize>,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct DiagnosticsParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub kind: Option<String>,
pub func: Option<String>,
pub offset: Option<usize>,
pub limit: Option<usize>,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct RangeParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub addr: String,
pub len: usize,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct XrefsParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub to: Option<String>,
pub from: Option<String>,
pub kind: Option<String>,
pub offset: Option<usize>,
pub limit: Option<usize>,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct IrCoverageParams {
pub arch: String,
pub binary: Option<String>,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub addr: Option<String>,
pub len: Option<usize>,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct RenameParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub addr: String,
pub name: String,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct CommentParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub addr: String,
pub comment: String,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct SearchBytesParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub pattern: String,
pub section: Option<String>,
pub range_start: Option<String>,
pub range_end: Option<String>,
pub offset: Option<usize>,
pub limit: Option<usize>,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct CallgraphParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub addr: String,
pub depth: Option<usize>,
pub offset: Option<usize>,
pub limit: Option<usize>,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct SliceParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub addr: String,
pub depth: Option<usize>,
pub offset: Option<usize>,
pub limit: Option<usize>,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct AnnotationsImportParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub document: String,
pub overwrite: Option<bool>,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct FlirtHintsParams {
pub binary: String,
pub db: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
pub addr: Option<String>,
pub offset: Option<usize>,
pub limit: Option<usize>,
}
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct DiffParams {
pub binary_a: String,
pub binary_b: String,
pub db_a: Option<String>,
pub db_b: Option<String>,
pub raw: Option<RawParams>,
pub fat_arch: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct BinscoutMcp {
lock: Arc<Mutex<()>>,
}
impl BinscoutMcp {
#[must_use]
pub fn new() -> Self {
Self::default()
}
fn guard(&self) -> MutexGuard<'_, ()> {
self.lock.lock().unwrap_or_else(|e| e.into_inner())
}
}
#[tool_handler(
name = "binscout-mcp",
instructions = "Headless agent-first binary analysis. Every tool takes a binary path and returns one JSON document as text."
)]
impl ServerHandler for BinscoutMcp {}
#[tool_router]
impl BinscoutMcp {
#[tool(
name = "project_info",
description = "Open a binary and report arch, format, entry, and analysis counts"
)]
fn project_info(&self, p: Parameters<BinaryParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
ok(serde_json::to_value(proj.project_info()).expect("project_info serializes"))
}
#[tool(
name = "functions",
description = "List functions with rename-resolved names, filtered by query/caller/callee/range, paged by offset/limit"
)]
fn functions(&self, p: Parameters<FunctionsParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let filter = FunctionFilter {
query: p.query,
caller: opt_addr(p.caller)?,
callee: opt_addr(p.callee)?,
range: match (p.range_lo, p.range_hi) {
(None, None) => None,
(Some(lo), Some(hi)) => Some((
parse_addr(&lo).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?,
parse_addr(&hi).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?,
)),
_ => {
return Err(ErrorData::invalid_params(
"range_lo and range_hi must be given together",
None,
));
}
},
};
let rows = proj.functions_filtered(&filter, p.offset.unwrap_or(0), p.limit.unwrap_or(50));
ok(serde_json::Value::Array(rows))
}
#[tool(
name = "func",
description = "Compact metadata of one function: entry, name, and block/insn/call counts. Any address inside the function snaps to its containing entry"
)]
fn func(&self, p: Parameters<AddrParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let addr =
parse_addr(&p.addr).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
proj.func_meta(addr)
.map_err(|e| ErrorData::internal_error(e.to_string(), None))
.and_then(|m| ok(serde_json::to_value(m).expect("func_meta serializes")))
}
#[tool(
name = "blocks",
description = "Block summaries of one function ordered by block start, paged with total block count. Any address inside the function snaps to its containing entry"
)]
fn blocks(&self, p: Parameters<BlocksParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let addr =
parse_addr(&p.addr).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
proj.func_blocks_page(addr, p.offset.unwrap_or(0), p.limit.unwrap_or(50))
.map_err(|e| ErrorData::internal_error(e.to_string(), None))
.and_then(|page| ok(serde_json::to_value(page).expect("blocks page serializes")))
}
#[tool(
name = "block_insns",
description = "Instructions of one function-owned block in address order, paged. Addr snaps to its containing function; block must be a block start belonging to that function"
)]
fn block_insns(&self, p: Parameters<BlockInsnsParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let addr =
parse_addr(&p.addr).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
let block =
parse_addr(&p.block).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
proj.func_block_insns_page(addr, block, p.offset.unwrap_or(0), p.limit.unwrap_or(50))
.map_err(|e| ErrorData::internal_error(e.to_string(), None))
.and_then(|page| ok(serde_json::to_value(page).expect("block_insns page serializes")))
}
#[tool(
name = "diagnostics",
description = "Analysis provenance: unresolved indirect sites and decode failures, filtered by kind and containing function, paged under the protocol-1 envelope"
)]
fn diagnostics(&self, p: Parameters<DiagnosticsParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let kind = p
.kind
.as_deref()
.map(crate::parse_diagnostic_kind)
.transpose()
.map_err(|e| match e {
crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
other => ErrorData::internal_error(other.to_string(), None),
})?;
let func = opt_addr(p.func)?;
proj.query_diagnostics(kind, func, p.offset.unwrap_or(0), p.limit.unwrap_or(50))
.map_err(|e| ErrorData::internal_error(e.to_string(), None))
.and_then(|page| ok(serde_json::to_value(page).expect("diagnostics page serializes")))
}
#[tool(
name = "disasm",
description = "Disassemble len bytes at addr with the binary architecture; returns the valid prefix plus error_at for the first bad opcode (null on a clean range)"
)]
fn disasm(&self, p: Parameters<RangeParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let addr =
parse_addr(&p.addr).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
proj.disasm_at(addr, p.len)
.map_err(|e| ErrorData::internal_error(e.to_string(), None))
.and_then(|v| ok(serde_json::to_value(v).expect("partial disasm serializes")))
}
#[tool(
name = "cfg",
description = "Control-flow graph of one function: block nodes plus block edges. Any address inside the function snaps to its containing entry"
)]
fn cfg(&self, p: Parameters<AddrParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let addr =
parse_addr(&p.addr).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
proj.cfg_of(addr)
.map_err(|e| ErrorData::internal_error(e.to_string(), None))
.and_then(ok)
}
#[tool(
name = "structure",
description = "Approximate control-flow structure of one function: syntactic loops (back-edge headers with latches) and ifs (two-successor branch sites with then/else targets) plus an approximation warning. Any address inside the function snaps to its containing entry"
)]
fn structure(&self, p: Parameters<AddrParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let addr =
parse_addr(&p.addr).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
proj.structure_of(addr)
.map_err(|e| ErrorData::internal_error(e.to_string(), None))
.and_then(ok)
}
#[tool(
name = "pseudo",
description = "Approximate pseudo-C of one function: one lossy C-like line per IR row plus assembled text, with an approximation warning. Any address inside the function snaps to its containing entry"
)]
fn pseudo(&self, p: Parameters<AddrParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let addr =
parse_addr(&p.addr).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
proj.pseudo_of(addr)
.map_err(|e| ErrorData::internal_error(e.to_string(), None))
.and_then(ok)
}
#[tool(
name = "callees",
description = "Transitive callees of one function out to depth hops (direct callees are depth 1), ordered by entry with shortest distance, paged under the protocol-1 envelope. Addr snaps to its containing function"
)]
fn callees(&self, p: Parameters<CallgraphParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let addr =
parse_addr(&p.addr).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
proj.callees_page(
addr,
p.depth.unwrap_or(crate::analysis::MAX_CALL_DEPTH),
p.offset.unwrap_or(0),
p.limit.unwrap_or(50),
)
.map_err(|e| match e {
crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
other => ErrorData::internal_error(other.to_string(), None),
})
.and_then(|page| ok(serde_json::to_value(page).expect("callees page serializes")))
}
#[tool(
name = "callers",
description = "Transitive callers of one function out to depth hops (direct callers are depth 1), ordered by entry with shortest distance, paged under the protocol-1 envelope. Addr snaps to its containing function"
)]
fn callers(&self, p: Parameters<CallgraphParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let addr =
parse_addr(&p.addr).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
proj.callers_page(
addr,
p.depth.unwrap_or(crate::analysis::MAX_CALL_DEPTH),
p.offset.unwrap_or(0),
p.limit.unwrap_or(50),
)
.map_err(|e| match e {
crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
other => ErrorData::internal_error(other.to_string(), None),
})
.and_then(|page| ok(serde_json::to_value(page).expect("callers page serializes")))
}
#[tool(
name = "slice",
description = "Backward slice of one address: every instruction that can reach it via xref edges (any kind) and intra-function CFG predecessors, out to depth hops (direct predecessors are depth 1), ordered by address with shortest distance, paged under the protocol-1 envelope. Any address is a valid root"
)]
fn slice(&self, p: Parameters<SliceParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let addr =
parse_addr(&p.addr).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
proj.slice_page(
addr,
p.depth.unwrap_or(crate::analysis::MAX_SLICE_DEPTH),
p.offset.unwrap_or(0),
p.limit.unwrap_or(50),
)
.map_err(|e| match e {
crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
other => ErrorData::internal_error(other.to_string(), None),
})
.and_then(|page| ok(serde_json::to_value(page).expect("slice page serializes")))
}
#[tool(
name = "xrefs",
description = "Cross-references filtered by to/from address and kind, paged with total match count"
)]
fn xrefs(&self, p: Parameters<XrefsParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let kind = p
.kind
.as_deref()
.map(parse_xref_kind)
.transpose()
.map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
let (to, from) = (opt_addr(p.to)?, opt_addr(p.from)?);
let total = proj.count_xrefs(to, from, kind);
let rows = proj.query_xrefs(to, from, kind, p.offset.unwrap_or(0), p.limit.unwrap_or(50));
ok(serde_json::json!({ "total": total, "xrefs": rows }))
}
#[tool(
name = "strings",
description = "Extracted strings ordered by address, filtered by pattern/min-len/section, paged by start/limit. Hits in executable memory are hidden unless pattern, section, or include_code is given. Decode renders a read-only single-byte-obfuscated view: xor:<byte>, add:<byte>, or rot:<0-7>"
)]
fn strings(&self, p: Parameters<StringsParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
if p.offset.is_some() {
eprintln!("warning: strings offset is deprecated, use start");
}
let decode = p
.decode
.as_deref()
.map(crate::loader::strings::parse_decode_spec)
.transpose()
.map_err(|e| match e {
crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
other => ErrorData::internal_error(other.to_string(), None),
})?;
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let filter = crate::analysis::StringsFilter {
pattern: p.pattern,
min_len: p.min_len,
section: p.section,
include_code: p.include_code.unwrap_or(false),
start: p.start.or(p.offset).unwrap_or(0),
limit: p.limit.unwrap_or(50),
};
let rows = match decode {
Some(spec) => proj.query_strings_decoded(&filter, spec),
None => proj.query_strings(&filter),
}
.map_err(|e| match e {
crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
other => ErrorData::internal_error(other.to_string(), None),
})?;
ok(serde_json::to_value(rows).expect("strings serialize"))
}
#[tool(name = "symbols", description = "Imports and exports of the binary")]
fn symbols(&self, p: Parameters<BinaryParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
ok(open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?
.symbols_json())
}
#[tool(
name = "stats",
description = "Storage stats: binary size, sidecar DB size, and analysis counts"
)]
fn stats(&self, p: Parameters<BinaryParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?
.stats_json()
.map_err(|e| ErrorData::internal_error(e.to_string(), None))
.and_then(ok)
}
#[tool(
name = "sections",
description = "Section table: name, virtual address (PE: IMAGE_BASE + RVA), in-memory and file sizes, permissions"
)]
fn sections(&self, p: Parameters<BinaryParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
ok(open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?
.sections_json())
}
#[tool(
name = "ir",
description = "Lift len bytes at addr to P-code-inspired IR"
)]
fn ir(&self, p: Parameters<RangeParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let addr =
parse_addr(&p.addr).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
proj.ir_at(addr, p.len)
.map_err(|e| ErrorData::internal_error(e.to_string(), None))
.and_then(ok)
}
#[tool(
name = "ir_coverage",
description = "Machine-readable IR lift coverage for one arch (implemented families, partial mappings, limitations); with binary/addr/len adds per-range decoded/lifted/unlifted counts from actual lifts plus a bounded mnemonic summary"
)]
fn ir_coverage(&self, p: Parameters<IrCoverageParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let arch = crate::parse_raw_arch(&p.arch)
.map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
match (p.binary, p.addr, p.len) {
(None, None, None) => ok(crate::ir_coverage(arch)),
(Some(binary), Some(addr), Some(len)) => {
let proj = open(
&binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let addr = parse_addr(&addr)
.map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
proj.ir_coverage_at(arch, addr, len)
.map_err(|e| match e {
crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
other => ErrorData::internal_error(other.to_string(), None),
})
.and_then(ok)
}
_ => Err(ErrorData::invalid_params(
"ir_coverage range needs binary, addr, and len together",
None,
)),
}
}
#[tool(
name = "rename",
description = "Rename a function in the project DB (binary untouched); empty name clears"
)]
fn rename(&self, p: Parameters<RenameParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let mut proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let addr =
parse_addr(&p.addr).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
proj.rename_function(addr, &p.name)
.map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
ok(proj.annotation_json(addr))
}
#[tool(
name = "comment",
description = "Comment any address in the project DB (binary untouched); empty comment clears"
)]
fn comment(&self, p: Parameters<CommentParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let mut proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let addr =
parse_addr(&p.addr).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
proj.set_comment(addr, &p.comment)
.map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
ok(proj.annotation_json(addr))
}
#[tool(
name = "search_bytes",
description = "Search mapped file bytes for a whitespace-separated hex pattern (two hex digits or ?? per token), filtered by section/range, paged with total match count"
)]
fn search_bytes(&self, p: Parameters<SearchBytesParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let range = match (p.range_start, p.range_end) {
(None, None) => None,
(Some(lo), Some(hi)) => Some((
parse_addr(&lo).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?,
parse_addr(&hi).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?,
)),
_ => {
return Err(ErrorData::invalid_params(
"range_start and range_end must be given together",
None,
));
}
};
proj.search_bytes(
&p.pattern,
p.section.as_deref(),
range,
p.offset.unwrap_or(0),
p.limit.unwrap_or(50),
)
.map_err(|e| match e {
crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
other => ErrorData::internal_error(other.to_string(), None),
})
.and_then(|page| ok(serde_json::to_value(page).expect("search_bytes page serializes")))
}
#[tool(
name = "annotations_export",
description = "Emit the portable annotation interchange document (revision, sha256, size, mapping, sorted rows); read-only, never creates or modifies the sidecar"
)]
fn annotations_export(&self, p: Parameters<BinaryParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let doc = proj
.export_annotations()
.map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
serde_json::from_str::<serde_json::Value>(&doc)
.map_err(|e| {
ErrorData::internal_error(format!("encode annotation document: {e}"), None)
})
.and_then(ok)
}
#[tool(
name = "annotations_import",
description = "Atomically merge a portable annotation document into the project DB; returns row/change counts. Default fails on conflicting fields, overwrite replaces supplied fields only"
)]
fn annotations_import(
&self,
p: Parameters<AnnotationsImportParams>,
) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let mut proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
proj.import_annotations(&p.document, p.overwrite.unwrap_or(false))
.map_err(|e| match e {
crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
other => ErrorData::internal_error(other.to_string(), None),
})
.and_then(|s| ok(serde_json::json!({"rows": s.rows, "changed": s.changed})))
}
#[tool(
name = "flirt_hints",
description = "FLIRT-like library hints: corpus signature matches over each function's leading bytes, paged under the protocol-1 envelope. Suggested names stay hints; read-only, never renames or writes the sidecar"
)]
fn flirt_hints(&self, p: Parameters<FlirtHintsParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let proj = open(
&p.binary,
p.db.as_deref(),
p.raw.as_ref(),
p.fat_arch.as_deref(),
)?;
let addr = opt_addr(p.addr)?;
proj.query_flirt_hints(addr, p.offset.unwrap_or(0), p.limit.unwrap_or(50))
.map_err(|e| ErrorData::internal_error(e.to_string(), None))
.and_then(|page| ok(serde_json::to_value(page).expect("flirt hints page serializes")))
}
#[tool(
name = "diff",
description = "Function-level diff between two binaries: byte-identical pairs are matched, content-matched pairs are changed (with the match reason), the rest is added (only in B) / removed (only in A). Both projects open read-only, never creating or modifying a sidecar"
)]
fn diff(&self, p: Parameters<DiffParams>) -> Result<String, ErrorData> {
let _guard = self.guard();
let p = all_params(p);
let raw_opts = raw_options(p.raw.as_ref())?;
let db_a_path;
let db_a = match p.db_a.as_deref() {
Some(d) => {
db_a_path = Path::new(d).to_path_buf();
Some(db_a_path.as_path())
}
None => None,
};
let db_b_path;
let db_b = match p.db_b.as_deref() {
Some(d) => {
db_b_path = Path::new(d).to_path_buf();
Some(db_b_path.as_path())
}
None => None,
};
let map_err = |e| match e {
crate::error::Error::Invalid(msg) => ErrorData::invalid_params(msg, None),
other => ErrorData::internal_error(other.to_string(), None),
};
let a = crate::open_mapped(
Path::new(&p.binary_a),
db_a,
raw_opts,
p.fat_arch.as_deref(),
)
.map_err(map_err)?;
let b = crate::open_mapped(
Path::new(&p.binary_b),
db_b,
raw_opts,
p.fat_arch.as_deref(),
)
.map_err(map_err)?;
let report = crate::diff::diff_projects(&a, &b);
ok(serde_json::to_value(report).expect("diff report serializes"))
}
}