Tools Hub / Blueprints / AI & LLM Ops
⚙️ AI & LLM Ops

Authenticated Streamable HTTP Wrapper & Per-Token Rate Limiter for Remote MCP Servers

A hardened reverse-proxy gateway that fronts a streamable-HTTP MCP server with constant-time bearer auth, CIDR allowlists, per-token token-bucket limiting and SSE-safe streaming passthrough.

Stack: Python 3.11 / FastAPI / Uvicorn / SQLite WAL / S RAM: 96 MB RAM Intermediate
📄 mcp_gateway.py
import os
import time
import hmac
import json
import hashlib
import logging
import sqlite3
import asyncio
from contextlib import asynccontextmanager
from typing import Dict, Tuple

import httpx
from fastapi import FastAPI, Request, Response, HTTPException
from fastapi.responses import StreamingResponse
from starlette.background import BackgroundTask

LOG = logging.getLogger("mcp.gateway")
UPSTREAM = os.environ.get("MCP_UPSTREAM", "http://127.0.0.1:8000")
DB_PATH = os.environ.get("MCP_DB", "/var/lib/mcp-gateway/state.db")
ALLOW_CIDRS = [c.strip() for c in os.environ.get("MCP_ALLOW_CIDRS", "").split(",") if c.strip()]
RATE = float(os.environ.get("MCP_RATE_PER_SEC", "5"))
BURST = float(os.environ.get("MCP_BURST", "20"))
TIMEOUT = float(os.environ.get("MCP_UPSTREAM_TIMEOUT", "300"))


def _hash(token: str) -> str:
    return hashlib.sha256(token.encode()).hexdigest()


def load_tokens() -> Dict[str, str]:
    raw = os.environ.get("MCP_TOKENS", "")
    out: Dict[str, str] = {}
    for pair in raw.split(","):
        if not pair.strip():
            continue
        token, _, label = pair.partition(":")
        out[_hash(token.strip())] = (label or "default").strip()
    return out


TOKENS = load_tokens()


def init_db() -> None:
    os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
    con = sqlite3.connect(DB_PATH)
    con.execute("PRAGMA journal_mode=WAL")
    con.execute("PRAGMA synchronous=NORMAL")
    con.execute("CREATE TABLE IF NOT EXISTS buckets (key TEXT PRIMARY KEY, tokens REAL, ts REAL)")
    con.commit()
    con.close()


def take_token(key: str) -> Tuple[bool, float]:
    now = time.monotonic()
    con = sqlite3.connect(DB_PATH, timeout=5.0)
    try:
        con.execute("BEGIN IMMEDIATE")
        row = con.execute("SELECT tokens, ts FROM buckets WHERE key=?", (key,)).fetchone()
        tokens, ts = (row if row else (BURST, now))
        tokens = min(BURST, tokens + (now - ts) * RATE)
        if tokens < 1.0:
            con.execute("INSERT OR REPLACE INTO buckets(key,tokens,ts) VALUES(?,?,?)", (key, tokens, now))
            con.commit()
            return False, (1.0 - tokens) / RATE
        con.execute("INSERT OR REPLACE INTO buckets(key,tokens,ts) VALUES(?,?,?)", (key, tokens - 1.0, now))
        con.commit()
        return True, 0.0
    finally:
        con.close()


def client_ip(request: Request) -> str:
    fwd = request.headers.get("x-forwarded-for")
    return (fwd.split(",")[0].strip() if fwd else (request.client.host if request.client else "0.0.0.0"))


def ip_allowed(ip: str) -> bool:
    if not ALLOW_CIDRS:
        return True
    import ipaddress
    addr = ipaddress.ip_address(ip)
    return any(addr in ipaddress.ip_network(c, strict=False) for c in ALLOW_CIDRS)


@asynccontextmanager
async def lifespan(app: FastAPI):
    init_db()
    app.state.client = httpx.AsyncClient(timeout=httpx.Timeout(TIMEOUT, connect=10.0))
    LOG.info("gateway ready upstream=%s tokens=%d", UPSTREAM, len(TOKENS))
    yield
    await app.state.client.aclose()


app = FastAPI(lifespan=lifespan)


@app.api_route("/{path:path}", methods=["GET", "POST", "DELETE", "PUT", "OPTIONS"])
async def proxy(path: str, request: Request):
    ip = client_ip(request)
    if not ip_allowed(ip):
        raise HTTPException(403, "ip not allowed")
    auth = request.headers.get("authorization", "")
    token = auth[7:].strip() if auth.lower().startswith("bearer ") else ""
    label = None
    if token:
        h = _hash(token)
        for known, lbl in TOKENS.items():
            if hmac.compare_digest(known, h):
                label = lbl
                break
    if label is None:
        raise HTTPException(401, "invalid bearer token", headers={"WWW-Authenticate": "Bearer"})
    ok, retry = take_token(label)
    if not ok:
        raise HTTPException(429, "rate limited", headers={"Retry-After": f"{retry:.2f}"})
    body = await request.body()
    headers = {k: v for k, v in request.headers.items() if k.lower() not in ("host", "authorization", "content-length")}
    req = app.state.client.build_request(request.method, f"{UPSTREAM}/{path}", content=body, headers=headers)
    upstream = await app.state.client.send(req, stream=True)
    resp_headers = {k: v for k, v in upstream.headers.items() if k.lower() not in ("content-length", "transfer-encoding", "connection")}
    return StreamingResponse(upstream.aiter_raw(), status_code=upstream.status_code, headers=resp_headers, background=BackgroundTask(upstream.aclose))


if __name__ == "__main__":
    import uvicorn
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
    uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("MCP_PORT", "8080")), proxy_headers=True, forwarded_allow_ips="127.0.0.1")

1. Production Pain Points and Architecture Trade-offs

Once a remote MCP server is exposed to the public internet, the question shifts from "does it run" to "who can call it, how often, and what happens under abuse." MCP's streamable HTTP transport is fundamentally long-lived connections plus SSE chunked streaming, which creates three hard constraints. First, a default Nginx with proxy_buffering on will accumulate SSE events in its buffer and the client sees tool calls that "hang and never return." Second, authentication cannot live in application business logic, or every MCP tool reimplements it. Third, rate limiting must be per-token rather than per-IP, because a single CI runner egress IP may carry dozens of tenants.

The trade-off in this blueprint: use FastAPI plus httpx stream=True for zero-buffer passthrough, collapsing auth, allowlisting and rate limiting into one dedicated process, while the MCP server itself binds only to 127.0.0.1 and is never directly reachable. Token bucket state lives in SQLite WAL rather than an in-memory dict — with multiple uvicorn workers an in-memory dict is per-process, so the effective rate silently becomes N times the configured value. SQLite's BEGIN IMMEDIATE gives a cross-process write lock at the cost of one fsync-class transaction per request, measured at roughly 0.1–0.3 ms on NVMe. For MCP, where tool-call intervals are far larger than milliseconds, that is entirely acceptable. Only move to Redis plus a Lua script above ~2000 QPS; do not optimize prematurely.

The second key trade-off is token storage. Plaintext tokens live in an environment file, are SHA-256 hashed into an in-memory dict at startup, and are compared with hmac.compare_digest for constant-time comparison to avoid timing side channels. Logs never print raw tokens, only labels.

2. Step-by-Step Deployment and Permission Hardening

Step 1: create a dedicated system user and directories.

bash
sudo useradd --system --no-create-home --shell /usr/sbin/nologin mcp-gw
sudo install -d -o mcp-gw -g mcp-gw -m 0750 /var/lib/mcp-gateway
sudo install -d -o mcp-gw -g mcp-gw -m 0750 /etc/mcp-gateway

Step 2: write the env file with mode 0640 owned by root:mcp-gw. The service can read it but cannot rewrite its own credentials, and no other user can read it.

bash
sudo tee /etc/mcp-gateway/env >/dev/null <<'EOF'
MCP_UPSTREAM=http://127.0.0.1:8000
MCP_DB=/var/lib/mcp-gateway/state.db
MCP_ALLOW_CIDRS=10.0.0.0/8,203.0.113.0/24
MCP_RATE_PER_SEC=5
MCP_BURST=20
MCP_UPSTREAM_TIMEOUT=300
MCP_TOKENS=sk_live_ci_runner:ci,sk_live_agent_prod:agent
EOF
sudo chown root:mcp-gw /etc/mcp-gateway/env && sudo chmod 0640 /etc/mcp-gateway/env

Step 3: the systemd unit, with sandboxing as the point. ProtectSystem=strict plus ReadWritePaths opens only the state directory; PrivateTmp, NoNewPrivileges and RestrictAddressFamilies shrink the attack surface.

ini
[Unit]
Description=MCP Auth Gateway
After=network-online.target
Wants=network-online.target

[Service]
User=mcp-gw
Group=mcp-gw
EnvironmentFile=/etc/mcp-gateway/env
ExecStart=/opt/mcp-gateway/.venv/bin/python /opt/mcp-gateway/mcp_gateway.py
Restart=on-failure
RestartSec=2
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/mcp-gateway
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target

Step 4: bind the MCP server to loopback. Whether you use the official Python or TypeScript SDK, the launch flag must be --host 127.0.0.1. Confirm with ss -lntp | grep 8000 that the listen address is 127.0.0.1:8000, not 0.0.0.0:8000. This is the security floor of the whole design.

Step 5: TLS termination. The gateway speaks plain HTTP; put Caddy or Nginx in front. Caddy needs two lines:

code
mcp.example.net {
    reverse_proxy 127.0.0.1:8080 {
        flush_interval -1
    }
}

flush_interval -1 disables response buffering in Caddy and is mandatory — without it SSE gets batched. The Nginx equivalent is proxy_buffering off; proxy_cache off; chunked_transfer_encoding on;.

3. Parameter Tuning and Load Verification

Rate limit parameters. MCP_RATE_PER_SEC is steady-state rate, MCP_BURST is bucket capacity. Rule of thumb: burst = 4x rate, which absorbs the MCP client's "initialize + tools/list + first tools/call" triple burst. If your agent fans out concurrent tool calls, raise burst to 8x.

Timeout parameters. MCP_UPSTREAM_TIMEOUT=300 is a streaming read timeout, not total duration — httpx's Timeout(read=...) means "max gap between chunks." An MCP tool may run ten minutes while emitting heartbeats, so read timeout must be generous; connect=10.0 must be short so a dead upstream does not pile up connections.

Verify auth and rate limiting.

bash
# no token -> 401
curl -s -o /dev/null -w '%{http_code}\n' -X POST https://mcp.example.net/mcp
# wrong token -> 401
curl -s -o /dev/null -w '%{http_code}\n' -H 'Authorization: Bearer wrong' -X POST https://mcp.example.net/mcp
# valid token -> 200/4xx depending on upstream
curl -s -o /dev/null -w '%{http_code}\n' -H 'Authorization: Bearer sk_live_agent_prod' -X POST https://mcp.example.net/mcp
# burst 30 times, watch where 429 appears
for i in $(seq 1 30); do curl -s -o /dev/null -w '%{http_code} ' -H 'Authorization: Bearer sk_live_agent_prod' -X POST https://mcp.example.net/mcp; done; echo

Expected: the first 20 (burst) pass, then refill at 5/s, with 429 plus Retry-After from request 21 onward.

Verify SSE is not buffered. This is the most common failure mode:

bash
curl -N -H 'Authorization: Bearer sk_live_agent_prod' \
  -H 'Accept: text/event-stream' \
  https://mcp.example.net/mcp | while IFS= read -r line; do echo "$(date +%s.%N) $line"; done

Timestamps must increase line by line at the upstream's cadence. If every line arrives in the same millisecond, some layer is buffering.

Load test. Hit a fixed token with hey or wrk and confirm the 429 ratio matches token bucket math: steady-state QPS should approach RATE and everything above it should be 429.

code
hey -z 30s -c 20 -H 'Authorization: Bearer sk_live_ci_runner' -m POST https://mcp.example.net/mcp

4. Troubleshooting and Safe Rollback

Failure 1: every request returns 401. Nine times out of ten a token has trailing whitespace or a newline. The parser calls strip(), but if you export MCP_TOKENS="sk_x:ci " and use EnvironmentFile, systemd preserves spaces inside quotes. Check the actual injected value with systemctl show mcp-gateway -p Environment.

Failure 2: 429 appears earlier than expected. Check whether multiple workers share the DB but labels collide — different tokens with the same label share one bucket. Labels must be globally unique; use tenant-purpose naming.

Failure 3: SSE hangs. Check in order: Caddy flush_interval -1; Nginx proxy_buffering off; whether the gateway added Content-Length (the code strips it); whether the upstream MCP server enabled gzip (SSE must not be compressed).

Failure 4: SQLite database is locked. Indicates a long transaction. Each request here is sub-millisecond, so this means disk IO saturation or a corrupt WAL. Check whether PRAGMA wal_checkpoint(TRUNCATE) keeps failing; if so, stop the service and delete state.db-wal and state.db-shm to rebuild. Losing bucket state is acceptable — worst case rate limiting briefly relaxes.

Failure 5: IP allowlist false positives. Behind a CDN, X-Forwarded-For is forgeable. Caddy/Nginx must overwrite rather than append that header, and uvicorn's forwarded_allow_ips must trust only 127.0.0.1. Verify: curl -H 'X-Forwarded-For: 1.2.3.4' should still be judged by the real IP.

Safe rollback. Before any change, sudo cp /etc/mcp-gateway/env /etc/mcp-gateway/env.bak.$(date +%s). Rollback is three steps: systemctl stop mcp-gateway, restore the env file, systemctl start mcp-gateway. If a token is suspected leaked, delete its entry from MCP_TOKENS and systemctl restart — the hash dict rebuilds at startup and the old token dies immediately, no code change needed. In an emergency where the gateway itself is down, you may temporarily point Caddy straight at the MCP server with basic_auth, but you must simultaneously rebind the MCP server from loopback to an internal interface. That is a conscious degradation and must be reverted afterward.

Auditing. Add one structured log line in the gateway: LOG.info("req label=%s ip=%s path=%s status=%d", label, ip, path, upstream.status_code). With journald, journalctl -u mcp-gateway -o json | jq gives per-label call volume — the only reliable data source for post-incident forensics and capacity planning.

Want the full multi-workflow production repo with REST API & ops dashboard?
All blueprints are bundled inside the B2B AI Automation MVP Pack with Docker, Systemd & test suite.
Get Full MVP Pack $499 →
PARTNER ECOSYSTEM

Recommended Cloud & AI Infrastructure

Hand-picked developer infrastructure we use to run 24/7 workflows. Partner links help keep all browser tools free.
📬 WEEKLY BRIEF · ZERO SPAM

Get the Yevrix Indie Dev & AI Digest

One weekly email with new browser-local dev tools, cloud & LLM pricing benchmarks, ready-to-install Agent Skills, and rising OSS repos. 1-click unsubscribe anytime.