Skip to content

LayeSec006/pentest-mcp-server

Repository files navigation

Pentest MCP Server

Python 3.10+ License: MIT Tests

A production-ready Model Context Protocol (MCP) server that enables AI agents to perform autonomous penetration testing on ANY Linux distribution via SSH. Built with persistent tmux sessions, intelligent triggers, auto-reconnection, and comprehensive resource management.

πŸš€ Key Differentiator: Unlike other MCP servers that run commands independently, this server provides persistent session management with tmux, enabling complex interactive workflows and long-running operations.

πŸ“‹ Table of Contents

πŸ‘€ Connect

πŸŽ₯ Video Tutorial: Watch the complete walkthrough on YouTube

LinkedIn: Abdallah Ndiaye

πŸ–ΌοΈ Screenshots

Screenshot 1 Screenshot 2 Screenshot 3 Screenshot 4

🎯 Core Capabilities

This MCP server provides AI agents with persistent session control over ANY Linux distribution through SSH, enabling:

  • 🌍 Universal Compatibility: Works with Kali Linux, Parrot Security, BackBox, and ANY Linux distribution
  • πŸ”“ Zero Tool Limitations: Run ANY tool installed on the target system - no restrictions
  • πŸ”„ Persistent Sessions: Tmux-based sessions that survive disconnections and crashes
  • πŸ€– Intelligent Automation: AI suspension/resumption based on output patterns and triggers
  • ⚑ Auto-Reconnection: Automatic SSH reconnection with exponential backoff
  • πŸ“Š Resource Management: Smart limits on concurrent heavy operations
  • 🎯 Interactive Tools: Full support for msfconsole, mysql, reverse shells, and complex workflows
  • πŸ›‘οΈ Session Recovery: Recover all sessions after crashes or network issues

🎯 Key Features

Our Core Advantages:

  • πŸ”„ Session Persistence: Sessions survive disconnections and crashes
  • 🎯 Interactive Tool Support: Handle msfconsole, reverse shells, complex workflows
  • πŸ€– Intelligent Automation: AI suspension/resumption with smart triggers
  • ⚑ Auto-Reconnection: Automatic recovery from network issues
  • πŸ“Š Resource Management: Smart limits and system monitoring
  • 🌍 Universal Compatibility: Works with any Linux distribution

πŸ’‘ The Advantage: Our server provides persistent session management that enables complex, multi-step pentesting workflows with full interactive tool support.

🎯 Real-World Impact

What This Enables:

  • Complex Workflows: Multi-step pentesting operations that span hours
  • Interactive Tools: Full Metasploit automation, reverse shell management
  • Session Persistence: Long-running scans that survive network issues
  • Resource Management: Smart limits on concurrent operations
  • Universal Deployment: Works on any Linux distribution

Use Cases:

  • Red Team Operations: Automated reconnaissance and exploitation
  • CTF Challenges: Complex multi-step problem solving
  • Security Research: Long-running vulnerability assessments
  • AI-Assisted Pentesting: Intelligent automation of repetitive tasks

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   AI Agent          β”‚
β”‚   (Claude/ChatGPT)  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚ MCP Protocol
           β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   MCP Server        β”‚
β”‚   (Python)          β”‚
β”‚                     β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚Session Managerβ”‚  β”‚
β”‚  β”‚Auto-Reconnect β”‚  β”‚
β”‚  β”‚Resource Mgmt  β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚ SSH + PTY
           β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Pentest System    β”‚
β”‚   (Kali/Parrot/etc) β”‚
β”‚                     β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚    tmux       β”‚  β”‚
β”‚  β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚  β”‚
β”‚  β”‚  β”‚Session 1β”‚  β”‚  β”‚
β”‚  β”‚  β”‚Session 2β”‚  β”‚  β”‚
β”‚  β”‚  β”‚Session Nβ”‚  β”‚  β”‚
β”‚  β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸš€ Quick Start

Installation (5 minutes)

# 1. Clone repository
git clone https://github.com/LayeSec006/pentest-mcp-server.git
cd pentest-mcp-server

# 2. Install package
pip install -e .

# 3. Configure
cp .env.example .env
# Edit .env with your pentesting os details

# 4. Install tmux on target system
ssh kali@<TARGET_HOST>

# For Debian/Ubuntu/Kali/Parrot:
sudo apt update && sudo apt install tmux

# For Arch/BlackArch:
sudo pacman -S tmux

# For RHEL/CentOS/Fedora:
sudo yum install tmux
# OR for newer versions:
sudo dnf install tmux

# For Alpine Linux:
sudo apk add tmux

exit

# 5. Test
python -m pytest tests/ -v

Configuration

Create a .env file with your target system details:

# SSH Connection
TARGET_HOST=192.168.1.100
TARGET_PORT=22
TARGET_USER=kali
TARGET_PASSWORD=your_password
# OR use SSH key instead
# TARGET_SSH_KEY=/path/to/private/key

# Resource Limits
MAX_SESSIONS=20
MAX_HEAVY_TASKS=3

# Monitoring
POLL_INTERVAL=1.0
DEFAULT_TIMEOUT=300

πŸ€– AI Platform Integration

Claude Desktop Integration

Add to your Claude Desktop configuration:

Windows: %APPDATA%\Claude\claude_desktop_config.json
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Linux: ~/.config/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "pentest-mcp": {
      "command": "python",
      "args": ["-m", "pentest_mcp_server"],
      "env": {
        "TARGET_HOST": "192.168.1.100",
        "TARGET_USER": "kali", 
        "TARGET_PASSWORD": "your_password"
      }
    }
  }
}

Windsurf Integration

Add to your Windsurf settings:

{
  "mcpServers": {
    "pentest-mcp": {
      "command": "python",
      "args": ["-m", "pentest_mcp_server"],
      "env": {
        "TARGET_HOST": "192.168.1.100",
        "TARGET_USER": "kali",
        "TARGET_PASSWORD": "your_password"
      }
    }
  }
}

Cursor Integration

Add to your Cursor settings:

{
  "mcpServers": {
    "pentest-mcp": {
      "command": "python",
      "args": ["-m", "pentest_mcp_server"],
      "env": {
        "TARGET_HOST": "192.168.1.100",
        "TARGET_USER": "kali",
        "TARGET_PASSWORD": "your_password"
      }
    }
  }
}

5ire Integration

In 5ire:

  1. Click on Tools in the main interface
  2. Click the Local button
  3. Fill out the "Edit tool (Local Server)" form:
    • Tool Key: pentest-mcp
    • Name: Pentest MCP (optional)
    • Description: AI-powered penetration testing server (optional)
    • Approval Policy: Select Always (recommended)
    • Command: python -m pentest_mcp_server
    • Environment Variables:
      • TARGET_HOST = 192.168.1.100
      • TARGET_USER = kali
      • TARGET_PASSWORD = your_password
  4. Review the Config Preview to ensure it's correct
  5. Click Save
  6. Enable the tool: Hover over the pentest-mcp entry in the Tools list and click the toggle button that appears on the right to enable it

### Warp AI Integration

In Warp terminal:
1. Go to **Settings** (⌘ + ,)
2. Click on **AI** in the sidebar
3. Scroll down to find **Manage MCP**
4. Click **Add MCP**
5. Paste this JSON configuration:

```json
{
  "mcpServers": {
    "pentest-mcp": {
      "command": "python",
      "args": ["-m", "pentest_mcp_server"],
      "env": {
        "TARGET_HOST": "192.168.1.100",
        "TARGET_USER": "kali",
        "TARGET_PASSWORD": "your_password"
      }
    }
  }
}
  1. Click Save
  2. Restart Warp

πŸ”§ Quick Setup

Setup Steps

# 1. Clone and install
git clone https://github.com/LayeSec006/pentest-mcp-server.git
cd pentest-mcp-server
pip install -e .

# 2. Configure
cp .env.example .env
# Edit .env with your target system details

# 3. Test configuration
python -c "from pentest_mcp_server.config import Config; c = Config(); print('Config loaded:', c.TARGET_HOST)"

πŸš€ Advanced Capabilities

🎯 Interactive Tool Support

Start and interact with complex tools like Metasploit Framework:

{
  "tool": "execute",
  "args": {
    "session_id": "msf_session",
    "command": "msfconsole -q"
  }
}

Interact with the running tool:

{
  "tool": "send_input",
  "args": {
    "session_id": "msf_session",
    "input": "use exploit/multi/handler"
  }
}

πŸ”„ Reverse Shell Management

Handle incoming reverse shells seamlessly:

{
  "tool": "execute",
  "args": {
    "session_id": "reverse_shell",
    "command": "nc -lvp 4444"
  }
}

Interact with connected shells:

{
  "tool": "send_input",
  "args": {
    "session_id": "reverse_shell",
    "input": "whoami"
  }
}

πŸ“Š Complex Workflow Automation

Support for multi-step pentesting workflows:

  1. Network reconnaissance (nmap, masscan)
  2. Web application scanning (gobuster, nikto, dirb)
  3. Vulnerability exploitation (metasploit, custom exploits)
  4. Post-exploitation (meterpreter, privilege escalation)
  5. Data exfiltration (file operations, tunneling)

πŸ›‘οΈ Session Persistence & Recovery

Sessions survive network interruptions and crashes:

{
  "tool": "recover_sessions",
  "args": {}
}

Key Benefits:

  • Sessions continue running even if SSH connection drops
  • Automatic reconnection with exponential backoff
  • State preservation across network issues
  • Full recovery of interactive sessions

πŸ› οΈ MCP Tools

Session Management

Tool Description Purpose
create_session Create new persistent tmux session Start isolated workspace for pentesting tasks
list_sessions List all active sessions Monitor running operations
kill_session Terminate specific session Clean up completed tasks

create_session

Create a new persistent tmux session for isolated pentesting operations.

Parameters:

{
  "session_id": "scan_network",
  "shell": "bash"
}

list_sessions

List all active tmux sessions and their status.

Parameters:

{}

kill_session

Terminate a specific session and clean up resources.

Parameters:

{
  "session_id": "scan_network"
}

Command Execution

Tool Description Purpose
execute Execute commands in persistent sessions Run pentesting tools and scripts
read_output Get current output from session Monitor command progress and results
send_input Send input to interactive tools Control interactive applications

execute

Execute commands in persistent sessions.

{
  "session_id": "scan_network",
  "command": "nmap -sV 192.168.1.0/24",
  "background": false
}

read_output

Get current output from a session.

{
  "session_id": "scan_network",
  "lines": 50
}

send_input

Send input to interactive tools.

{
  "session_id": "msf_session",
  "input": "use exploit/multi/handler",
  "press_enter": true
}

System Management

get_system_status

Get system resource usage and session status.

{}

recover_sessions

Recover orphaned sessions after reconnection.

{}

File Operations

upload_file

Upload files to your system via SFTP.

{
  "local_path": "/path/to/local/file",
  "remote_path": "/tmp/uploaded_file"
}

download_file

Download files from your system via SFTP.

{
  "remote_path": "/tmp/scan_results.xml",
  "local_path": "/path/to/local/results.xml"
}

Tool Output Parsing

parse_tool_output

Parse common pentest tool outputs (nmap XML, JSON, etc.).

{
  "tool": "nmap",
  "file_path": "/tmp/scan.xml",
  "format": "xml"
}

πŸ’‘ Usage Examples

Basic Network Scan

AI: I need to scan the network 192.168.1.0/24

Tool: create_session
Args: {"session_id": "network_scan"}

Tool: execute  
Args: {
  "session_id": "network_scan",
  "command": "nmap -sV 192.168.1.0/24 -oX /tmp/scan.xml"
}

Tool: read_output
Args: {"session_id": "network_scan"}

Interactive Metasploit Usage

AI: Let me start Metasploit and set up a handler

Tool: create_session
Args: {"session_id": "metasploit"}

Tool: execute
Args: {
  "session_id": "metasploit", 
  "command": "msfconsole -q"
}

Tool: send_input
Args: {
  "session_id": "metasploit",
  "input": "use exploit/multi/handler"
}

Tool: send_input  
Args: {
  "session_id": "metasploit",
  "input": "set PAYLOAD linux/x64/meterpreter/reverse_tcp"
}

Tool: send_input
Args: {
  "session_id": "metasploit", 
  "input": "exploit"
}

Parallel Operations

AI: I'll run multiple scans in parallel

Tool: create_session
Args: {"session_id": "nmap_scan"}

Tool: create_session 
Args: {"session_id": "gobuster_scan"}

Tool: execute
Args: {
  "session_id": "nmap_scan",
  "command": "nmap -p- 192.168.1.5",
  "background": true
}

Tool: execute
Args: {
  "session_id": "gobuster_scan", 
  "command": "gobuster dir -u http://192.168.1.5 -w /usr/share/wordlists/dirb/common.txt",
  "background": true
}

πŸ”’ Security Features

Command Filtering (Optional)

The server can optionally block dangerous commands:

  • rm -rf / - Recursive delete from root
  • dd if=...of=/dev/sd* - Disk wiping commands
  • mkfs - Filesystem formatting
  • Fork bombs and other destructive patterns

πŸ§ͺ Testing

Run the test suite:

# Install test dependencies
pip install pytest pytest-asyncio pytest-mock

# Run tests
python -m pytest tests/ -v

# Run with coverage
python -m pytest tests/ --cov=pentest_mcp_server --cov-report=html

Test Categories

  • Unit Tests: Individual component testing
  • Integration Tests: End-to-end workflow testing
  • Connection Tests: SSH and reconnection scenarios
  • Session Tests: Tmux session management

πŸ“Š Monitoring & Debugging

Logging

The server provides detailed logging:

import logging
logging.basicConfig(level=logging.INFO)

Log levels:

  • INFO: Connection status, session creation/destruction
  • WARNING: Reconnection attempts, blocked commands
  • ERROR: Connection failures, command errors
  • DEBUG: Detailed protocol messages

System Status

Use the get_system_status tool to monitor:

  • CPU and memory usage
  • Active session count
  • Connection health
  • Recent command history

Session Recovery

After crashes or network issues:

Tool: recover_sessions
Args: {}

Response: {
  "status": "success",
  "recovered_sessions": [
    {
      "session_id": "network_scan",
      "age_seconds": 1800,
      "last_output": "...Nmap scan report..."
    }
  ]
}

πŸ”§ Advanced Configuration

Resource Management

# Limit concurrent heavy operations
MAX_HEAVY_TASKS=3

# Heavy commands that count against the limit
HEAVY_COMMANDS=nmap,masscan,hydra,john,hashcat,sqlmap

Connection Tuning

# Reconnection settings
MAX_RECONNECT_ATTEMPTS=5
RECONNECT_DELAY_BASE=2  # Exponential backoff base

# Health check interval  
POLL_INTERVAL=1.0

# Default command timeout
DEFAULT_TIMEOUT=300

Tmux Customization

# Custom tmux socket name
TMUX_SOCKET_NAME=mcp-pentest

# Session persistence location
TMUX_SESSION_PATH=/tmp/mcp-sessions

πŸ› Troubleshooting

Common Issues

Connection Refused

Error: Connection failed: [Errno 111] Connection refused
  • Verify SSH is running on your system: service ssh status
  • Check firewall rules: ufw status
  • Verify host/port in configuration

Authentication Failed

Error: Permission denied (publickey,password)
  • Verify username/password are correct
  • Check SSH key permissions (600)
  • Enable password auth: PasswordAuthentication yes in /etc/ssh/sshd_config

Tmux Not Found

Error: tmux is not installed on target system
  • Install tmux on your distro: apt update && apt install tmux

Session Lost

Error: Session 'scan_network' does not exist
  • Use recover_sessions tool to find orphaned sessions
  • Check if the system rebooted (sessions don't survive reboot)

Debug Mode

Enable verbose logging:

import logging
logging.getLogger('pentest_mcp_server').setLevel(logging.DEBUG)
logging.getLogger('asyncssh').setLevel(logging.DEBUG)

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Run tests (python -m pytest tests/)
  4. Commit changes (git commit -m 'Add amazing feature')
  5. Push to branch (git push origin feature/amazing-feature)
  6. Open a Pull Request

Development Setup

git clone <your-fork>
cd pentest_mcp_server
pip install -e .
pip install pytest pytest-asyncio pytest-mock

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

⚠️ Legal Disclaimer

This tool is intended for authorized security testing and educational purposes only. Users are responsible for ensuring they have proper authorization before using this tool against any systems. The developers are not responsible for any misuse or damage caused by this tool.

πŸ™ Acknowledgments


Happy Pentesting! πŸ”’πŸ”“