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
| Name | Required | Description | Default |
|---|---|---|---|
| target | Yes | Target host or network (e.g., 192.168.1.1 or 192.168.1.0/24) | |
| options | No | Nmap options (e.g., -sV -p 1-1000) |
Implementation Reference
- src/nmap_mcp/server.py:236-349 (handler)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)
- src/nmap_mcp/server.py:152-158 (schema)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"], },
- src/nmap_mcp/server.py:149-159 (registration)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"], }, ),
- src/nmap_mcp/server.py:197-225 (helper)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)