Skip to main content
Glama
mohdhaji87

Nmap MCP Server

by mohdhaji87

nmap_port_scan

Scan specific ports on target hosts to identify open services and assess network security using the Nmap MCP Server.

Instructions

Scan specific ports on target hosts

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
targetsYes
portsYes
scan_methodNosyn

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The handler function for the nmap_port_scan tool. It constructs Nmap arguments based on the scan_method (syn, connect, or udp) and executes the scan using the shared run_nmap_command helper.
    async def nmap_port_scan(
        targets: str,
        ports: str,
        scan_method: str = "syn"
    ) -> str:
        """Scan specific ports on target hosts."""
        if scan_method == "syn":
            args = ["-sS", "-p", ports, targets]
        elif scan_method == "connect":
            args = ["-sT", "-p", ports, targets]
        else:  # udp
            args = ["-sU", "-p", ports, targets]
        
        result = run_nmap_command(args)
        
        if result["success"]:
            return f"Port scan completed:\n\n{result['stdout']}"
        else:
            return f"Port scan failed:\n\n{result['stderr']}"
  • server.py:244-247 (registration)
    Registration of the nmap_port_scan tool using the FastMCP @app.tool decorator.
    @app.tool(
        name="nmap_port_scan",
        description="Scan specific ports on target hosts"
    )
  • Shared helper function used by all Nmap tools, including nmap_port_scan, to execute Nmap commands via subprocess and handle output, errors, and timeouts.
    def run_nmap_command(args: List[str], timeout: int = 300) -> Dict[str, Any]:
        """
        Execute an nmap command and return the results.
        
        Args:
            args: List of nmap command arguments
            timeout: Command timeout in seconds
        
        Returns:
            Dictionary containing command output, error, and exit code
        """
        try:
            # Construct the full nmap command
            cmd = ["nmap"] + args
            
            logger.info(f"Executing nmap command: {' '.join(cmd)}")
            
            # Run the command with timeout
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                timeout=timeout,
                check=False
            )
            
            return {
                "stdout": result.stdout,
                "stderr": result.stderr,
                "exit_code": result.returncode,
                "success": result.returncode == 0
            }
            
        except subprocess.TimeoutExpired:
            return {
                "stdout": "",
                "stderr": f"Command timed out after {timeout} seconds",
                "exit_code": -1,
                "success": False
            }
        except FileNotFoundError:
            return {
                "stdout": "",
                "stderr": "nmap command not found. Please ensure nmap is installed and in PATH",
                "exit_code": -1,
                "success": False
            }
        except Exception as e:
            return {
                "stdout": "",
                "stderr": f"Error executing nmap command: {str(e)}",
                "exit_code": -1,
                "success": False
            }
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. 'Scan specific ports' implies a read-only operation, but it doesn't address potential network impact, permissions required, rate limits, timeout behavior, or what constitutes a 'scan' (e.g., active probing vs. passive). For a network scanning tool with zero annotation coverage, this leaves critical behavioral traits unspecified.

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 wasted words. It's front-loaded with the core action and resource, making it easy to parse. Every word earns its place by conveying essential information without fluff.

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 network scanning (with potential for misuse or network impact), no annotations, 0% schema coverage, and multiple sibling tools, the description is incomplete. It doesn't address behavioral risks, parameter details, or differentiation from alternatives. The presence of an output schema helps with return values, but the overall context demands more guidance for safe and effective use.

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

Parameters2/5

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

Schema description coverage is 0%, meaning none of the 3 parameters (targets, ports, scan_method) have descriptions in the schema. The description mentions 'specific ports' and 'target hosts', which loosely maps to the 'ports' and 'targets' parameters but adds minimal semantic value—it doesn't explain format (e.g., comma-separated ports, CIDR ranges), defaults, or the meaning of 'scan_method' (with a default of 'syn'). The description fails to compensate for the lack of schema documentation.

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 'Scan specific ports on target hosts' clearly states the verb ('Scan') and resource ('specific ports on target hosts'), making the purpose immediately understandable. However, it doesn't explicitly differentiate this tool from its many siblings (like nmap_basic_scan, nmap_service_detection, etc.), which all involve scanning but with different scopes or focuses.

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. With 10 sibling tools available, including nmap_basic_scan and nmap_comprehensive_scan, the agent has no indication whether this is for targeted port scanning versus broader network discovery or other scan types. No context, exclusions, or prerequisites are mentioned.

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/mohdhaji87/Nmap-MCP-Server'

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