Metadata-Version: 2.4
Name: mcp-gate-firewall
Version: 0.1.1
Summary: Lightweight, 100% local runtime security proxy and policy firewall for MCP servers
Author: mcp-gate contributors
License-Expression: MIT
Project-URL: Homepage, https://github.com/anasmanaa29/mcp-gate
Project-URL: Repository, https://github.com/anasmanaa29/mcp-gate
Project-URL: Issues, https://github.com/anasmanaa29/mcp-gate/issues
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: PyYAML>=6.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: mypy>=1.10; extra == "dev"
Requires-Dist: types-PyYAML>=6.0.12; extra == "dev"
Dynamic: license-file

# mcp-gate

[![CI](https://github.com/anasmanaa29/mcp-gate/actions/workflows/ci.yml/badge.svg)](https://github.com/anasmanaa29/mcp-gate/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/mcp-gate-firewall.svg)](https://pypi.org/project/mcp-gate-firewall/)
[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
[![Typed: mypy --strict](https://img.shields.io/badge/typing-mypy%20--strict-1f6feb.svg)](https://mypy-lang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](./LICENSE)

**Runtime security proxy and declarative policy firewall for local Model Context Protocol (MCP) servers.**

`mcp-gate` sits transparently over `stdio` (JSON-RPC 2.0) between an AI coding agent (Claude Desktop, Cursor, Windsurf, custom MCP hosts) and any child MCP server. It enforces workspace path boundaries, tool allowlists/denylists, bidirectional credential leak prevention, indirect prompt-injection session taint latches, and cryptographic SHA-256 command & schema pinning — **100% locally and offline**, with `PyYAML` as its sole runtime dependency.

---

## Architecture

```mermaid
flowchart LR
    Agent["AI Coding Agent<br/>(MCP Client)"]
    subgraph Gate["mcp-gate (stdio JSON-RPC 2.0 Firewall)"]
        direction TB
        Proxy["Framing & ID Correlator"]
        Integrity["Integrity & Anti-Poisoning Guard<br/>(Command + ServerInfo + Tool SHA-256)"]
        Policy["Policy Engine<br/>(ACL + Taint Latch + Path Sandbox + Bidirectional Secrets)"]
        Audit["Secret-Safe Audit Logger<br/>(audit.jsonl)"]
        Proxy --> Integrity
        Proxy --> Policy
        Integrity --> Audit
        Policy --> Audit
    end
    Server["Upstream MCP Server<br/>(npx / uvx / python / binary)"]

    Agent <-->|"UTF-8 JSON-RPC\n(stdin / stdout)"| Proxy
    Proxy <-->|"Child Subprocess\n(piped stdio)"| Server
```

---

## Quickstart

### 1. Install

```bash
# From PyPI (installs the `mcp-gate` CLI):
pip install mcp-gate-firewall

# Or run directly without cloning via uvx:
uvx --from mcp-gate-firewall mcp-gate demo

# From source (editable install):
python -m venv .venv
# Linux / macOS:
source .venv/bin/activate
# Windows PowerShell:
.\.venv\Scripts\Activate.ps1

pip install -e .
```

### 2. Run the Built-In Live Attack Demo

Spin up `mcp-gate` in front of a built-in vulnerable MCP server to watch it block path traversal, credential exfiltration (in both `redact` and `block` modes), and a live mid-session rug-pull attack:

```bash
mcp-gate demo --audit audit.demo.jsonl
```

### 3. Pin Command, Identity & Tool Catalog (`mcp-gate lock` & `verify-config`)

Inspect an MCP server's `initialize` identity and `tools/list` definitions (including paginated `nextCursor` catalogs), scan descriptions and JSON schemas for hidden prompt-injection patterns, and pin canonical SHA-256 digests of both the server command and tool catalog:

```bash
mcp-gate lock --output mcp-gate.lock.json -- npx -y @modelcontextprotocol/server-filesystem .

# Verify in CI that an MCP server's live identity and tool catalog have not drifted:
mcp-gate lock --check --output mcp-gate.lock.json -- npx -y @modelcontextprotocol/server-filesystem .

# Verify in CI that .mcp.json has not been tampered with (command-swap / extra-arg drift):
mcp-gate verify-config --config .mcp.json --lock mcp-gate.lock.json
```

### 4. Enforce Policies at Runtime (`mcp-gate run`)

When `--lock` is passed, `mcp-gate run` verifies the server command/args against `mcp-gate.lock.json` **before** spawning the child subprocess:

```bash
mcp-gate run \
  --policy examples/policy.example.yaml \
  --lock mcp-gate.lock.json \
  --audit audit.jsonl \
  -- npx -y @modelcontextprotocol/server-filesystem .
```

---

## Drop-In MCP Client Configuration

Wrap any existing `npx`, `uvx`, or `python` MCP server entry in `.mcp.json`, `claude_desktop_config.json`, or `.cursor/mcp.json`:

```json
{
  "mcpServers": {
    "filesystem-hardened": {
      "command": "mcp-gate",
      "args": [
        "run",
        "--policy", "/abs/path/to/policy.yaml",
        "--lock", "/abs/path/to/mcp-gate.lock.json",
        "--audit", "/abs/path/to/audit.jsonl",
        "--",
        "npx", "-y", "@modelcontextprotocol/server-filesystem", "/abs/path/to/workspace"
      ]
    },
    "internal-python-tools": {
      "command": "mcp-gate",
      "args": [
        "run",
        "--policy", "/abs/path/to/policy.yaml",
        "--audit", "/abs/path/to/audit.jsonl",
        "--",
        "python", "-m", "my_org_mcp_server"
      ]
    }
  }
}
```

---

## Threat Model & Fail-Closed Error Contract

`mcp-gate` fails closed by default. When a request or response violates policy or integrity checks, execution is blocked and a structured JSON-RPC 2.0 error is returned to the client:

| Threat Vector | Defense Layer | Action | JSON-RPC Code |
| :--- | :--- | :--- | :--- |
| **Forbidden / Dangerous Tools** (`exec_*`, `delete_*`) | `ToolAccessPolicy` | Hidden from `tools/list` (`hide_denied_tools: true`) **and** blocked on `tools/call` (denylist overrides allowlist). | `-32001` (`ERR_POLICY_VIOLATION`) |
| **Indirect Prompt Injection (Untrusted Source -> Sink)** | `SessionTaintTracker` | Calling any tool matching `taint.untrusted_sources` latches the session as data-tainted and blocks subsequent calls to `taint.sensitive_sinks` (`category: taint_violation`). | `-32001` (`ERR_POLICY_VIOLATION`) |
| **Path Traversal & Symlink Escape** (`../../.env`, `/etc/passwd`, `%2e%2e`, symlinks/junctions, UNC/NT/ADS) | `PathSandbox` | Explicit path keys resolved via `Path.resolve()` against `allowed_roots`; nested strings scanned for traversal & outside-root paths. | `-32001` (`ERR_POLICY_VIOLATION`) |
| **`.mcp.json` Command Drift, Rug-Pull & Identity Spoofing** | `IntegrityGuard` + `verify-config` | Verifies `server_command_sha256` **pre-spawn**, `server_info` (`name`, `version`) on `initialize`, and tool SHA-256 digests against `mcp-gate.lock.json` + session TOFU hashes (including `__mcpgate_preflight_<N>` probes). | `-32002` (`ERR_INTEGRITY_VIOLATION`) |
| **Tool-Poisoning Prompt Injection** (`<IMPORTANT>`, hidden comments, Bidi/zero-width/homoglyph smuggling, stealth directives) | `scanner.py` | Recursively scans `description`, `inputSchema`, `outputSchema`, `annotations`, and JSON keys; blocks `lock` and taints runtime sessions. | `-32003` (`ERR_TOOL_POISONING`) |
| **Bidirectional Credential Exfiltration** (AWS keys, GitHub PATs, PEM keys, vendor keys, JWTs, DB URIs, `.env` secrets, UTF-8 base64) | `SecretScanner` | Blocks outbound secrets in `tools/call` arguments (`secrets.scan_requests: true`), and blocks (`action: "block"`, default) or redacts (`action: "redact"`) inbound responses and server notifications. | `-32004` (`ERR_SECRET_BLOCKED`) |
| **Memory Exhaustion via Unbounded Frame** | `transport.py` | Incremental bounded line framer rejects frames exceeding `--max-frame-bytes` (`10 MiB` default). | `-32005` (`ERR_FRAME_TOO_LARGE`) |

---

## Security Boundaries & Non-Goals

`mcp-gate` is an **MCP protocol-layer firewall**, not an OS kernel or container sandbox:

- **What `mcp-gate` protects against**:
  - **Prompt-injected or confused AI agents** attempting to read files outside the workspace, invoke dangerous tools, exfiltrate secrets outbound (raw or base64-encoded), or chain untrusted external inputs (`fetch_url`, `read_issue`) into privileged sinks (`create_issue`, `send_email`).
  - **`.mcp.json` configuration drift & supply-chain tampering** where server commands, flags, `serverInfo` metadata, or tool schemas/descriptions mutate unexpectedly after review (`mcp-gate lock` + `mcp-gate verify-config`).
  - **Accidental or protocol-level secret leakage** in MCP tool responses, structured outputs, error traces, and notifications.
- **What `mcp-gate` does NOT protect against (Non-Goals)**:
  - **Malicious server code bypassing MCP via direct OS syscalls**: Once a child MCP server process is spawned and receives an allowed `tools/call`, `mcp-gate` cannot stop native code inside that server from opening raw network sockets or reading arbitrary files directly via OS syscalls without reporting them over MCP.
  - **Arbitrary custom secret encodings or split-channel obfuscation**: Built-in secret detection inspects plaintext and UTF-8 decodable base64 spans; it cannot detect secrets deliberately transformed with custom encodings (e.g., hex, reversed strings, URL-encoded payloads, compression/encryption) or split character-by-character across multiple fields or calls.
  - **Defense-in-depth recommendation**: For untrusted third-party MCP server binaries or unverified packages, pair `mcp-gate` with OS-level isolation (Docker/Podman containers with read-only bind mounts and `--network none`, bubblewrap, Firecracker microVMs, or macOS Seatbelt profiles).

---

## Policy Configuration (`policy.yaml`)

See [`examples/policy.example.yaml`](./examples/policy.example.yaml) for a complete template. Unknown YAML keys fail closed on startup so typos never silently disable a security rule.

```yaml
version: "1"

tools:
  allowlist: ["read_file", "list_directory", "fetch_issue", "create_comment"]
  denylist: ["exec_*", "shell*"]
  hide_denied_tools: true

paths:
  enabled: true
  workspace_root: "."
  allowed_roots: ["."]
  scan_all_string_arguments: true

secrets:
  enabled: true
  action: "block"          # "block" (fail-closed default) or "redact" on responses
  scan_requests: true      # Block (-32004) outbound secrets in tools/call arguments
  custom_patterns:
    - id: "internal_token"
      description: "Internal service token"
      pattern: "\\bINT-[A-Z0-9]{24}\\b"
      action: "block"

taint:
  enabled: true
  untrusted_sources: ["fetch_*", "web_*"]
  sensitive_sinks: ["create_*", "send_*", "post_*"]

integrity:
  block_on_poisoning: true
  pin_session_tools: true
  allow_unpinned_tools: false
```

---

## Scope & Roadmap

- **v0.1.1 (Current)**: Secures local `stdio` JSON-RPC 2.0 MCP servers across Linux, macOS, and Windows — inspecting `tools/list`, `tools/call`, `resources/read`, and `prompts/get` (including JSON-RPC batch arrays, multi-page `nextCursor` pagination, `.mcp.json` verification, and secret-safe `audit.jsonl` telemetry).
- **v0.2.0 (Planned)**:
  - **Streamable HTTP and legacy SSE transport proxy** for remote MCP servers.
  - **Response Size / Token-Bloat Guard** to cap per-call response bytes/tokens and prevent context-window DoS or runaway token spend.
  - Per-tool JSON Schema argument constraint validation (`maxLength`, numeric bounds, regex patterns).

---

## Development & Verification

```bash
pip install -e ".[dev]"
python -m mypy --strict src tests
python -m pytest -v --tb=short
mcp-gate demo --audit audit.demo.jsonl
```

## License

Released under the [MIT License](./LICENSE).
