Skip to main content
Glama
imjdl

Nmap MCP Server

run-nmap-scan

Scan network targets for open ports and services using customizable Nmap options to identify security vulnerabilities and network configurations.

Instructions

Run an nmap scan on specified targets

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
targetYesTarget host or network (e.g., 192.168.1.1 or 192.168.1.0/24)
optionsNoNmap options (e.g., -sV -p 1-1000)

Implementation Reference

  • Main handler logic inside handle_call_tool for executing the 'run-nmap-scan' tool: validates input, checks rate limits and ongoing scans, runs nmap via subprocess, parses XML output using NmapParser, stores structured results globally, notifies of resource changes, and returns success message with scan ID.
    if name == "run-nmap-scan":
        target = arguments.get("target")
        options = arguments.get("options", "-sV")  # Default to version detection
    
        if not target:
            raise ValueError("Missing target")
            
        # Create a unique scan identifier based on target and options
        scan_key = f"{target}:{options}"
        
        # Check if an identical scan is already running
        if scan_key in ongoing_scans:
            return [
                types.TextContent(
                    type="text",
                    text=f"A scan with the same target and options is already running. Please wait for it to complete.",
                )
            ]
            
        # Check rate limiting
        if not check_rate_limit():
            return [
                types.TextContent(
                    type="text",
                    text=f"Rate limit exceeded. Please wait before starting another scan. Maximum {RATE_LIMIT_MAX_SCANS} scans per {RATE_LIMIT_PERIOD} seconds.",
                )
            ]
            
        try:
            # Mark this scan as ongoing
            ongoing_scans.add(scan_key)
            add_scan_timestamp()
            
            logger.info(f"Starting nmap scan on {target} with options {options}")
            
            # Use direct subprocess call instead of NmapProcess
            stdout, stderr = run_nmap_directly(target, options)
            
            if stderr:
                logger.error(f"Nmap scan failed: {stderr}")
                return [
                    types.TextContent(
                        type="text",
                        text=f"Nmap scan failed: {stderr}",
                    )
                ]
    
            # Parse results - convert bytes to string first
            try:
                xml_string = stdout.decode('utf-8', errors='replace')
                parsed = NmapParser.parse_fromstring(xml_string)
            except Exception as e:
                logger.error(f"Error parsing nmap results: {str(e)}")
                return [
                    types.TextContent(
                        type="text",
                        text=f"Error parsing nmap results: {str(e)}",
                    )
                ]
            
            # Generate a unique ID for this scan
            scan_id = str(uuid.uuid4())
            
            # Store scan results
            scan_results[scan_id] = {
                "target": target,
                "options": options,
                "timestamp": parsed.started,
                "hosts": [
                    {
                        "address": host.address,
                        "status": host.status,
                        "hostnames": [
                            hostname.name if hasattr(hostname, 'name') else str(hostname)
                            for hostname in host.hostnames
                        ],
                        "services": [
                            {
                                "port": service.port,
                                "protocol": service.protocol,
                                "state": service.state,
                                "service": service.service,
                                "banner": service.banner
                            }
                            for service in host.services
                        ]
                    }
                    for host in parsed.hosts
                ]
            }
            
            # Notify clients that new resources are available
            await server.request_context.session.send_resource_list_changed()
            
            logger.info(f"Scan completed. Found {len(parsed.hosts)} hosts. Scan ID: {scan_id}")
            
            return [
                types.TextContent(
                    type="text",
                    text=f"Scan completed. Found {len(parsed.hosts)} hosts. Scan ID: {scan_id}",
                )
            ]
        except Exception as e:
            logger.error(f"Error during nmap scan: {str(e)}")
            return [
                types.TextContent(
                    type="text",
                    text=f"Error during nmap scan: {str(e)}",
                )
            ]
        finally:
            # Remove from ongoing scans when done
            ongoing_scans.discard(scan_key)
  • Input schema for 'run-nmap-scan' tool defining 'target' as required string and 'options' as optional string.
        "type": "object",
        "properties": {
            "target": {"type": "string", "description": "Target host or network (e.g., 192.168.1.1 or 192.168.1.0/24)"},
            "options": {"type": "string", "description": "Nmap options (e.g., -sV -p 1-1000)"},
        },
        "required": ["target"],
    },
  • Registration of the 'run-nmap-scan' tool in the handle_list_tools function via types.Tool with name, description, and inputSchema.
        name="run-nmap-scan",
        description="Run an nmap scan on specified targets",
        inputSchema={
            "type": "object",
            "properties": {
                "target": {"type": "string", "description": "Target host or network (e.g., 192.168.1.1 or 192.168.1.0/24)"},
                "options": {"type": "string", "description": "Nmap options (e.g., -sV -p 1-1000)"},
            },
            "required": ["target"],
        },
    ),
  • Helper function that executes the nmap command using subprocess.Popen equivalent via run, capturing XML output for parsing.
    def run_nmap_directly(target, options):
        """Run nmap directly using subprocess instead of relying on python-libnmap."""
        try:
            # Construct the basic command with XML output
            cmd = [NMAP_PATH, "-oX", "-"]
            
            # Split options into separate arguments
            if options:
                option_args = options.split()
                cmd.extend(option_args)
                
            # Add target at the end
            cmd.append(target)
            logger.info(f"Executing nmap command: {' '.join(cmd)}")
            
            # Run the command and capture both stdout and stderr
            process = subprocess.run(
                cmd,
                capture_output=True,
                text=False,
                check=True
            )
            
            return process.stdout, None
        except subprocess.CalledProcessError as e:
            return None, f"nmap failed with exit code {e.returncode}: {e.stderr.decode('utf-8', errors='replace')}"
        except Exception as e:
            return None, str(e)
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the action ('Run an nmap scan') but doesn't describe what this entails—such as network impact, execution time, permission requirements, or output format. For a tool that likely performs network scanning, this is a significant gap in transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with zero waste—it directly states the tool's purpose without unnecessary details. It's appropriately sized and front-loaded, making it easy for an agent to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of running an nmap scan (a network operation with potential side effects), the description is incomplete. With no annotations, no output schema, and minimal behavioral context, it fails to provide enough information for safe and effective use. The agent lacks details on execution behavior, results, or error handling.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents both parameters ('target' and 'options') with clear descriptions. The description adds no additional meaning beyond what the schema provides, such as example usage or constraints, resulting in a baseline score of 3.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb ('Run') and resource ('nmap scan on specified targets'), making the purpose immediately understandable. It doesn't differentiate from sibling tools like 'get-scan-details' or 'list-all-scans', which are clearly different operations, so it doesn't need explicit sibling differentiation for a 5.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites like network access or permissions, nor does it explain when to choose this over siblings like 'get-scan-details' or 'list-all-scans'. This lack of context leaves the agent with minimal usage direction.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/imjdl/nmap-mcpserver'

If you have feedback or need assistance with the MCP directory API, please join our Discord server