binscout 0.2.1

Headless, agent-first binary analysis: functions, CFGs, xrefs, strings, and IR over a JSON CLI or MCP server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! binscout MCP server: 13 stateless tools over [`Project`].
//!
//! Every tool takes a `binary` path (plus optional `db` sidecar path), opens
//! the project, and returns one JSON document as text. Failures surface as
//! tool errors, never as silent empty results.

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};

/// Shared opener: explicit `db` path or the default sidecar.
fn open(binary: &str, db: Option<&str>) -> Result<Project, ErrorData> {
    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,
    };
    Project::open_any(Path::new(binary), db_ref)
        .map_err(|e| ErrorData::internal_error(e.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
}

/// Parameters for single-binary tools (`project_info`, `symbols`, `sections`, `stats`).
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct BinaryParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path (default: `<binary>.rsdbg.redb` sidecar).
    pub db: Option<String>,
}

/// Parameters for the `strings` tool: filtered, paged string search.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct StringsParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Rows to skip after filtering.
    pub start: Option<usize>,
    /// Deprecated alias of `start`.
    pub offset: Option<usize>,
    /// Max rows (capped at 1024).
    pub limit: Option<usize>,
    /// Case-sensitive substring, or `regex:`-prefixed expression.
    pub pattern: Option<String>,
    /// Keep strings with at least this many characters.
    pub min_len: Option<usize>,
    /// Keep strings in exactly this section (e.g. `.rdata`).
    pub section: Option<String>,
    /// Show strings in executable memory (hidden by default).
    pub include_code: Option<bool>,
}

/// Parameters for the `functions` tool: paged list with optional filters.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct FunctionsParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Case-insensitive substring over the rename-resolved name.
    pub query: Option<String>,
    /// Keep functions that call the function containing this address.
    pub caller: Option<String>,
    /// Keep functions called by the function containing this address.
    pub callee: Option<String>,
    /// Keep functions with entry at or above this address (needs range_hi).
    pub range_lo: Option<String>,
    /// Keep functions with entry at or below this address (needs range_lo).
    pub range_hi: Option<String>,
    /// First row to return.
    pub offset: Option<usize>,
    /// Max rows (capped at 1024).
    pub limit: Option<usize>,
}

/// Parameters for single-address tools (`func`, `cfg`, `comment`).
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct AddrParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Virtual address (`0x`-hex or decimal string).
    pub addr: String,
}

/// Parameters for byte-range tools (`disasm`, `ir`).
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct RangeParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Virtual address (`0x`-hex or decimal string).
    pub addr: String,
    /// Bytes to decode.
    pub len: usize,
}

/// Parameters for the `xrefs` tool.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct XrefsParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Only xrefs pointing at this address (`0x`-hex or decimal).
    pub to: Option<String>,
    /// Only xrefs originating at this address.
    pub from: Option<String>,
    /// Only `code`, `data`, or `string` xrefs.
    pub kind: Option<String>,
    /// First row to return.
    pub offset: Option<usize>,
    /// Max rows (capped at 1024).
    pub limit: Option<usize>,
}

/// Parameters for the `rename` tool.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct RenameParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Function entry address (`0x`-hex or decimal string).
    pub addr: String,
    /// New name (empty string clears).
    pub name: String,
}

/// Parameters for the `comment` tool.
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct CommentParams {
    /// Path to the analyzed binary.
    pub binary: String,
    /// Explicit project DB path.
    pub db: Option<String>,
    /// Address to comment (`0x`-hex or decimal string).
    pub addr: String,
    /// Comment text (empty string clears).
    pub comment: String,
}

/// MCP server handler; serializes tool calls behind one lock.
#[derive(Debug, Clone, Default)]
pub struct BinscoutMcp {
    /// Serializes tool calls: `redb` allows one open handle per file per
    /// process, and rename/comment are read-modify-write cycles.
    lock: Arc<Mutex<()>>,
}

impl BinscoutMcp {
    /// New handler with a fresh call-serializing lock.
    #[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())?;
        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())?;
        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 = "Full detail of one function: blocks with instructions, edges, calls. 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())?;
        let addr =
            parse_addr(&p.addr).map_err(|e| ErrorData::invalid_params(e.to_string(), None))?;
        proj.func_detail(addr)
            .map_err(|e| ErrorData::internal_error(e.to_string(), None))
            .and_then(ok)
    }

    #[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())?;
        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())?;
        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 = "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())?;
        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"
    )]
    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 proj = open(&p.binary, p.db.as_deref())?;
        let rows = proj
            .query_strings(&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),
            })
            .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())?.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())?
            .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())?.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())?;
        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 = "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())?;
        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())?;
        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))
    }
}