nmap-mcp 0.1.0

Nmap network scanner and NSE scripting engine control for AI assistants via MCP
//! Parser for `nmap --script-help <name>` output.
//!
//! For one or more requested scripts, nmap prints a banner line, then one
//! block per script:
//!
//! ```text
//! Starting Nmap 7.95 ( https://nmap.org ) at 2026-08-08 21:20 CEST
//!
//! http-title
//! Categories: default discovery safe
//! https://nmap.org/nsedoc/scripts/http-title.html
//!   Shows the title of the default page of a web server.
//!
//!   The script will follow up to 5 HTTP redirects, using the default rules in
//!   the http library.
//! ```
//!
//! Unknown scripts produce a line like `NSE: Script 'foo' was not found!`.
//! The parser is a pure function over the text; [`ScriptInfo`] entries are
//! returned in output order, and the caller matches them against the
//! requested names to surface not-found errors.

use serde_json::{Map, Value};

/// Parsed information for one script from `--script-help`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ScriptInfo {
    /// Script base name, e.g. `http-title`.
    pub name: String,
    /// Categories the script belongs to.
    pub categories: Vec<String>,
    /// nsedoc URL for the script, if printed.
    pub url: Option<String>,
    /// The description body (indented lines), paragraphs preserved.
    pub description: String,
    /// True when nmap reported the script as not found.
    pub not_found: bool,
}

impl ScriptInfo {
    /// Convert to the JSON row returned by the `nmap_script_info` tool.
    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        m.insert("name".to_string(), Value::String(self.name.clone()));
        m.insert(
            "categories".to_string(),
            Value::Array(
                self.categories
                    .iter()
                    .map(|c| Value::String(c.clone()))
                    .collect(),
            ),
        );
        if let Some(u) = &self.url {
            m.insert("url".to_string(), Value::String(u.clone()));
        }
        m.insert(
            "description".to_string(),
            Value::String(self.description.clone()),
        );
        m.insert("not_found".to_string(), Value::Bool(self.not_found));
        Value::Object(m)
    }
}

/// Parse `--script-help` output into script blocks.
pub fn parse_script_help(input: &str) -> Vec<ScriptInfo> {
    let mut scripts: Vec<ScriptInfo> = Vec::new();
    let mut current: Option<ScriptInfo> = None;

    for raw in input.lines() {
        let line = raw.trim_end();
        let trimmed = line.trim_start();

        // Not-found diagnostics: "NSE: Script 'foo' was not found!"
        if trimmed.starts_with("NSE:") {
            if let Some(name) = extract_not_found_name(trimmed) {
                // Flush any in-progress block first.
                if let Some(s) = current.take() {
                    scripts.push(s);
                }
                scripts.push(ScriptInfo {
                    name,
                    not_found: true,
                    ..Default::default()
                });
            }
            continue;
        }

        // Banner and summary lines; blank lines inside a block preserve a
        // paragraph break in the description.
        if trimmed.starts_with("Starting Nmap") || trimmed.starts_with("Nmap done") {
            continue;
        }
        if trimmed.is_empty() {
            if let Some(s) = current.as_mut() {
                s.description.push('\n');
            }
            continue;
        }

        if line == trimmed {
            // Column-zero line: a block header, category line, or URL line.
            if let Some(cats) = trimmed.strip_prefix("Categories:") {
                if let Some(s) = current.as_mut() {
                    s.categories = cats.split_whitespace().map(str::to_string).collect();
                }
                continue;
            }
            if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
                if let Some(s) = current.as_mut() {
                    if s.url.is_none() {
                        s.url = Some(trimmed.to_string());
                    }
                }
                continue;
            }
            // Otherwise a new script block header.
            if let Some(s) = current.take() {
                scripts.push(s);
            }
            current = Some(ScriptInfo {
                name: trimmed.to_string(),
                ..Default::default()
            });
        } else {
            // Indented line: description body.
            if let Some(s) = current.as_mut() {
                s.description.push_str(raw);
                s.description.push('\n');
            }
        }
    }

    if let Some(s) = current.take() {
        scripts.push(s);
    }

    for s in &mut scripts {
        s.description = s.description.trim_end().to_string();
    }
    scripts
}

/// Extract the script name from `NSE: Script 'foo' was not found!` lines.
fn extract_not_found_name(line: &str) -> Option<String> {
    let rest = line.strip_prefix("NSE: Script")?.trim();
    let rest = rest.strip_prefix('\'')?;
    let name = rest.split('\'').next()?;
    if name.is_empty() {
        None
    } else {
        Some(name.to_string())
    }
}

/// Match parsed blocks against the requested names, filling in `not_found`
/// entries for requested scripts nmap did not describe.
pub fn complete_with_requested(parsed: Vec<ScriptInfo>, requested: &[&str]) -> Vec<ScriptInfo> {
    let mut out = parsed;
    for name in requested {
        if !out.iter().any(|s| s.name == *name) {
            out.push(ScriptInfo {
                name: name.to_string(),
                not_found: true,
                ..Default::default()
            });
        }
    }
    out
}

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

    const SINGLE_HELP: &str = r#"Starting Nmap 7.95 ( https://nmap.org ) at 2026-08-08 21:20 CEST

http-title
Categories: default discovery safe
https://nmap.org/nsedoc/scripts/http-title.html
  Shows the title of the default page of a web server.

  The script will follow up to 5 HTTP redirects, using the default rules in the
  http library.
"#;

    #[test]
    fn parses_single_script_block() {
        let scripts = parse_script_help(SINGLE_HELP);
        assert_eq!(scripts.len(), 1);
        let s = &scripts[0];
        assert_eq!(s.name, "http-title");
        assert_eq!(s.categories, vec!["default", "discovery", "safe"]);
        assert_eq!(
            s.url.as_deref(),
            Some("https://nmap.org/nsedoc/scripts/http-title.html")
        );
        assert!(s
            .description
            .contains("Shows the title of the default page"));
        assert!(s.description.contains("follow up to 5 HTTP redirects"));
        assert!(!s.not_found);
        // Paragraph structure preserved as a double newline.
        assert!(s.description.contains("\n\n"));
    }

    const MULTI_HELP: &str = r#"Starting Nmap 7.95 ( https://nmap.org )

ssh-hostkey
Categories: default safe
https://nmap.org/nsedoc/scripts/ssh-hostkey.html
  Shows the SSH host keys of a target.

http-title
Categories: default discovery safe
https://nmap.org/nsedoc/scripts/http-title.html
  Shows the title of the default page of a web server.
"#;

    #[test]
    fn parses_multiple_blocks_in_order() {
        let scripts = parse_script_help(MULTI_HELP);
        assert_eq!(scripts.len(), 2);
        assert_eq!(scripts[0].name, "ssh-hostkey");
        assert_eq!(scripts[1].name, "http-title");
    }

    const NOT_FOUND_HELP: &str = r#"Starting Nmap 7.95 ( https://nmap.org )

NSE: Script 'no-such-script' was not found!
"#;

    #[test]
    fn marks_not_found_scripts() {
        let scripts = parse_script_help(NOT_FOUND_HELP);
        assert_eq!(scripts.len(), 1);
        assert_eq!(scripts[0].name, "no-such-script");
        assert!(scripts[0].not_found);
        assert!(scripts[0].description.is_empty());
    }

    #[test]
    fn completes_missing_scripts() {
        let parsed = parse_script_help(MULTI_HELP);
        let complete = complete_with_requested(parsed, &["ssh-hostkey", "http-title", "ghost"]);
        assert_eq!(complete.len(), 3);
        let ghost = complete.iter().find(|s| s.name == "ghost").expect("ghost");
        assert!(ghost.not_found);
    }

    #[test]
    fn categories_line_without_url_still_parses() {
        let text = "my-script\nCategories: safe vuln\n  Does a thing.\n";
        let scripts = parse_script_help(text);
        assert_eq!(scripts.len(), 1);
        assert_eq!(scripts[0].categories, vec!["safe", "vuln"]);
        assert_eq!(scripts[0].url, None);
        assert!(scripts[0].description.contains("Does a thing."));
    }

    #[test]
    fn to_json_shape() {
        let scripts = parse_script_help(SINGLE_HELP);
        let j = scripts[0].to_json();
        assert_eq!(j["name"], "http-title");
        assert_eq!(j["categories"][0], "default");
        assert_eq!(j["not_found"], false);
        assert!(j["description"]
            .as_str()
            .unwrap()
            .contains("Shows the title"));
    }
}