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};
type JsonMap = serde_json::Map<String, Value>;
#[derive(Debug, Clone)]
struct NmapMcpServer {
#[allow(dead_code)]
tool_router: ToolRouter<Self>,
runner: NmapRunner,
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)),
}
}
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
}
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}")),
}
}
}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct StatusRequest {}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct ListScriptsRequest {
category: Option<String>,
name: Option<String>,
limit: Option<u32>,
}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct ScriptInfoRequest {
name: String,
}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct TargetRequest {
targets: String,
timeout_secs: Option<u64>,
}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct PortScanRequest {
targets: String,
ports: Option<String>,
top_ports: Option<u32>,
timing: Option<u8>,
timeout_secs: Option<u64>,
}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct ServiceScanRequest {
targets: String,
ports: Option<String>,
version_intensity: Option<u8>,
timing: Option<u8>,
timeout_secs: Option<u64>,
}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct OsScanRequest {
targets: String,
timing: Option<u8>,
timeout_secs: Option<u64>,
}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct ScriptScanRequest {
targets: String,
script: String,
script_args: Option<String>,
ports: Option<String>,
timing: Option<u8>,
timeout_secs: Option<u64>,
}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct FullScanRequest {
targets: String,
ports: Option<String>,
timing: Option<u8>,
timeout_secs: Option<u64>,
}
#[tool_router]
impl NmapMcpServer {
#[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))
}
#[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))
}
#[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}")),
}
}
#[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
}
#[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
}
#[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
}
#[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
}
#[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
}
#[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");
}
}