nmap-mcp 0.1.0

Nmap network scanner and NSE scripting engine control for AI assistants via MCP
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! nmap-mcp — MCP server exposing the nmap network scanner and its Nmap
//! Scripting Engine (NSE) to AI assistants.
//!
//! Tools:
//!   - nmap_status         version, binary path, script inventory summary
//!   - nmap_list_scripts   list NSE scripts from script.db, filter by category/name
//!   - nmap_script_info    full metadata for one script via --script-help
//!   - nmap_ping_scan      host discovery (-sn)
//!   - nmap_port_scan      TCP port scan (-sT, ports or --top-ports)
//!   - nmap_service_scan   service/version detection (-sV)
//!   - nmap_os_scan        OS detection (-O)
//!   - nmap_script_scan    run NSE script(s) against a target (--script)
//!   - nmap_full_scan      combined default-script + version + OS scan
//!
//! The server drives the real nmap binary (env `NMAP_MCP_BIN` override, then
//! `PATH`), requests `-oX -` XML output, and parses it into structured JSON.
//! All commands are spawned with explicit argument arrays — never through a
//! shell — so targets cannot inject commands.

mod nmap_runner;
mod nmap_xml;
mod script_db;
mod script_help;
mod validate;

use std::sync::Arc;

use anyhow::Result;
use rmcp::{
    handler::server::{router::tool::ToolRouter, wrapper::Parameters},
    model::{ServerCapabilities, ServerInfo},
    schemars, tool, tool_handler, tool_router,
    transport::stdio,
    ServerHandler, ServiceExt,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::sync::Mutex;

use nmap_runner::{script_db_path, script_file_count, NmapRunner};
use script_db::{category_counts, entry_json, filter_entries, parse_script_db, ScriptEntry};

/// Shorthand for a JSON object map with string keys.
type JsonMap = serde_json::Map<String, Value>;

#[derive(Debug, Clone)]
struct NmapMcpServer {
    // Held by the tool-router macro's generated code; the field itself is
    // never read directly.
    #[allow(dead_code)]
    tool_router: ToolRouter<Self>,
    runner: NmapRunner,
    /// Parsed script.db, loaded once and shared across tool calls.
    script_db: Arc<Mutex<Option<Vec<ScriptEntry>>>>,
}

impl NmapMcpServer {
    fn new() -> Self {
        Self {
            tool_router: Self::tool_router(),
            runner: NmapRunner::new(),
            script_db: Arc::new(Mutex::new(None)),
        }
    }

    /// Load script.db (cached), falling back to an empty list.
    async fn entries(&self) -> Vec<ScriptEntry> {
        let mut cache = self.script_db.lock().await;
        if let Some(entries) = cache.as_ref() {
            return entries.clone();
        }
        let entries = match script_db_path(&self.runner) {
            Some(path) => match std::fs::read_to_string(&path) {
                Ok(text) => parse_script_db(&text),
                Err(_) => Vec::new(),
            },
            None => Vec::new(),
        };
        *cache = Some(entries.clone());
        entries
    }

    /// Run a scan and return the parsed JSON document as a pretty string.
    async fn scan_json(&self, args: &[String], timeout_secs: u64) -> String {
        match self.runner.scan(args, timeout_secs).await {
            Ok(v) => pretty(&v),
            Err(e) => err_str(&anyhow::anyhow!("{e}")),
        }
    }
}

// ---------------------------------------------------------------------------
// Tool input types
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct StatusRequest {}

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct ListScriptsRequest {
    /// Filter by script category, e.g. "default", "discovery", "safe",
    /// "vuln", "brute". Case-insensitive.
    category: Option<String>,
    /// Substring filter on the script name, e.g. "http" or "ssh".
    name: Option<String>,
    /// Maximum number of results. Default 50, max 200. Use a category or
    /// name filter to narrow the list.
    limit: Option<u32>,
}

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct ScriptInfoRequest {
    /// Script name without the .nse extension, e.g. "http-title" or
    /// "ssh-hostkey". Several names may be given space-separated.
    name: String,
}

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct TargetRequest {
    /// Target host(s): IP address, hostname, CIDR range, or comma-separated
    /// list, e.g. "192.168.1.10", "scanme.nmap.org", "10.0.0.0/24".
    targets: String,
    /// Per-scan timeout in seconds. Default 120, max 3600.
    timeout_secs: Option<u64>,
}

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct PortScanRequest {
    /// Target host(s): IP address, hostname, CIDR range, or comma-separated
    /// list, e.g. "192.168.1.10", "scanme.nmap.org", "10.0.0.0/24".
    targets: String,
    /// Ports to scan: "22", "22,80,443", "1-1024", "ssh,http", or "-" for
    /// all 65535. When omitted, --top-ports (default 100) is used.
    ports: Option<String>,
    /// Scan the N most common ports instead of a fixed list (1-10000).
    top_ports: Option<u32>,
    /// Timing template 0-5 (paranoid..insane). Default: nmap's own default.
    timing: Option<u8>,
    /// Per-scan timeout in seconds. Default 120, max 3600.
    timeout_secs: Option<u64>,
}

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct ServiceScanRequest {
    /// Target host(s): IP address, hostname, CIDR range, or comma-separated
    /// list.
    targets: String,
    /// Ports to probe: "22,80", "1-1024", "ssh,http", or "-" for all. When
    /// omitted, --top-ports (default 100) is used.
    ports: Option<String>,
    /// Version detection intensity 0-9 (higher = more probes). Default 7.
    version_intensity: Option<u8>,
    /// Timing template 0-5. Default: nmap's own default.
    timing: Option<u8>,
    /// Per-scan timeout in seconds. Default 120, max 3600.
    timeout_secs: Option<u64>,
}

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct OsScanRequest {
    /// Target host(s): IP address, hostname, CIDR range, or comma-separated
    /// list.
    targets: String,
    /// Timing template 0-5. Default: nmap's own default.
    timing: Option<u8>,
    /// Per-scan timeout in seconds. Default 120, max 3600.
    timeout_secs: Option<u64>,
}

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct ScriptScanRequest {
    /// Target host(s): IP address, hostname, CIDR range, or comma-separated
    /// list.
    targets: String,
    /// NSE script(s) to run, comma-separated, or a category like "default",
    /// "safe", "vuln". Examples: "http-title", "ssh-hostkey", "vuln".
    script: String,
    /// Script arguments as nmap expects them, e.g.
    /// "http-title.maxsize=500,userdb=/path/users.txt". Optional.
    script_args: Option<String>,
    /// Ports to run the script against: "22", "80,443", "1-1024". When
    /// omitted, scripts run on the default ports nmap picks.
    ports: Option<String>,
    /// Timing template 0-5. Default: nmap's own default.
    timing: Option<u8>,
    /// Per-scan timeout in seconds. Default 120, max 3600.
    timeout_secs: Option<u64>,
}

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct FullScanRequest {
    /// Target host(s): IP address, hostname, CIDR range, or comma-separated
    /// list.
    targets: String,
    /// Ports to scan: "22,80,443", "1-1024", "ssh,http", or "-". When
    /// omitted, --top-ports (default 100) is used.
    ports: Option<String>,
    /// Timing template 0-5. Default: nmap's own default.
    timing: Option<u8>,
    /// Per-scan timeout in seconds. Default 120, max 3600.
    timeout_secs: Option<u64>,
}

// ---------------------------------------------------------------------------
// Tools
// ---------------------------------------------------------------------------

#[tool_router]
impl NmapMcpServer {
    /// Report nmap availability and version.
    #[tool(
        description = "Check that nmap is installed and report the version, resolved binary path, script database location, and NSE script inventory (total scripts and per-category counts). Run this first to verify the environment, then use the scan and script tools."
    )]
    async fn nmap_status(&self, Parameters(_req): Parameters<StatusRequest>) -> String {
        let version = self.runner.version().await;
        let db_path = script_db_path(&self.runner);
        let entries = self.entries().await;
        let counts = category_counts(&entries);

        let mut m = JsonMap::new();
        match version {
            Ok((v, line)) => {
                m.insert("available".into(), Value::Bool(true));
                m.insert("version".into(), Value::String(v));
                m.insert("version_line".into(), Value::String(line));
            }
            Err(e) => {
                m.insert("available".into(), Value::Bool(false));
                m.insert("error".into(), Value::String(e));
            }
        }
        m.insert("binary".into(), Value::String(self.runner.bin()));
        m.insert(
            "script_db".into(),
            db_path
                .map(|p| Value::String(p.display().to_string()))
                .unwrap_or(Value::Null),
        );
        m.insert("script_count".into(), Value::from(entries.len() as u64));
        if let Some(files) = script_file_count(&self.runner) {
            m.insert("nse_files".into(), Value::from(files as u64));
        }
        m.insert(
            "canonical_categories".into(),
            Value::Array(
                script_db::SCRIPT_CATEGORIES
                    .iter()
                    .map(|c| Value::String(c.to_string()))
                    .collect(),
            ),
        );
        m.insert("categories".into(), Value::Array(counts));
        pretty(&Value::Object(m))
    }

    /// List NSE scripts by category and/or name.
    #[tool(
        description = "List the Nmap Scripting Engine (NSE) scripts available in this installation, optionally filtered by category (default, discovery, safe, vuln, brute, ...) and by a name substring. Returns each script's base name, file name, and categories. Combine with nmap_script_info for the full description of a script, and nmap_script_scan to run one."
    )]
    async fn nmap_list_scripts(&self, Parameters(req): Parameters<ListScriptsRequest>) -> String {
        let entries = self.entries().await;
        let limit = req.limit.unwrap_or(50).min(200) as usize;
        let filtered = filter_entries(&entries, req.category.as_deref(), req.name.as_deref());
        let rows: Vec<Value> = filtered.iter().take(limit).map(|e| entry_json(e)).collect();

        let mut m = JsonMap::new();
        m.insert("total".into(), Value::from(entries.len() as u64));
        m.insert("matched".into(), Value::from(filtered.len() as u64));
        m.insert("truncated".into(), Value::Bool(filtered.len() > limit));
        if let Some(c) = &req.category {
            m.insert("category_filter".into(), Value::String(c.clone()));
        }
        if let Some(n) = &req.name {
            m.insert("name_filter".into(), Value::String(n.clone()));
        }
        m.insert("scripts".into(), Value::Array(rows));
        pretty(&Value::Object(m))
    }

    /// Full metadata for one NSE script.
    #[tool(
        description = "Fetch the full description of one NSE script (or several, space-separated) from 'nmap --script-help': categories, nsedoc URL, and the complete description text. Use nmap_list_scripts to discover script names first, and nmap_script_scan to execute a script against a target."
    )]
    async fn nmap_script_info(&self, Parameters(req): Parameters<ScriptInfoRequest>) -> String {
        let names: Vec<&str> = req.name.split_whitespace().collect();
        if names.is_empty() {
            return err_str(&anyhow::anyhow!("name must not be empty"));
        }
        match self.runner.script_help(&names, 30).await {
            Ok(text) => {
                let parsed = script_help::parse_script_help(&text);
                let complete = script_help::complete_with_requested(parsed, &names);
                let rows: Vec<Value> = complete.iter().map(|s| s.to_json()).collect();
                let mut m = JsonMap::new();
                m.insert("requested".into(), Value::from(names.len()));
                m.insert("scripts".into(), Value::Array(rows));
                pretty(&Value::Object(m))
            }
            Err(e) => err_str(&anyhow::anyhow!("{e}")),
        }
    }

    /// Host discovery (ping sweep).
    #[tool(
        description = "Discover which hosts are up with a ping sweep (nmap -sn): no port scanning, just liveness. Useful to map a subnet before port scanning, e.g. '192.168.1.0/24'. Returns each up host with its addresses and reverse DNS names, plus scan statistics."
    )]
    async fn nmap_ping_scan(&self, Parameters(req): Parameters<TargetRequest>) -> String {
        if let Err(e) = validate::validate_target(&req.targets) {
            return err_str(&anyhow::anyhow!("{e}"));
        }
        let timeout = validate::timeout_secs(req.timeout_secs);
        let args = vec!["-sn".to_string(), req.targets.trim().to_string()];
        self.scan_json(&args, timeout).await
    }

    /// TCP port scan.
    #[tool(
        description = "Scan TCP ports on the target(s) with a connect scan (nmap -sT, works without root). Specify 'ports' as '22', '22,80,443', '1-1024', 'ssh,http', or '-' for all 65535 ports; otherwise the 'top_ports' most common ports are scanned (default 100). Returns per-host open/closed/filtered ports with service names, plus scan statistics. Use nmap_service_scan for version details, nmap_script_scan to run NSE scripts on open ports."
    )]
    async fn nmap_port_scan(&self, Parameters(req): Parameters<PortScanRequest>) -> String {
        if let Err(e) = validate::validate_target(&req.targets) {
            return err_str(&anyhow::anyhow!("{e}"));
        }
        let timeout = validate::timeout_secs(req.timeout_secs);
        let mut args = vec!["-sT".to_string()];
        match (&req.ports, req.top_ports) {
            (Some(p), _) => {
                if let Err(e) = validate::validate_ports(p) {
                    return err_str(&anyhow::anyhow!("{e}"));
                }
                args.push("-p".to_string());
                args.push(p.trim().to_string());
            }
            (None, Some(n)) => {
                if let Err(e) = validate::validate_top_ports(n) {
                    return err_str(&anyhow::anyhow!("{e}"));
                }
                args.push("--top-ports".to_string());
                args.push(n.to_string());
            }
            (None, None) => {
                args.push("--top-ports".to_string());
                args.push("100".to_string());
            }
        }
        if let Some(t) = req.timing {
            if let Err(e) = validate::validate_timing(t) {
                return err_str(&anyhow::anyhow!("{e}"));
            }
            args.push(format!("-T{t}"));
        }
        args.push(req.targets.trim().to_string());
        self.scan_json(&args, timeout).await
    }

    /// Service/version detection.
    #[tool(
        description = "Detect the service and version running on open ports (nmap -sV). Probes each open port and returns product, version, extra info, CPE identifiers, and detection confidence. Specify 'ports' to limit the probe set, or leave empty to probe the top 100. Use 'version_intensity' (0-9, default 7) to trade speed for accuracy."
    )]
    async fn nmap_service_scan(&self, Parameters(req): Parameters<ServiceScanRequest>) -> String {
        if let Err(e) = validate::validate_target(&req.targets) {
            return err_str(&anyhow::anyhow!("{e}"));
        }
        let timeout = validate::timeout_secs(req.timeout_secs);
        let mut args = vec!["-sV".to_string()];
        if let Some(p) = &req.ports {
            if let Err(e) = validate::validate_ports(p) {
                return err_str(&anyhow::anyhow!("{e}"));
            }
            args.push("-p".to_string());
            args.push(p.trim().to_string());
        } else {
            args.push("--top-ports".to_string());
            args.push("100".to_string());
        }
        if let Some(i) = req.version_intensity {
            if let Err(e) = validate::validate_intensity(i) {
                return err_str(&anyhow::anyhow!("{e}"));
            }
            args.push("--version-intensity".to_string());
            args.push(i.to_string());
        }
        if let Some(t) = req.timing {
            if let Err(e) = validate::validate_timing(t) {
                return err_str(&anyhow::anyhow!("{e}"));
            }
            args.push(format!("-T{t}"));
        }
        args.push(req.targets.trim().to_string());
        self.scan_json(&args, timeout).await
    }

    /// OS detection.
    #[tool(
        description = "Detect the operating system of the target (nmap -O) using TCP/IP fingerprinting. Returns OS match names with accuracy and classified families (vendor, family, generation, CPE). Note: OS detection needs raw sockets and usually root privileges; without them nmap reports reduced reliability or skips the fingerprint."
    )]
    async fn nmap_os_scan(&self, Parameters(req): Parameters<OsScanRequest>) -> String {
        if let Err(e) = validate::validate_target(&req.targets) {
            return err_str(&anyhow::anyhow!("{e}"));
        }
        let timeout = validate::timeout_secs(req.timeout_secs);
        let mut args = vec!["-O".to_string()];
        if let Some(t) = req.timing {
            if let Err(e) = validate::validate_timing(t) {
                return err_str(&anyhow::anyhow!("{e}"));
            }
            args.push(format!("-T{t}"));
        }
        args.push(req.targets.trim().to_string());
        self.scan_json(&args, timeout).await
    }

    /// Run NSE scripts.
    #[tool(
        description = "Run Nmap Scripting Engine (NSE) scripts against the target(s) (nmap --script). 'script' is a comma-separated list of script names or a category such as 'default', 'safe', or 'vuln'. Optional 'script_args' passes arguments in nmap syntax, e.g. 'http-title.maxsize=500'. 'ports' limits the scan to specific ports. Returns each host's ports with the script id, its text output, and any structured table data. Combine with nmap_list_scripts and nmap_script_info to choose scripts."
    )]
    async fn nmap_script_scan(&self, Parameters(req): Parameters<ScriptScanRequest>) -> String {
        if let Err(e) = validate::validate_target(&req.targets) {
            return err_str(&anyhow::anyhow!("{e}"));
        }
        if req.script.trim().is_empty() {
            return err_str(&anyhow::anyhow!("script must not be empty"));
        }
        let timeout = validate::timeout_secs(req.timeout_secs);
        let mut args = vec![
            "-sT".to_string(),
            "--script".to_string(),
            req.script.trim().to_string(),
        ];
        if let Some(a) = &req.script_args {
            if !a.trim().is_empty() {
                args.push("--script-args".to_string());
                args.push(a.trim().to_string());
            }
        }
        if let Some(p) = &req.ports {
            if let Err(e) = validate::validate_ports(p) {
                return err_str(&anyhow::anyhow!("{e}"));
            }
            args.push("-p".to_string());
            args.push(p.trim().to_string());
        }
        if let Some(t) = req.timing {
            if let Err(e) = validate::validate_timing(t) {
                return err_str(&anyhow::anyhow!("{e}"));
            }
            args.push(format!("-T{t}"));
        }
        args.push(req.targets.trim().to_string());
        self.scan_json(&args, timeout).await
    }

    /// Combined full scan.
    #[tool(
        description = "Run a full default scan: connect scan with the default NSE script set, service/version detection, and OS detection (nmap -sT -sV -O -sC). This is the deepest single-pass scan; it is also the slowest and noisiest. OS detection may need root. Prefer targeted tools (nmap_port_scan, nmap_service_scan, nmap_script_scan) when you know what you need."
    )]
    async fn nmap_full_scan(&self, Parameters(req): Parameters<FullScanRequest>) -> String {
        if let Err(e) = validate::validate_target(&req.targets) {
            return err_str(&anyhow::anyhow!("{e}"));
        }
        let timeout = validate::timeout_secs(req.timeout_secs);
        let mut args = vec![
            "-sT".to_string(),
            "-sV".to_string(),
            "-O".to_string(),
            "-sC".to_string(),
        ];
        if let Some(p) = &req.ports {
            if let Err(e) = validate::validate_ports(p) {
                return err_str(&anyhow::anyhow!("{e}"));
            }
            args.push("-p".to_string());
            args.push(p.trim().to_string());
        } else {
            args.push("--top-ports".to_string());
            args.push("100".to_string());
        }
        if let Some(t) = req.timing {
            if let Err(e) = validate::validate_timing(t) {
                return err_str(&anyhow::anyhow!("{e}"));
            }
            args.push(format!("-T{t}"));
        }
        args.push(req.targets.trim().to_string());
        self.scan_json(&args, timeout).await
    }
}

#[tool_handler]
impl ServerHandler for NmapMcpServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(ServerCapabilities::builder().enable_tools().build()).with_instructions(
            "Nmap network scanner and NSE scripting engine control. \
             Typical flow: nmap_status to verify the environment, nmap_list_scripts / \
             nmap_script_info to pick NSE scripts, then nmap_ping_scan to find live hosts, \
             nmap_port_scan to find open ports, nmap_service_scan for service versions, \
             nmap_script_scan to run NSE scripts (categories like 'safe' or 'vuln'), and \
             nmap_full_scan for a deep single pass. \
             Scan only hosts the user has authorized: network scanning is active \
             reconnaissance and can be detected, so confirm scope before scanning \
             anything outside the local network.",
        )
    }
}

fn pretty(v: &Value) -> String {
    serde_json::to_string_pretty(v).unwrap_or_else(|_| "{}".into())
}

fn err_str(e: &anyhow::Error) -> String {
    serde_json::json!({ "error": e.to_string() }).to_string()
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let service = NmapMcpServer::new();
    let running = service.serve(stdio()).await?;
    running.waiting().await?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn error_json_shape() {
        let s = err_str(&anyhow::anyhow!("boom"));
        let v: Value = serde_json::from_str(&s).unwrap();
        assert_eq!(v["error"], "boom");
    }
}