Skip to main content
Glama
mcp-security-mitmproxy
by dandgabr

mcp-security-mitmproxy

MCP (Model Context Protocol) server exposing the mitmproxy ecosystem (mitmdump, mitmweb, and mitmproxy) to AI agents.

Designed to allow LLMs and autonomous agents to intercept, inspect, modify, and replay HTTP, WebSocket, TCP, and UDP traffic under controlled security constraints and process isolation.


๐Ÿ—๏ธ Architecture

The server uses a hybrid architecture: it runs mitmweb or mitmdump inside managed subprocesses with deterministic teardown (app_lifespan), while flow observation happens over an authenticated asynchronous REST bridge (MitmwebClient). Offline analysis and export of saved dumps execute in-process without allocating network ports.

flowchart TB
    Agent["AI Agent (Claude, Cursor, Antigravity)"]

    subgraph Server["MCP Server (FastMCP 4.x)"]
        Tools["18 MCP Tools (Dump, Web, Core, Rules)"]
        Registry["SessionRegistry (Deterministic Lifecycle)"]
        RESTClient["MitmwebClient (Async REST Bridge)"]
        Redactor["Redaction Engine (core/redact.py - R4)"]
        OfflineMgr["FlowsManager (FlowReader + FlowFilter + Export)"]
    end

    subgraph Subprocesses["Managed Subprocesses"]
        WebProc["mitmweb (Proxy + REST API on port 8081)"]
        DumpProc["mitmdump (Headless Streaming Capture)"]
    end

    Agent -->|"MCP stdio (JSON-RPC)"| Tools
    Tools --> Registry
    Tools --> RESTClient
    Tools --> OfflineMgr
    RESTClient --> Redactor
    Registry -->|"spawn / terminate"| WebProc
    Registry -->|"spawn / terminate"| DumpProc
    RESTClient -->|"HTTP REST (Bearer Token)"| WebProc

Related MCP server: nodriver-proxy-mcp

โšก Prerequisites and Installation

The project requires Python 3.13+ and uses uv for package and virtual environment management.

# Clone repository
git clone https://github.com/dandgabr/mcp-security-mitmproxy.git
cd mcp-security-mitmproxy

# Sync virtual environment and dependencies
uv sync

# Activate virtual environment (optional when using 'uv run')
source .venv/bin/activate

๐Ÿš€ Usage

1. Starting the MCP Server via stdio

Run the server as a child process for MCP clients (Claude Desktop, Cursor, Zed, Antigravity):

uv run mcp-security-mitmproxy

Or via Python module:

uv run python -m mcp_security_mitmproxy

2. MCP Client Configuration

Claude Desktop (claude_desktop_config.json)

{
  "mcpServers": {
    "mitmproxy": {
      "command": "uv",
      "args": [
        "--directory",
        "/absolute/path/to/mcp-security-mitmproxy",
        "run",
        "mcp-security-mitmproxy"
      ],
      "env": {
        "MCP_MITM_WEB_HOST": "127.0.0.1",
        "MCP_MITM_WEB_PORT": "8081"
      }
    }
  }
}

Cursor (.cursor/mcp.json)

{
  "mcpServers": {
    "mitmproxy": {
      "command": "uv",
      "args": [
        "--directory",
        "/absolute/path/to/mcp-security-mitmproxy",
        "run",
        "mcp-security-mitmproxy"
      ]
    }
  }
}

Zed (~/.config/zed/settings.json)

{
  "context_servers": {
    "mitmproxy": {
      "command": {
        "path": "uv",
        "args": [
          "--directory",
          "/absolute/path/to/mcp-security-mitmproxy",
          "run",
          "mcp-security-mitmproxy"
        ]
      }
    }
  }
}

โš™๏ธ Environment Variables and Settings

Runtime configuration is handled in config.py:

Variable

Default

Description

MCP_MITM_WEB_HOST

127.0.0.1

Bind address for mitmweb REST/Web UI interface (R1).

MCP_MITM_WEB_PORT

8081

HTTP port for web interface and REST bridge.


๐Ÿ› ๏ธ Catalog of 18 MCP Tools

The tools are grouped into four operational categories:

1. mitmdump Controls (Headless & Capture)

  • mitmdump_start: Starts a headless traffic capture session with one or more proxy modes (regular, reverse, upstream, etc.), optional .mitm dump saving, and Python addon scripts.

  • mitmdump_stop: Deterministically terminates an active proxy session and releases allocated ports.

  • mitmdump_replay: Replays captured flows from dump files using client replay (-C) or server replay (-S).

2. mitmweb Controls (Interactive Inspection & REST)

  • mitmweb_start: Starts a proxy session with web UI and REST API enabled. Generates a local cryptographic authentication token.

  • mitmweb_stop: Stops the mitmweb session, closing both proxy and REST endpoints.

  • mitmweb_get_flows: Returns a paginated list of captured flows (FlowSummary) with method, host, path, HTTP status, and duration.

  • mitmweb_get_flow_detail: Retrieves full flow details (headers, payloads, and WebSocket messages) with automatic secret redaction enabled by default (R4).

3. Core Commands and Offline Operations (core)

  • session_list: Lists all registered sessions (running, stopped, or failed).

  • session_status: Returns operational runtime details for a session by UUID.

  • mitm_execute_command: Runs allowlisted mitmproxy commands on active sessions (such as view.clear, flow.kill, flow.resume). Commands outside the allowlist are denied (R3).

  • mitm_export_flow: Exports a flow to curl, httpie, or raw formats, either from an active session dump or directly from a .mitm file.

  • mitm_filter_flows: Evaluates FlowFilter syntax expressions (~u /api/, ~m POST, ~c 200, ~b json) over offline dumps or live sessions.

4. Codeless Traffic Manipulation & Rules (rules โ€” Phase 4)

  • mitm_set_map_remote: Redirects requests matching a URL regex pattern to a remote destination.

  • mitm_set_map_local: Serves mocked responses from allowlisted local files, guarded against Local File Inclusion (LFI - R3) via allowed_mock_roots.

  • mitm_modify_headers: Injects, alters, or removes HTTP headers on requests and responses, enforced with RFC 9110 token validation and rejection of unsafe @file syntax.

  • mitm_modify_body: Replaces request or response payload fragments using regex patterns (DOTALL) without disk access.

  • mitm_list_rules: Lists active traffic mutation rules organized by family with match counters.

  • mitm_clear_rules: Clears active rules for a specific family or resets all mutation families atomically.


๐Ÿ”’ Security Model and Safeguards

The server enforces strict controls against unauthorized access and credential leakage:

  1. R1 โ€” Restricted Network Binding: Default web_host is 127.0.0.1. Non-loopback bindings (0.0.0.0) require explicit parameters and trigger audit warnings.

  2. R2 โ€” Key Isolation and Session Protection: Web tokens are generated using secrets.token_hex(16) and stored in config.yaml (0600 permissions) inside per-session isolated directories (0700 permissions), avoiding exposure in /proc/<pid>/cmdline.

  3. R3 โ€” Strict Allowlist for Paths and Commands: Paths for .mitm dumps, addon scripts, and mocks pass through ensure_allowed(), resolving symlinks and blocking directory traversal (PATH_NOT_ALLOWED). In-process command execution is restricted to ALLOWED_COMMANDS (COMMAND_NOT_ALLOWED). Raw option overrides through --set block reserved options (confdir, scripts, map_local, etc.).

  4. R4 โ€” Automatic Secret Redaction: Inspection tools sanitize authentication headers (Authorization, Cookie, X-API-Key) and apply regex matching across text bodies to mask tokens and passwords ([REDACTED]) by default.

  5. R5 โ€” No Implicit Privilege Escalation: Modes requiring elevated kernel permissions (such as eBPF local mode or tun) fail explicitly with configuration instructions rather than attempting automatic privilege escalation.


๐Ÿงช Testing, Quality, and Packaging

Code integrity is verified through unit, adversarial, and live integration tests:

# Run test suite
uv run pytest

# Run tests with coverage report
uv run pytest --cov=mcp_security_mitmproxy

# Run type and lint checks
uv run ruff check

# Verify code formatting
uv run ruff format --check

# Build distributable artifacts (wheel and sdist)
uv build

๐Ÿ“š Technical Documentation

User Guide (docs/user-guide/)

  • Getting Started โ€” install, launch, first capture session.

  • Tools Reference โ€” all 18 MCP tools: inputs, outputs, errors, examples.

  • Configuration โ€” environment variables, settings, filesystem allowlists.

  • Security Model โ€” R1โ€“R5 enforcement, reserved options, error handling.

  • Secrets Handling โ€” redaction engine, token lifecycle, on-disk artifacts.

Architecture and ADRs


๐Ÿ“„ License

This project is licensed under the terms of the MIT License.

Available Tools

18 tools
mitm_clear_rulesMitm Clear RulesA

Clear active rules. Pass rule_type to clear one family, or omit it to clear all four.

Inputs: params (required). Returns: ok, error, remaining, cleared_count

mitmdump_replayMitmdump ReplayC

Replay flows through mitmdump using client (-C) or server (-S) replay from existing .mitm dump files.

Inputs: params (required). Returns: ok, error, session

mitmdump_startMitmdump StartB

Start a headless mitmdump capture session with explicit proxy modes, optional .mitm output saving, flow filtering and scripts.

Inputs: params (required). Returns: ok, error, session

mitmdump_stopMitmdump StopB

Stop an active mitmproxy/mitmdump/mitmweb session and release ports.

Inputs: params (required). Returns: Single return envelope. Every tool returns this (invariant I1).

mitm_execute_commandMitm Execute CommandC

Execute an allowlisted command on an active mitmweb session (e.g. view.clear, flow.kill).

Inputs: params (required). Returns: ok, error, result, stdout

mitm_export_flowMitm Export FlowA

Export a captured flow to an external format (curl, httpie, raw, raw_request, raw_response) from an active session's dump or directly from a .mitm dump file. The exported content has secrets redacted (R4).

Inputs: params (required). Returns: ok, error, format, content

mitm_filter_flowsMitm Filter FlowsB

Filter flows using mitmproxy FlowFilter expressions (~u, ~m, ~c, ~b, ~h, ~d, etc.) evaluated either from a .mitm dump file or from an active session.

Inputs: params (required). Returns: ok, count, error, matched

mitm_list_rulesMitm List RulesC

List the active map_remote/map_local/modify_headers/modify_body rules.

Inputs: params (required). Returns: ok, error, rules, counts

mitm_modify_bodyMitm Modify BodyB

Regex-substitute inside matching request/response payloads (mitmproxy modify_body, DOTALL).

Inputs: params (required). Returns: ok, error, rule_id, rendered_spec

mitm_modify_headersMitm Modify HeadersC

Set or remove an HTTP header on matching requests/responses (mitmproxy modify_headers).

Inputs: params (required). Returns: ok, error, rule_id, rendered_spec

mitm_set_map_localMitm Set Map LocalA

Serve a mocked response for requests matching a URL regex from a local file or directory. The path MUST be inside allowed_mock_roots (R3).

Inputs: params (required). Returns: ok, error, rule_id, rendered_spec, +1 more

mitm_set_map_remoteMitm Set Map RemoteB

Redirect requests matching a URL regex to another remote URL (mitmproxy map_remote). Applied live over mitmweb.

Inputs: params (required). Returns: ok, error, rule_id, rendered_spec

mitmweb_get_flow_detailMitmweb Get Flow DetailA

Fetch detailed inspection data for a single flow from mitmweb, including headers, payloads and content views, with automatic secret redaction.

Inputs: params (required). Returns: ok, error, detail

mitmweb_get_flowsMitmweb Get FlowsC

Retrieve captured flows (HTTP/WebSocket/TCP/UDP) from a running mitmweb session.

Inputs: params (required). Returns: ok, error, flows, total

mitmweb_startMitmweb StartC

Start an interactive mitmweb proxy session with web UI and REST API bridge enabled.

Inputs: params (required). Returns: ok, error, session, web_url

mitmweb_stopMitmweb StopB

Stop an active mitmweb session and release listen and web ports.

Inputs: params (required). Returns: Single return envelope. Every tool returns this (invariant I1).

session_listSession ListA

List all active, stopped and managed mitmproxy sessions.

Inputs: no named parameters. Returns: ok, error, sessions

session_statusSession StatusB

Get the detailed status and runtime parameters of a session by ID.

Inputs: params (required). Returns: ok, error, session

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelogโ€ฆ

    TDQS

    B3.2/5.0

    Scored across 18 tools

    Disambiguation5/5

    Every tool targets a distinct mitmproxy operation: session lifecycle, flow inspection/export/filtering, and rule management are cleanly separated. Even similarly named start/stop tools are disambiguated by mitmdump vs mitmweb mode, and the rule tools map clearly to remote/local/header/body mutations.

    Naming Consistency4/5

    Most tools follow a verb_noun pattern under a mitm/mitmdump/mitmweb prefix, e.g. get_flows, export_flow, clear_rules. The noun-first session_list and session_status tools deviate slightly, and get vs list is mixed across tools, but the overall pattern remains predictable.

    Tool Count3/5

    At 18 tools, this is above the ideal 3โ€“15 range and feels heavy, though the tools are not redundant. The count is justified by the breadth of mitmproxy functionality but still pushes the server into the 'heavy' band.

    Completeness4/5

    The server covers the complete proxy workflow: start/stop sessions, replay, retrieve/filter/export flows, and apply map/modify rules. Minor gaps remain, such as no direct intercept/breakpoint controls or explicit session/dump cleanup, but agents can work around these with the provided command and rule tools.

    Maintenance

    ActivitySlowing
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers