mcp-grant-proxy
README.md
# mcp-grant-proxy
A small stdio MCP proxy that holds a tenant's secret so your agent never does,
signs a **fresh, single-use, tool-bound, short-lived HMAC grant for every
upstream request**, and records a redacted capsule of what each call actually
did.
Pure Python standard library. No runtime dependencies, no SDK pin.
```console
$ pip install "git+https://github.com/MarkLernReBar/mcp-grant-proxy.git"
$ mcp-grant-proxy # one tenant, fixed at startup
$ mcp-multi-tenant-proxy # every tenant, namespaced by name
# or from a checkout, with dev tooling and no runtime dependencies:
$ git clone https://github.com/MarkLernReBar/mcp-grant-proxy.git
$ cd mcp-grant-proxy && pip install -e ".[dev]"
$ PYTHONPATH=src python3 -m mcp_grant_proxy.cli # single
$ PYTHONPATH=src python3 -m mcp_grant_proxy.cli multi # multi-tenant
```
---
## Demo Video
[](assets/demo.mp4)
*[Watch the 16-second mechanics-to-value demo (MP4)](assets/demo.mp4)*
## The problem
An MCP client is a process you do not fully control: it loads tools, it reads
files, and it runs whatever a model decides to call. Give that process a bearer
secret and every prompt-injected tool call, crash dump, and debug log line
becomes a credential-exfiltration path. Give it nothing and it cannot work.
A proxy inverts the trust relationship:
```mermaid
flowchart LR
A["MCP client<br/>(agent)<br/>sees: tool catalog + results"]
P["grant proxy<br/>(holds the tenant secret)<br/>sees: secret, minted grants"]
S["upstream MCP server<br/>(verifies)<br/>sees: one grant"]
A <-->|"stdio JSON-RPC"| P
P -->|"HTTPS + single-use grant"| S
```
The client's blast radius becomes *the tools this proxy exposes, for this
tenant, until the caps are hit* — and every one of those limits is enforced
before an upstream request is made.
Three properties are worth calling out, because each one is a real failure mode
in agent systems:
* **Single use.** A captured grant cannot be replayed. Each request gets a new
nonce, and the verifier consumes it atomically.
* **Tool bound.** A grant for `search` cannot be used to call `admin_delete`,
even though both are on the same connection.
* **Short lived.** Ninety seconds by default, hard ceiling 300. A leaked grant
is a nuisance, not a session.
One call, end to end:
```mermaid
sequenceDiagram
autonumber
participant A as Agent (untrusted)
participant P as Grant proxy (holds secret)
participant S as Upstream MCP server
A->>P: tools/call "search"
Note over P: Rails first — allow-list, call cap,<br/>wall-clock cap, size cap.<br/>A refused call costs zero upstream bytes.
P->>P: mint grant — tenant, tool, run_id,<br/>fresh nonce, at most 300 s
P->>S: tools/call + Authorization: grant
S->>S: structure, then signature, then window,<br/>then tool binding, then contract digest,<br/>then privileges
S->>S: consume nonce last, atomically
S-->>P: result
P->>P: redacted capsule + metadata-only audit row
P-->>A: result, verbatim
Note over P,S: A captured grant presented twice to the verifier is refused as replayed_nonce. A corrupted-signature replay<br/>is refused as bad_signature, and the legitimate nonce is never burned.
```
---
## Two proxy shapes, one set of rails
| | `mcp-grant-proxy` | `mcp-multi-tenant-proxy` |
|---|---|---|
| Serves | **one** tenant, fixed at startup | every tenant with a secret file |
| Use when | the agent belongs to one tenant | the operator's own agents work across tenants |
| Config | one MCP entry per tenant | one MCP entry, total |
| Agent names the tenant? | no — it cannot | yes, in the tool name, on every call |
| Tenant names look like | `search` | `acme__search`, `globex__search` |
Prefer the single-tenant proxy whenever an agent genuinely belongs to one
tenant: it is the stronger rail, because that agent is structurally incapable of
reaching another tenant's data. There is no tenant parameter anywhere on its
surface — not in a tool schema, not in an environment variable it can read.
Reach for the multi-tenant proxy when the operator's own harnesses span
tenants. The prefix is the contract, not a label: it decides whose account the
call is billed to and whose records it is filed against, and the proxy never
infers it from the conversation, the repository, or the previous call. A bare
tool name is refused with the naming shape and the tenant roster; a prefix the
proxy does not hold is refused the same way. Each tool's *description* also
names the tenant, because an agent choosing between near-identical tools reads
the description, not the prefix.
The multi-tenant proxy verifies every tenant at startup — in parallel, retried,
with a per-tenant failure recorded rather than fatal — so one broken tenant
cannot silently present itself as a missing set of tools. It is still loud: the
unavailable tenant is named on stderr, in the connect-time instructions, and in
every refusal that mentions it.
---
## The grant
```
<payload>.<signature>
```
`payload` is canonical JSON — sorted keys, compact separators, UTF-8 — encoded
as URL-safe base64 with all `=` padding stripped. `signature` is the lowercase
hex HMAC-SHA256 **of the encoded payload string**, keyed by the tenant secret.
```json
{
"tenant": "acme",
"run_id": "run-6f2c…",
"tool": "search",
"contract_digest": "sha256:0f1e…",
"issued_at": 1767225600,
"expires_at": 1767225720,
"nonce": "Yk3n…",
"privileges": []
}
```
All eight fields are fixed. A payload with an extra or missing field is
malformed rather than "accepted with defaults", because a field the verifier does
not understand is a claim it cannot check.
The secret is used for two things only: as the bearer credential, and as the
HMAC key. It never appears in a grant — a grant is *signed with* it, not
*derived from* it.
Signing the **encoded** form rather than the raw JSON is deliberate. It makes
"parse, then re-encode" equality a meaningful check, so alternate padding and
non-canonical key order are rejected before the HMAC comparison ever runs. The
bytes that were signed and the bytes that were verified are provably the same
string.
Full detail — including why nonce consumption happens last — is in
[`docs/security-and-protocol.md`](docs/security-and-protocol.md).
---
## Run capsules
A capsule answers the question an operator asks after something goes wrong:
*what exactly did this call send and return?* It is written per proxied call
when `MCP_PROXY_CAPSULE_DIR` is set:
```
<capsule_dir>/capsules/acme/search/2026-01-01/call-6f2c….json
```
It records the tool, tenant, arguments, outcome (`is_error`, `reason_code`,
result bytes, duration), retrieval events, validation rejections with their
per-candidate reasons, and usage counters.
It does **not** record credentials. Redaction happens on the way out — there is
no code path that serializes an unredacted document — and it scrubs both
secret-shaped *keys* (`authorization`, `api_key`, `client_secret`, …) and
credential-shaped *values* (`Bearer …`, `sk-…`, `AKIA…`, `xoxb-…`). Token
*counts* (`input_tokens`, `max_tokens`) survive, because they are not
credentials.
Capsules are private: files are created `0600` inside `0700` directories.
Storage is pluggable — `JsonFileSink` for local files, `CallbackSink(fn)` to
ship them anywhere else. A failing sink is logged and reported as `False`,
never raised into the request path: observation must not fail the call it
observes.
---
## Context byte budgets
Two caps, because they fail differently.
**Per page text** (`apply_page_text_budget`) keeps one oversized document from
crowding out everything else in a result set. It truncates *page body text
only* — `markdown`, `content`, `text`, `html`, `rawHtml` — structurally, with an
explicit omission marker:
```json
{"url": "https://example.test/a", "status": 200,
"markdown": "The page begins…[content omitted for model budget, 48213 chars]"}
```
The result stays valid JSON. URLs, titles, links, ids, and metadata are never
touched: a truncated URL is worse than no URL, because it still looks citable.
**Per turn** (`TurnBudget`) is cumulative across every tool result in one
model turn, because the sum is what the model actually reads. When a result does
not fit it is cut on a UTF-8 boundary and marked
`…[turn tool-result budget reached]`. When the budget is gone entirely, later
results become an explicit notice:
```json
{"notice": "tool_result_omitted_turn_budget_exhausted"}
```
An empty string would read to a model as "the tool found nothing" — a very
different, and much more damaging, claim than "the budget ran out".
---
## Quickstart
You need Python 3.11+ and nothing else.
```bash
git clone https://github.com/MarkLernReBar/mcp-grant-proxy.git
cd mcp-grant-proxy
# Optional: install the two console scripts plus dev tooling (pytest, mypy,
# ruff). Without it, run the module with PYTHONPATH=src (every command below
# shows that form), because the runtime has no dependencies at all.
python3 -m pip install -e ".[dev]"
# 1. An owner-only secret file. The proxy refuses anything group- or
# world-readable, so this is a hard requirement, not a suggestion.
mkdir -p ~/.config/mcp-proxy/tenants && chmod 700 ~/.config/mcp-proxy/tenants
printf '%s' "$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))')" \
> ~/.config/mcp-proxy/tenants/acme.secret
chmod 600 ~/.config/mcp-proxy/tenants/acme.secret
# 2. A real end-to-end demonstration: a local MCP server, a real stdio
# subprocess, a proxied call, a refused replay, and a redacted capsule.
PYTHONPATH=src python3 examples/demo.py
# 3. The test suite, plus the type and lint gates CI runs.
PYTHONPATH=src python3 -m pytest -q
ruff check src tests examples
mypy src --ignore-missing-imports
```
### Wiring it into a client
Claude Code / Cursor / any stdio MCP client takes a command, args, and env:
```json
{
"mcpServers": {
"acme-research": {
"command": "python3",
"args": ["-m", "mcp_grant_proxy.cli", "single"],
"env": {
"MCP_PROXY_TENANT": "acme",
"MCP_PROXY_UPSTREAM_ORIGIN": "https://mcp.example.com",
"MCP_PROXY_CONTRACT_DIGEST": "sha256:0f1e2d…",
"MCP_PROXY_TENANT_SECRET_FILE": "/Users/you/.config/mcp-proxy/tenants/acme.secret",
"MCP_PROXY_LOG_FILE": "/Users/you/.config/mcp-proxy/audit.jsonl",
"MCP_PROXY_CAPSULE_DIR": "/Users/you/.config/mcp-proxy/capsules"
}
}
}
}
```
Prefer `MCP_PROXY_TENANT_SECRET_FILE` over the inline `MCP_PROXY_TENANT_SECRET`:
an inline secret sits in the client's config file, and anything that can read that
file can read it. The file form is checked for owner-only permissions at startup.
### Multi-tenant
```json
{
"mcpServers": {
"all-tenants": {
"command": "python3",
"args": ["-m", "mcp_grant_proxy.cli", "multi"],
"env": {
"MCP_PROXY_SECRETS_DIR": "/Users/you/.config/mcp-proxy/tenants",
"MCP_PROXY_UPSTREAM_ORIGIN": "https://mcp.example.com",
"MCP_PROXY_CONTRACT_DIGESTS": "acme=sha256:0f1e2d…,globex=sha256:9a8b7c…"
}
}
}
}
```
The directory's filenames enumerate the tenants served: `acme.secret`,
`globex.secret`. Each must be `0600`, or startup fails and names the file.
### Configuration
Everything comes from the environment. Nothing comes from `argv`, because
process arguments are world-readable on many systems and a secret in `argv` is
a secret leaked. Only `--help`, `--version`, and the `single`/`multi` selector
are parsed.
| Variable | Default | Meaning |
|---|---|---|
| `MCP_PROXY_TENANT` | — | the one tenant this process serves (single-tenant) |
| `MCP_PROXY_SECRETS_DIR` | — | directory of `<tenant>.secret` files (multi-tenant) |
| `MCP_PROXY_CONTRACT_DIGESTS` | — | `acme=<digest>,globex=<digest>` (multi-tenant) |
| `MCP_PROXY_UPSTREAM_ORIGIN` | — | https origin; `http` allowed only for localhost |
| `MCP_PROXY_UPSTREAM_PATH` | `/mcp` | upstream endpoint path |
| `MCP_PROXY_TENANT_SECRET` | — | inline secret (set exactly one of the two) |
| `MCP_PROXY_TENANT_SECRET_FILE` | — | `0600` file holding the secret |
| `MCP_PROXY_CONTRACT_DIGEST` | — | the tenant's contract digest, a public value |
| `MCP_PROXY_ALLOWED_TOOLS` | `think,search,fetch,list_documents,read_document` | comma-separated allow-list |
| `MCP_PROXY_MAX_CALLS` | `500` | per-session tool-call cap |
| `MCP_PROXY_MAX_SESSION_SECONDS` | `7200` | per-session wall-clock cap |
| `MCP_PROXY_MAX_REQUEST_BYTES` | `65536` | cap on the serialized `tools/call` |
| `MCP_PROXY_GRANT_LIFETIME_SECONDS` | `120` | grant lifetime, ceiling `300` |
| `MCP_PROXY_UPSTREAM_TIMEOUT_SECONDS` | `180` | per-request HTTP timeout |
| `MCP_PROXY_LOG_FILE` | unset | JSONL audit log; metadata only |
| `MCP_PROXY_CAPSULE_DIR` | unset | write one redacted capsule per call |
| `MCP_PROXY_VERIFY_ATTEMPTS` | `2` | startup verification attempts per tenant |
Exit codes: `0` clean shutdown, `2` configuration or startup failure. A startup
failure prints variable *names* and the tenant, never a value, and serves
nothing — a misconfigured proxy must never reach a model as a half-working
catalog.
---
## Security model
**What the agent can never see**
* The tenant secret. It is read once at startup into process memory, used only
for the `Authorization` header and the HMAC, and never logged, echoed in tool
output, or written to a capsule or audit row.
* Any grant. One is minted per upstream request and discarded.
* Another tenant, on the single-tenant proxy: there is no tenant parameter, no
tenant field in any schema, and no other tenant's secret in the process.
* Anything outside the allow-list: rails run *before* the upstream request, so a
non-listed tool costs zero requests and leaks zero bytes.
**What it does see** — the upstream catalog intersected with the allow-list,
tool results verbatim (including typed `isError` results, so the upstream error
taxonomy keeps its meaning), and typed proxy refusals:
| Rail | `error_code` |
|---|---|
| Tool not on the allow-list | `proxy_tool_not_allowed` |
| Tool absent from the upstream catalog | `tool_not_enabled_for_tenant` |
| Call cap reached | `proxy_call_cap_exceeded` |
| Wall-clock cap reached | `proxy_session_expired` |
| Request too large | `proxy_request_too_large` |
| Upstream unreachable or failing | `proxy_upstream_unavailable` |
| Unnamespaced name (multi-tenant) | `proxy_tenant_not_named` |
| Tenant failed startup (multi-tenant) | `proxy_tenant_unavailable` |
**The boundary this does not draw.** The proxy constrains *what the agent can
reach through the proxy*. It does not sandbox the agent's host: a client running
as your OS user can still read any file you can read. That is why the secret
file form matters, why it should live outside any directory the agent can read,
and why the file is rejected unless it is `0600`.
**Not retried, by design.** The proxy never retries an upstream call. A
transport error may be retried once *by the caller* with identical inputs; a
retry inside the proxy would hide a credential rotation or a revocation behind
silent duplication.
The full protocol and threat model — including the nonce ordering rule and the
redaction rules — is in
[`docs/security-and-protocol.md`](docs/security-and-protocol.md). Disclosure
scope and the enforcement invariants are summarized in
[`SECURITY.md`](SECURITY.md).
---
## Layout
```
src/mcp_grant_proxy/
py.typed PEP 561 marker: downstream mypy checks this package, not skips it
grants.py mint, parse, verify single-use HMAC grants (no I/O, injected clock)
proxy.py stdio MCP proxies, rails, JSONL audit log
capsules.py redacted run capsules, file + callback sinks
budgets.py per-page and per-turn byte budgets
cli.py the two console entry points
examples/
demo.py end-to-end proof: real HTTP server, real stdio subprocess
mock_mcp_server.py a local MCP server that verifies grants
tests/ 127 tests: format parity, replay, 0600 enforcement, routing,
redaction, budgets, and a real HTTP + stdio integration test
.github/workflows/ci.yml ruff + mypy + pytest + demo + wheel, Python 3.11–3.14
CHANGELOG.md release history
SECURITY.md threat model, nonce ordering invariant, 0600 rule, redaction scope
```
```bash
ruff check src tests examples
mypy src --ignore-missing-imports
PYTHONPATH=src python3 -m pytest -v
PYTHONPATH=src python3 examples/demo.py
```
Packaging is checked too: `python3 -m pip wheel . --no-deps` builds a wheel that
carries the `py.typed` marker, and installing it gives working
`mcp-grant-proxy` and `mcp-multi-tenant-proxy` console scripts.
## License
MIT. See [LICENSE](LICENSE).