Skip to content

MCP server for controlling mitmproxy via Model Context Protocol

License

Notifications You must be signed in to change notification settings

bibibi-bug/mitmproxyMCP

Repository files navigation

mitmproxy MCP Server

A Python server that controls mitmproxy via Model Context Protocol (MCP), enabling natural language interaction with HTTP/HTTPS traffic.

中文文档

Features

Category Features Tools
Proxy Control Start/stop proxy, configure port and mode proxy_start proxy_stop proxy_status proxy_get_ca
Traffic View View, filter, search HTTP traffic flow_list flow_get flow_search
Interception Set breakpoints, pause/modify/resume traffic intercept_set intercept_clear flow_resume flow_kill flow_modify
Auto Rules Auto-modify request/response headers and content rule_add rule_remove rule_list rule_clear
Scripts Load custom mitmproxy addons script_load script_unload script_list
Export/Replay Export HAR/JSON, replay requests export_flows import_flows replay_request
WebSocket View WS connections and messages ws_list ws_get_messages ws_resume_message
Bot Protection Detect and analyze bot protection systems analyze_protection extract_json_fields

Quick Start

1. Install

From source:

git clone https://github.com/bibibi-bug/mitmproxyMCP.git
cd mitmproxyMCP
pip install -e .

Or install dependencies only:

pip install -r requirements.txt

2. Configure MCP Client

Note: Use absolute paths for run_server.py (e.g., /path/to/mitmproxyMCP/run_server.py).

Claude Desktop

File location:

  • Windows: %APPDATA%\Claude\claude_desktop_config.json
  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
{
  "mcpServers": {
    "mitmproxy": {
      "command": "python",
      "args": ["/path/to/mitmproxyMCP/run_server.py"]
    }
  }
}

With Web UI and auto-start:

{
  "mcpServers": {
    "mitmproxy": {
      "command": "python",
      "args": ["/path/to/mitmproxyMCP/run_server.py", "--auto-start", "--web-ui"]
    }
  }
}
Claude Code

Global config ~/.claude/settings.json:

{
  "mcpServers": {
    "mitmproxy": {
      "command": "python",
      "args": ["/path/to/mitmproxyMCP/run_server.py"]
    }
  }
}

Or project-level .mcp.json:

{
  "mcpServers": {
    "mitmproxy": {
      "command": "python",
      "args": ["/path/to/mitmproxyMCP/run_server.py"]
    }
  }
}
Cursor

File location: ~/.cursor/mcp.json

{
  "mcpServers": {
    "mitmproxy": {
      "command": "python",
      "args": ["/path/to/mitmproxyMCP/run_server.py", "--auto-start", "--web-ui"]
    }
  }
}
Configuration Examples

Basic:

{
  "mcpServers": {
    "mitmproxy": {
      "command": "python",
      "args": ["/path/to/mitmproxyMCP/run_server.py"]
    }
  }
}

With auto-start and Web UI:

{
  "mcpServers": {
    "mitmproxy": {
      "command": "python",
      "args": [
        "/path/to/mitmproxyMCP/run_server.py",
        "--auto-start",
        "--web-ui",
        "--port", "8080",
        "-o", "ssl_insecure=true"
      ]
    }
  }
}

With storage options (env required):

{
  "mcpServers": {
    "mitmproxy": {
      "command": "python",
      "args": ["/path/to/mitmproxyMCP/run_server.py", "--auto-start"],
      "env": {
        "MCP_LOAD_HISTORY": "0",
        "MCP_FLOW_BUFFER": "5000"
      }
    }
  }
}

3. Install CA Certificate

Generate certificate on first run:

mitmdump -p 8080
# Ctrl+C to exit

Install to system:

Windows
certutil -addstore -user Root "%USERPROFILE%\.mitmproxy\mitmproxy-ca-cert.cer"
macOS
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ~/.mitmproxy/mitmproxy-ca-cert.pem
Linux (Ubuntu/Debian)
sudo cp ~/.mitmproxy/mitmproxy-ca-cert.pem /usr/local/share/ca-certificates/mitmproxy-ca-cert.crt
sudo update-ca-certificates

4. Start Using

Restart your MCP client and say:

"Start a proxy on port 8080"


Command-Line Arguments

Argument Description Default
--auto-start Auto-start proxy on MCP server startup off
--port Proxy port 8080
--web-ui Enable mitmweb interface off
--web-port Web interface port 8081
--mode Proxy mode (regular/transparent/reverse/upstream) regular
-o, --option Custom mitmproxy option (can be used multiple times) -

Custom options examples:

{
  "mcpServers": {
    "mitmproxy": {
      "command": "python",
      "args": [
        "/path/to/mitmproxyMCP/run_server.py",
        "--auto-start",
        "--web-ui",
        "-o", "ssl_insecure=true",
        "-o", "connection_strategy=lazy"
      ]
    }
  }
}
Option Description
ssl_insecure=true Disable upstream SSL certificate verification
ignore_hosts=PATTERN Skip interception for matching hosts
connection_strategy=lazy Delay upstream connections

Natural Language Examples

Scenario Example
Start proxy "Start a proxy on port 8080"
View traffic "Show the last 10 requests"
Filter traffic "Any requests to api.example.com?"
Search content "Search for requests containing password"
Set interception "Intercept all requests to /api/login"
Modify request "Change the Authorization header to Bearer xxx and resume"
Add rule "Add X-Debug: true header to all requests"
Export data "Export traffic to HAR file"
Replay request "Replay that login request"
WebSocket "Show WebSocket message history"
Bot protection "Analyze that request for bot protection"
Extract JSON "Extract the user ID from the response JSON"

Tool Reference

Proxy Control

Tool Description Key Parameters
proxy_start Start mitmproxy instance port, mode, upstream_url, reverse_url, options, web_ui, web_port
proxy_stop Stop instance(s) instance_id (optional)
proxy_status Get running status instance_id (optional)
proxy_get_ca Get CA certificate -

Modes: regular (default), transparent, reverse, upstream

Tool Annotations:

  • proxy_start: openWorldHint=true
  • proxy_stop: destructiveHint=true, idempotentHint=true
  • proxy_status, proxy_get_ca: readOnlyHint=true

Traffic Operations

Tool Description Key Parameters
flow_list List flows with pagination filters, limit, offset
flow_get Get flow details flow_id
flow_search Search content query, scope

Filter fields: url, method, status, header, contains

Response format:

{
  "count": 150,
  "flows": [...],
  "has_more": true,
  "next_offset": 50
}

Interception Control

Tool Description Annotations
intercept_set Set interception filter openWorldHint=true
intercept_clear Clear filter(s) idempotentHint=true
flow_resume Resume paused flow openWorldHint=true
flow_kill Kill/abort flow destructiveHint=true
flow_modify Modify paused flow openWorldHint=true

Modify patch fields:

  • Request: method, url, path, headers, body, body_b64
  • Response: status_code, reason, headers, body, body_b64

Rule Management

Tool Description
rule_add Add auto-modification rule
rule_remove Remove rule by ID
rule_list List all rules
rule_clear Clear all rules

Rule structure:

{
  "scope": "request",
  "match": {"url": "api.example.com"},
  "action": "set_header",
  "name": "X-Debug",
  "value": "true"
}

Actions: set_header, remove_header, replace_body, replace_text (response only)

Script Management

Tool Description Parameters
script_load Load addon script path or source
script_unload Unload script script_id
script_list List loaded scripts -

⚠️ Warning: Scripts execute with full Python capabilities. Only load trusted code.

Natural language examples:

Action Example
Load from file "Load addon script from /scripts/my_addon.py"
Load inline "Load this script: [paste code]"
List scripts "Show loaded scripts"
Unload script "Unload the script xxx"

Loading methods:

  1. From file path:
script_load(path="/path/to/my_addon.py")
  1. From inline source:
script_load(source="...")

Script examples:

# Example 1: Add authentication header
from mitmproxy import http

def request(flow: http.HTTPFlow) -> None:
    if "api.example.com" in flow.request.pretty_host:
        flow.request.headers["Authorization"] = "Bearer my-token"
# Example 2: Modify response content
from mitmproxy import http

def response(flow: http.HTTPFlow) -> None:
    if flow.response and "application/json" in flow.response.headers.get("content-type", ""):
        flow.response.text = flow.response.text.replace('"debug":false', '"debug":true')
# Example 3: Log specific requests
from mitmproxy import http

def request(flow: http.HTTPFlow) -> None:
    if "/api/login" in flow.request.path:
        print(f"Login attempt: {flow.request.get_text()}")

Available mitmproxy hooks: request, response, websocket_message, tcp_message, etc. See mitmproxy docs.

Export & Replay

Tool Description Parameters
export_flows Export to JSON/HAR destination, filters
import_flows Import from file source
replay_request Replay request flow_id

WebSocket

Tool Description Parameters
ws_list List connections -
ws_get_messages Get messages flow_id, limit, offset
ws_resume_message Resume message message_id

Bot Protection Analysis

Tool Description Key Parameters
analyze_protection Detect bot protection systems flow_id, include_body, max_body_bytes, include_scripts
extract_json_fields Extract JSON from response body flow_id, scope, path, max_depth

Natural language examples:

Action Example
Analyze protection "Analyze that request for bot protection"
Extract JSON field "Extract the user ID from the response JSON"
Get JSON structure "Show the JSON structure of that response"
Extract nested data "Extract $.data.users from the response"

Detected systems: Cloudflare, Akamai, PerimeterX, DataDome, reCAPTCHA, hCaptcha, Incapsula, Kasada

Analysis includes:

  • Protection system identification with confidence scores
  • Challenge response detection (CAPTCHA, JavaScript)
  • Cookie analysis for protection-related cookies
  • Script analysis (fingerprinting, obfuscation level)
  • Remediation suggestions

Using with Proxifier

Proxifier can force any application through the proxy for system-wide traffic capture.

Setup

  1. Start proxy - Say: "Start proxy on port 8080"

  2. Add proxy in Proxifier

    • Profile → Proxy Servers → Add
    • Address: 127.0.0.1 / Port: 8080 / Protocol: HTTPS
  3. Add rule

    • Applications: Target app or Any
    • Action: Select proxy
  4. Exclusion rule (required)

    • Applications: mitmdump.exe; python.exe; pythonw.exe
    • Action: Direct

Project Structure

mitmproxy-mcp/
├── mitmproxy_mcp/
│   ├── __init__.py          # Package entry
│   ├── server.py             # MCP server with 27 tools
│   ├── models.py             # Pydantic input validation models
│   ├── addon.py              # mitmproxy addon for traffic interception & RPC
│   ├── proxy_manager.py      # mitmdump process management
│   ├── storage.py            # SQLite + in-memory ring buffer storage
│   ├── protection_analysis.py # Bot protection detection
│   └── json_utils.py         # JSON structure analysis
├── run_server.py             # Entry point
├── pyproject.toml            # Project metadata and dependencies
├── requirements.txt          # Dependencies
└── README.md

Architecture

┌─────────────┐     stdio/JSON    ┌──────────────┐
│  MCP Client │ ◄────────────────► │  MCP Server  │
│  (Claude)   │                    │  (FastMCP)   │
└─────────────┘                    └──────┬───────┘
                                          │
                  ┌───────────────────────┼───────────────────────┐
                  │                       │                       │
            ┌─────▼─────┐          ┌──────▼──────┐        ┌───────▼───────┐
            │  Storage  │          │ProxyManager │        │AddonRPCClient │
            │ (SQLite)  │          │(subprocess) │        │  (TCP RPC)    │
            └───────────┘          └──────┬──────┘        └───────┬───────┘
                                          │                       │
                                   ┌──────▼───────────────────────▼──────┐
                                   │            mitmdump                 │
                                   │        (mitmproxy addon)            │
                                   └─────────────────────────────────────┘

Environment Variables

Storage & Internal Settings

Variable Default Description
MCP_DB_PATH mitmproxy_mcp.sqlite3 Database path (see below)
MCP_FLOW_BUFFER 2000 In-memory buffer size
MCP_LOAD_HISTORY 1 Load history on startup (0=disable)
MCP_EVENT_HOST 127.0.0.1 Event receiver host
MCP_EVENT_PORT 8250 Event receiver port
MCP_RPC_HOST 127.0.0.1 RPC server host
MCP_RPC_PORT 8251 RPC server port

MCP_DB_PATH examples:

  • Relative: data/flows.sqlite3 (relative to working directory)
  • Linux/macOS: /home/user/data/mitmproxy.sqlite3
  • Windows: C:/Users/Admin/data/mitmproxy.sqlite3

Note: Use absolute paths for predictable file location. The directory will be created automatically if it doesn't exist.

Proxy Settings (prefer using args)

These can also be set via command-line arguments, which is the recommended approach.

Variable Default Equivalent Arg Description
MCP_AUTO_START 0 --auto-start Auto-start proxy (1=enable)
MCP_DEFAULT_PORT 8080 --port Default proxy port
MCP_DEFAULT_MODE regular --mode Proxy mode (regular/transparent/reverse/upstream)
MCP_DEFAULT_WEB_UI 0 --web-ui Enable Web UI (1=enable)
MCP_DEFAULT_WEB_PORT 8081 --web-port Web UI port
MCP_PROXY_OPTIONS {} -o key=value JSON format proxy options

Example:

{
  "mcpServers": {
    "mitmproxy": {
      "command": "python",
      "args": ["/path/to/mitmproxyMCP/run_server.py", "--auto-start", "--web-ui"],
      "env": {
        "MCP_LOAD_HISTORY": "0",
        "MCP_FLOW_BUFFER": "5000"
      }
    }
  }
}

Debugging

Enable verbose output:

{
  "mcpServers": {
    "mitmproxy": {
      "command": "python",
      "args": ["/path/to/mitmproxyMCP/run_server.py"],
      "env": {
        "PYTHONUNBUFFERED": "1"
      }
    }
  }
}

Common Issues

Issue Cause Solution
Failed to connect Port 8250/8251 in use Kill existing process: netstat -ano | findstr :8250
mitmdump not found mitmproxy not installed pip install mitmproxy
RPC timeout Addon not connected Check firewall settings
Certificate error CA not installed Install CA certificate (see Quick Start)

Development

# Install with dev dependencies
pip install -e ".[dev]"

# Run linter
ruff check .

# Run type checker
mypy mitmproxy_mcp

# Run tests
pytest

License

MIT

About

MCP server for controlling mitmproxy via Model Context Protocol

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages