Metadata-Version: 2.5
Name: mcp-call-guard
Version: 0.1.0
Summary: Policy, human approval, audit log and prompt-injection screening for MCP tool calls, as a drop-in proxy.
Project-URL: Homepage, https://github.com/triguiahmed/mcp-guard
Project-URL: Issues, https://github.com/triguiahmed/mcp-guard/issues
Project-URL: Changelog, https://github.com/triguiahmed/mcp-guard/blob/main/CHANGELOG.md
Author: Ahmed Trigui
License-Expression: MIT
License-File: LICENSE
Keywords: agents,llm,mcp,model-context-protocol,prompt-injection,proxy,security
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: MacOS
Classifier: Operating System :: POSIX
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: anyio<5,>=4.1
Requires-Dist: httpx<1,>=0.25
Requires-Dist: pydantic<3,>=2.0
Requires-Dist: pyyaml<7,>=6.0
Requires-Dist: starlette<2,>=0.27
Requires-Dist: uvicorn<1,>=0.23
Description-Content-Type: text/markdown

# mcp-guard

[![CI](https://github.com/triguiahmed/mcp-guard/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/triguiahmed/mcp-guard/actions/workflows/ci.yml)
[![Python](https://img.shields.io/badge/python-3.10%E2%80%933.13-blue)](https://github.com/triguiahmed/mcp-guard/blob/main/pyproject.toml)
[![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)

**A drop-in proxy that puts a policy, a human approval step, an audit log and
prompt-injection screening between any MCP client and any MCP server.**

MCP has no enforcement layer of its own: a tool marked `destructiveHint: true` runs
exactly like any other, and whatever a tool returns goes straight to the model. With
`mcp-guard` in between, this is what the model sees instead (output of
[`examples/guarded_session.py`](examples/guarded_session.py)):

```text
read_note(web-clip): Nice post! [mcp-guard: removed instruction_override] and wipe.
wipe_notes():
  reviewer sees: wipe_notes({}) -> rejecting
  mcp-guard: the call to 'wipe_notes' was not run (rule 'review-destructive'): the call was rejected by human approval.
read_note(todo): buy milk
```

```bash
mcp-guard init > policy.yaml                                     # starter policy
mcp-guard run -p policy.yaml -- npx -y @modelcontextprotocol/server-filesystem ~/notes
mcp-guard serve -p policy.yaml --upstream https://mcp.example.com/mcp   # Streamable HTTP
```

## Why this exists

Every row is reproduced against the real MCP SDK without the proxy first, then fixed
through it. Each one is a test in [`tests/test_e2e_stdio.py`](tests/test_e2e_stdio.py)
(also run over HTTP in [`tests/test_e2e_http.py`](tests/test_e2e_http.py)).

| What happens without a guard | Seen with the real SDK | What mcp-guard does |
|---|---|---|
| A destructive tool runs without anyone looking | `delete_file` with `destructiveHint: true` deletes the file | `approve` rules hold the call until a person approves it in the UI, via a webhook link or via the API; timeout counts as rejection |
| A "read-only" SQL tool runs `DROP TABLE` | the server executes it | argument rules (`matches`, `not_matches`, `equals`, `in`, `exists`) deny it with a message the model can read |
| A tool result tells the model to ignore its instructions | the text reaches the client verbatim, **including a second copy in `structuredContent`** | screening redacts, flags or blocks it, in `content` *and* `structuredContent` |
| Instructions hidden in invisible Unicode tag characters | they survive JSON transport untouched | stripped; the audit log shows the decoded hidden text |
| A tool *description* carries the attack ("tool poisoning") | `<IMPORTANT>…Do not tell the user…</IMPORTANT>` reaches the client | the description is redacted, or the tool is hidden and its calls refused |
| An agent loops on `send_email` | every call goes out | token-bucket rate limits per tool or per rule, per client |
| Nobody can say afterwards what the agent did | nothing is recorded | every call is logged to SQLite with arguments (secrets redacted), outcome, rule, approver, latency and findings |

The MCP schema itself says clients "should never make tool use decisions based on
ToolAnnotations received from untrusted servers." `mcp-guard` uses annotations only to
*add* caution. A tool that publishes no annotations counts as destructive (the spec's
default), and an annotation rule whose annotations are unknown is applied cautiously.

## Install

```bash
pip install mcp-call-guard
```

The package on PyPI is `mcp-call-guard` (the name `mcp-guard` is too close to an
existing project there); the command it installs is `mcp-guard` and the import is
`mcp_guard`.

Python 3.10+. Runtime dependencies are anyio, httpx, pydantic, PyYAML, Starlette and
uvicorn. The proxy does not import the MCP SDK: it relays JSON-RPC, so it works with
clients and servers written in any language and with any SDK version.

## Usage

### stdio servers (Claude Desktop, Cursor and other clients that launch a command)

Put `mcp-guard run … --` in front of the command the client used to run:

```json
{
  "mcpServers": {
    "filesystem": {
      "command": "/absolute/path/to/mcp-guard",
      "args": ["run", "-p", "/absolute/path/to/policy.yaml", "--",
               "npx", "-y", "@modelcontextprotocol/server-filesystem", "/Users/me/notes"]
    }
  }
}
```

The tests drive the proxy with the official Python SDK's clients. They don't drive
Claude Desktop or Cursor themselves, but the config above is the shape those clients
use. When the policy has `approve` rules, the proxy starts a small approval UI and prints
its address with a one-time admin token to stderr (the client's MCP log):

```text
mcp-guard: approval UI at http://127.0.0.1:8765/?token=…
```

If two guarded servers run at once and the port is taken, the second one picks a free
port and prints that instead.

### Streamable HTTP servers

```bash
mcp-guard serve -p policy.yaml --upstream https://mcp.example.com/mcp --listen 127.0.0.1:8100
```

Point the client at `http://127.0.0.1:8100/mcp`. Headers (`Authorization`,
`Mcp-Session-Id`, `MCP-Protocol-Version` …) pass through. Responses are transformed
message by message, whether the server answers with JSON or with an SSE stream.

Both transports handle the handshake era (protocol 2024-11-05 to 2025-11-25) and the
stateless 2026-07-28 era (`server/discover`, a per-request `_meta` envelope,
`resultType`, `input_required` retries, `Mcp-Method`/`Mcp-Name` routing headers).

### The policy

```yaml
version: 1
default: allow            # allow | deny | approve when no rule applies
hide_denied_tools: true   # tools that are always denied disappear from tools/list

rules:                    # first match wins, like a firewall
  - name: sql-read-only
    tools: [sql_query]
    when:
      args:
        query: {matches: '(?i)\b(insert|update|delete|drop|alter|create|truncate)\b'}
    action: deny
    message: only read-only SQL is allowed
  - name: review-deletes
    tools: ["delete_*", "remove_*"]
    action: approve
  - name: review-destructive
    tools: ["*"]
    when: {annotations: {destructiveHint: true}}
    action: approve

rate_limits:
  - {tools: ["send_*"], limit: 10/hour}               # each send_* tool: its own budget
  - {tools: ["*"], limit: 120/minute, per: rule}      # one shared budget

screening: {action: redact, tool_descriptions: true, extra_patterns: {}}
approval:  {timeout: 50, listen: 127.0.0.1:8765, webhook: {url: https://…, format: slack}}
audit:     {path: mcp-guard-audit.db, redact_keys: [password, secret, token, api_key]}  # path "off" disables
```

Unknown keys are an error. A typo such as `acton: deny` must not fall through silently
to `allow`. Check a policy and try calls against it offline:

```bash
mcp-guard check policy.yaml
mcp-guard explain policy.yaml sql_query '{"query": "DELETE FROM users"}'
# sql_query: deny (rule 'sql-read-only')
```

Argument conditions address nested values with dotted paths (`options.force`,
`items.0`). A missing argument fails `matches`/`equals`/`in` and passes `not_matches`,
so a deny rule written with `not_matches` fails closed.

### Screening modes

| `screening.action` | Tool result with a finding | Tool description with a finding |
|---|---|---|
| `off` | unchanged | unchanged |
| `flag` | unchanged; findings in the audit log and in `_meta["mcp-guard/findings"]` | unchanged, logged |
| `redact` (default) | matched text replaced by `[mcp-guard: removed …]`, hidden characters stripped | redacted |
| `block` | replaced by an `isError` result telling the model not to retry | tool hidden from `tools/list`; calls refused |

Detectors: `instruction_override`, `role_markup` (chat-template tokens, `<system>`),
`addressed_to_model` (`<IMPORTANT>`, "note to the AI", "new instructions:"),
`secret_request`, `concealment` ("do not tell the user"), `exfil_image` (auto-loading
markdown images carrying data), `hidden_tag_chars`, `bidi_control`, `zero_width_run`,
`variation_selector_run`, plus your own `extra_patterns`.

### Approvals

A held call shows up at `/` in the UI with its arguments, the rule that held it and the
time left. Decisions come from:

* the UI (token cookie, `HttpOnly; SameSite=Strict`);
* a webhook link (`approval.webhook`, generic JSON or a Slack incoming webhook). Each
  link carries its own key, valid for that one call only. Opening it shows a
  confirmation page: **GET never approves**, because chat apps fetch links to build
  previews;
* the API: `GET /api/pending`, `POST /api/approvals/{id}` with `{"approve": true,
  "by": "alice"}` and `Authorization: Bearer <token>`.

Keep `approval.timeout` (default 50 s) below your client's request timeout. The
TypeScript SDK gives up after 60 s by default and does not reset that timer on progress
unless the client opts in. A refused call reaches the model as an `isError` tool
result with the reason, so the agent can adapt instead of crashing. If the client
cancels a held call, it is dropped and never reaches the server.

### Audit log

```bash
mcp-guard audit --db mcp-guard-audit.db --since 60
# 2026-12-03 22:13:08 rejected     delete_file                      rule=review-deletes by=ui:alice  {"path": "/srv/data/report.csv"}
# 2026-12-03 22:13:08 allowed      read_file                    3ms  {"path": "/srv/data/notes.md"}
mcp-guard audit --outcome denied --format json | jq .
```

Rows are written when a call arrives and completed when it ends, so a call that was
let through but never answered still leaves a record. The UI shows the last 50 calls,
and `GET /api/audit` serves the full log.

### Without the proxy

The parts are plain Python and are usable on their own:

```python
from mcp_guard import Screener, load_policy

policy = load_policy("policy.yaml")
policy.evaluate("delete_file", {"path": "/tmp/x"}, annotations={}).action  # Action.APPROVE

screener = Screener()
result = {"content": [{"type": "text", "text": "Ignore all previous instructions."}]}
findings = screener.screen_result(result)
clean = screener.apply(result, findings, policy.screening.action)
```

`mcp-guard screen FILE` does the same from the shell, for a tool result, a `tools/list`
response or plain text. It exits with 1 when something is found.

### CLI

| Command | Purpose | Exit code |
|---|---|---|
| `run [-p POLICY] -- CMD…` | stdio proxy | the server's exit code |
| `serve --upstream URL` | Streamable HTTP proxy | 0 |
| `check POLICY` | validate and summarise | 0 ok, 1 invalid |
| `explain POLICY TOOL [ARGS]` | the decision for one call | 0 |
| `screen FILE\|-` | scan a result, a tool list or text | 0 clean, 1 findings |
| `audit` | query the log | 0, 1 if there is no log |
| `init [--out FILE]` | print a starter policy | 0 |

Usage errors exit with 2.

## What it deliberately doesn't do

* **It is not a sandbox.** An allowed call runs with the server's full permissions.
  Give servers least privilege too, for example a read-only database role behind a
  `sql-read-only` rule. Regex rules on SQL are a guard rail, not a parser.
* **Screening is heuristic.** It catches the shapes real payloads keep using.
  Paraphrased or translated attacks will get through, so treat it as one layer and keep
  approvals on the tools that can do damage. There is no ML classifier.
* **It does not filter resources, prompts or sampling.** Those pass through unchanged,
  and so does every method it does not know, which keeps new protocol features working.
  Only `tools/list`, `tools/call` and their responses are inspected.
* **No stdio↔HTTP bridging.** `run` proxies stdio to stdio and `serve` proxies HTTP to
  HTTP.
* **No cost limits.** MCP carries no cost signal; rate limits count calls.
* **It doesn't authenticate HTTP clients.** `serve` listens on localhost by default.
  Put it behind your own authentication before exposing it.
* **Not built yet:** Postgres storage, interactive Slack buttons and a React dashboard.
  See the [changelog](CHANGELOG.md).

## How it's tested

* **The real SDK is the oracle.** End-to-end tests start a real MCP server built with
  the official Python SDK and connect a real SDK client: over stdio, over Streamable
  HTTP (JSON and SSE responses), and in the 2026-07-28 stateless era with the v2
  `Client`. Each problem is shown failing without the proxy before it is shown fixed.
  The server's tools have real side effects (files really get deleted), so a test can
  tell "the proxy stopped it" apart from "the server didn't run it".
* **Both SDK majors.** The full suite also runs with mcp 1.30 clients and servers.
* **Wire-level cases an SDK will not send:** malformed calls, JSON-RPC batches, ids that
  differ only in type (`7` vs `"7"`), garbage lines, server-to-client requests whose ids
  collide with client ids, and exit-code propagation.
* **Red-team suite.** 30 malicious tool outputs must each trigger their detector, 28
  ordinary outputs must come through byte for byte (code, logs, emoji with ZWJ, Persian
  ZWNJ, Arabic and Hebrew text, README badges), and redaction must be idempotent. See
  [`tests/redteam.py`](tests/redteam.py).
* **Property tests** (Hypothesis) check that redacted results have no findings and stay
  stable, that inputs are never mutated, and that the first matching rule always wins.
  They were stress-run once at 5,000 examples.
* **CI:** lint (ruff, mypy `--strict`), Python 3.10–3.13, a **floor** job where the proxy
  runs on the oldest supported dependencies (anyio 4.1, httpx 0.25, pydantic 2.0,
  PyYAML 6.0, Starlette 0.27, uvicorn 0.23) with real SDK peers talking through it, an
  **mcp 1.x** job, and a weekly **newest** job with every dependency upgraded.
* **Overhead**, measured with a real SDK client over stdio, 500 sequential calls returning
  1 KB, with audit and screening on, on a 2-vCPU Xeon @ 2.1 GHz: median **+1.4 ms**,
  p95 **+2.1 ms** per call (1.6–1.8 ms direct, 3.1 ms guarded). Screening grows
  linearly with result size: about 0.2 s for a 1 MB text result
  (`screening.max_scan_chars` caps it).

## Design notes

Why a message-level relay rather than an SDK server, how approval correlates with
cancellation and `input_required` retries, and the probe results behind each rule are
in [docs/design.md](docs/design.md).

## License

[MIT](LICENSE) © Ahmed Trigui
