Metasploit MCP Server

Metasploit MCP Server

Provides AI assistants with secure access to Metasploit Framework functionality through a standardized interface, enabling commands, exploit search, module info, and scanning.

Category
访问服务器

README

Metasploit MCP Server

A Model Context Protocol (MCP) server that provides AI assistants with secure access to Metasploit Framework functionality through a standardized interface. This server wraps core Metasploit capabilities into MCP tools that can be discovered and used by compatible clients.

Features

  • 🔧 Execute Metasploit commands - Run raw Metasploit commands with built-in security validation
  • 🔍 Search exploits - Find exploits by name, CVE, or keyword
  • 📋 Module information - Get detailed information about any Metasploit module
  • 📦 List modules - Browse available modules by type (exploits, auxiliaries, payloads, etc.)
  • 🌐 Network scanning - Run Nmap scans through Metasploit's database integration
  • 🔒 Vulnerability scanning - Execute vulnerability scans against target systems
  • ℹ️ Version information - Check your Metasploit installation details
  • 🛡️ Security controls - Input sanitization and command injection prevention

Requirements

  • Node.js 16.0.0 or higher
  • Metasploit Framework installed and accessible via command line (msfconsole)
  • MCP-compatible client (Claude Desktop, VS Code with MCP extension, etc.)

Installation

  1. Clone the repository:

    git clone https://github.com/RobertoDure/metasploit-mcp-server.git
    cd metasploit-mcp-server
    
  2. Install dependencies:

    npm install
    
  3. Verify Metasploit installation:

    msfconsole --version
    

Usage

Development Mode

npm run dev

Production Mode

npm start

The server communicates via STDIO transport, making it compatible with any MCP client that supports this transport method.

Available Tools

The MCP server exposes the following tools through the @modelcontextprotocol/sdk:

Tool Name Description Required Parameters Optional Parameters
execute-command Execute raw Metasploit commands with security validation command (string) None
search-exploit Search for exploits by name, CVE, or keywords query (string) None
module-info Get detailed information about a specific module modulePath (string) None
list-modules List available modules by type type (exploit|auxiliary|post|payload|encoder|nop) None
get-version Get Metasploit Framework version information None None
run-nmap-scan Execute Nmap scans through Metasploit's database target (string) options (string)
run-vuln-scan Run vulnerability scans using auxiliary modules target (string) None

Tool Details

execute-command

  • Executes any valid Metasploit command
  • Includes input sanitization to prevent command injection
  • Runs in quiet, non-interactive mode for consistent output
  • Timeout protection (30 seconds)

search-exploit

  • Searches Metasploit's exploit database
  • Supports CVE numbers, exploit names, and keywords
  • Returns formatted results with module paths and descriptions

module-info

  • Provides comprehensive module information
  • Includes options, targets, payloads, and references
  • Works with any module type (exploits, auxiliaries, etc.)

list-modules

  • Lists modules by category with validation
  • Supports all major module types
  • Returns organized module listings

run-nmap-scan

  • Integrates with Metasploit's database features
  • Supports custom Nmap options
  • Stores results in Metasploit database for further analysis

run-vuln-scan

  • Uses auxiliary scanner modules
  • Currently implements SMB MS17-010 (EternalBlue) scanning
  • Can be extended for additional vulnerability checks

Example Usage

When connected to an MCP-compatible client, you can interact with Metasploit using natural language:

Searching and Information:

  • "Search for Apache Log4j exploits"
  • "Show me details about the EternalBlue exploit (exploit/windows/smb/ms17_010_eternalblue)"
  • "List all available Windows payloads"
  • "What auxiliary modules are available?"

Scanning and Reconnaissance:

  • "Run an Nmap scan against 192.168.1.100"
  • "Perform a stealth scan on 10.0.0.0/24 with -sS -O options"
  • "Check if 192.168.1.50 is vulnerable to MS17-010"

System Information:

  • "What version of Metasploit am I running?"
  • "Execute the 'help' command to see available commands"

Sample Responses

The server returns structured JSON responses:

{
  "success": true,
  "output": "Metasploit Framework Console Output...",
  "command": "search apache"
}

Or in case of errors:

{
  "success": false,
  "output": "Command contains potentially dangerous characters",
  "error": "Security violation"
}

Architecture

The server follows a clean, modular architecture:

src/
├── index.js                     # Main MCP server with tool registrations
└── services/
    └── metasploit-service.js    # Metasploit Framework integration layer

tests/
└── metasploit-service.test.js   # Unit tests with Jest

Key Components

  • McpServer: Uses @modelcontextprotocol/sdk for MCP protocol implementation
  • MetasploitService: Encapsulates all Metasploit interactions with security controls
  • StdioServerTransport: Handles communication via STDIO for client compatibility
  • Zod Schemas: Provides runtime type validation for all tool inputs

Security Features

  • Input Sanitization: Removes dangerous shell characters (;&|$()`)
  • Command Validation: Ensures commands are non-empty strings
  • Timeout Protection: 30-second timeout on all command executions
  • Error Handling: Comprehensive error responses with structured formatting
  • Module Type Validation: Strict validation for module type parameters

Configuration

Package Configuration

The server is configured as an ES module with the following key settings:

{
  "name": "metasploit-mcp-server",
  "version": "1.0.0",
  "type": "module",
  "main": "src/index.js",
  "engines": {
    "node": ">=16.0.0"
  }
}

Dependencies

Production Dependencies:

  • @modelcontextprotocol/sdk (^1.12.0) - MCP protocol implementation
  • zod (^3.22.4) - Runtime type validation and schema definition

Development Dependencies:

  • jest (^29.7.0) - Testing framework with ES module support
  • eslint (^8.57.0) - Code linting and style enforcement

MCP Client Configuration

For Claude Desktop, add to your MCP settings:

{
  "mcpServers": {
    "metasploit": {
      "command": "node",
      "args": ["src/index.js"],
      "cwd": "/path/to/metasploit-mcp-server"
    }
  }
}

For VS Code with MCP extension:

{
  "mcpServers": {
    "metasploit-mcp-server": {
      "command": "npm",
      "args": ["start"],
      "cwd": "/path/to/metasploit-mcp-server"
    }
  }
}

Security Considerations

⚠️ Important Security Notice

This MCP server provides direct access to Metasploit Framework capabilities. Please observe these security guidelines:

🔒 Access Control

  • No built-in authentication - Consider adding authentication for production use
  • Local access recommended - Avoid exposing this server to untrusted networks
  • Principle of least privilege - Run with minimal required system permissions

🛡️ Built-in Security Features

  • Command sanitization - Prevents command injection attacks
  • Input validation - All parameters are validated using Zod schemas
  • Timeout protection - 30-second execution limits prevent hanging processes
  • Error isolation - Failures are contained and don't crash the server

⚖️ Legal and Ethical Considerations

  • Authorization required - Only use against systems you own or have explicit permission to test
  • Responsible disclosure - Follow responsible disclosure practices for discovered vulnerabilities
  • Compliance - Ensure usage complies with local laws and organizational policies
  • Documentation - Maintain records of authorized testing activities

🔧 Recommended Deployment Practices

  • Run in isolated/sandboxed environments
  • Use dedicated testing networks
  • Implement network-level access controls
  • Monitor and log all activities
  • Regular security updates for dependencies

🚨 Risk Awareness

  • Commands executed have the same privileges as the user running the server
  • Metasploit modules can perform invasive actions on target systems
  • Some modules may cause service disruption or system instability
  • Always test in non-production environments first

Development

Scripts

# Start in development mode with file watching
npm run dev

# Run production server
npm start

# Run tests with Jest
npm test

# Run tests in watch mode
npm run test:watch

# Lint code with ESLint
npm run lint

# Fix linting issues automatically
npm run lint:fix

Testing

The project includes comprehensive Jest tests:

# Run all tests
npm test

# Generate coverage report
npm test -- --coverage

# Watch mode for development
npm run test:watch

Test coverage includes:

  • ✅ Command execution validation
  • ✅ Security sanitization
  • ✅ Error handling
  • ✅ Module type validation
  • ✅ Input validation edge cases

Project Structure

metasploit-mcp-server/
├── src/
│   ├── index.js                   # MCP server entry point
│   └── services/
│       └── metasploit-service.js  # Metasploit integration
├── tests/
│   └── metasploit-service.test.js # Unit tests
├── package.json                   # Dependencies and scripts
├── jest.config.json              # Jest testing configuration
└── README.md                     # Documentation

Extending the Server

Adding New Tools

To add new Metasploit capabilities:

  1. Add a method to MetasploitService:

    async myNewFeature(param) {
      return this.executeCommand(`my_command ${param}`);
    }
    
  2. Register the tool in index.js:

    server.registerTool("my-new-tool", {
      title: "My New Tool",
      description: "Description of what it does",
      inputSchema: {
        param: z.string().describe("Parameter description")
      }
    }, async ({ param }) => {
      const result = await metasploitService.myNewFeature(param);
      return {
        content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
      };
    });
    
  3. Add tests:

    describe('myNewFeature', () => {
      it('should execute the new feature', async () => {
        // Test implementation
      });
    });
    

Custom Module Integration

For specific module integrations, you can create specialized methods:

async scanForWebVulns(target) {
  const commands = [
    `use auxiliary/scanner/http/dir_scanner`,
    `set RHOSTS ${target}`,
    `run`,
    `back`
  ].join('; ');
  
  return this.executeCommand(commands);
}

Error Handling Patterns

Follow the established error handling pattern:

if (!param || typeof param !== 'string') {
  return {
    success: false,
    output: 'Invalid parameter',
    error: 'Validation failed'
  };
}

Troubleshooting

Common Issues

Metasploit not found:

# Ensure Metasploit is in PATH
which msfconsole

# Or check installation
msfconsole --version

Permission errors:

# Check file permissions
ls -la src/index.js

# Ensure Node.js has execution rights
chmod +x src/index.js

Module import errors:

  • Verify "type": "module" is set in package.json
  • Use .js extensions in all import statements
  • Check Node.js version (requires >=16.0.0)

MCP client connection issues:

  • Verify STDIO transport is being used correctly
  • Check that the server starts without errors
  • Ensure the client configuration points to the correct path

Debug Mode

Enable debug logging by setting environment variables:

DEBUG=mcp* npm start

Performance Tuning

For better performance with large scans:

// Increase timeout for long-running operations
const { stdout, stderr } = await execAsync(fullCommand, { 
  timeout: 60000  // 60 seconds
});

License

MIT License - see LICENSE file for details.

Contributing

Contributions are welcome! Please follow these guidelines:

  1. Fork the repository and create a feature branch
  2. Write tests for new functionality
  3. Follow the existing code style (use ESLint)
  4. Update documentation as needed
  5. Submit a pull request with a clear description

Development Workflow

# Clone your fork
git clone https://github.com/yourusername/metasploit-mcp-server.git

# Install dependencies
npm install

# Create a feature branch
git checkout -b feature/new-tool

# Make changes and test
npm test
npm run lint

# Commit and push
git commit -m "Add new tool for X"
git push origin feature/new-tool

Code Standards

  • Use ES modules (import/export)
  • Follow JSDoc documentation style
  • Maintain test coverage above 80%
  • Use meaningful variable and function names
  • Handle errors gracefully with structured responses

Happy hacking! 🚀🔒

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选