Skip to main content

mcp-rbac-gateway

A lightweight security, RBAC and audit gateway for Model Context Protocol (MCP) servers and AI agents.

CI PyPI Python Typed License

AI agents now call real tools: file systems, databases, email, cloud APIs. MCP made connecting those tools easy. It didn't decide who may call what, with which arguments, what happens when a tool returns a prompt injection, or how you find out afterwards what an agent did.

mcp-rbac-gateway sits between the agent and its tools and answers those questions with one YAML file:

agent ──► mcp-rbac-gateway ──► MCP server / Python tool
           ├─ policy     who may call which tool, with which arguments (enforce or shadow)
           ├─ limits     per-agent rate limits, runaway-loop detection
           ├─ scanner    redact secrets & PII both ways, catch prompt injection
           │             (heuristics, plus your own classifier for the gray zone)
           ├─ approval   pause risky calls for a human (CLI, webhook or your own API),
           │             with pending requests in memory, SQLite, Redis or Postgres
           └─ audit      every call, decision and latency in SQLite, optionally hash-chained

It works in two ways:

  • As a proxy in front of any MCP server, over stdio, Streamable HTTP (including the stateless 2026-07-28 revision) or legacy SSE. You don't change the server or the client.
  • As a Python decorator (@guard) on LangGraph, LangChain, FastAPI or plain async functions.

Both paths share the same engine, so a rule behaves the same way whichever route a call takes.

What's new in 0.4.0

Feature In one line Config Read more
Pluggable injection classifier Send gray-zone heuristic scores to your own model (ONNX, DeBERTa, LLM judge); fails closed. scanner.prompt_injection.classifier_*, Sentinel(classifier=...) Plugging in your own injection classifier
Rate limits and loop detection Sliding-window limits per tenant, session, agent and tool, and a block on the Nth identical call in a row. agents.<name>.rate_limit, max_consecutive_identical_calls Rate limits and loop detection
Shadow mode Trial a policy on live traffic: would-be blocks run anyway and are logged as shadow_blocked. enforcement_mode: shadow, globally or per agent Shadow mode
Tamper-evident audit Optional SHA-256 or HMAC hash chain over audit rows, checked by verify-audit. audit.tamper_evident, audit.signing_key_env Tamper-evident hash chain
Distributed stores Pending approvals in Redis or Postgres and task ownership in Redis, so replicas on different hosts share them. hitl.store: redis|postgres, tasks.store: redis, *.store_url Running several replicas

Every new feature is off by default, so a 0.3 config behaves the same under 0.4. The audit database does change: see Upgrading from 0.3.


Contents


Install

pip install mcp-rbac-gateway

# extras
pip install "mcp-rbac-gateway[server]"      # HTTP proxy + approval API (FastAPI, uvicorn)
pip install "mcp-rbac-gateway[langgraph]"   # LangGraph example deps
pip install "mcp-rbac-gateway[redis]"       # Redis approval and task stores (redis-py)
pip install "mcp-rbac-gateway[postgres]"    # Postgres approval store (psycopg 3 + pool)

Requires Python 3.10+. The core depends only on pydantic, pyyaml, rich, typer and httpx. The Redis and Postgres client libraries are imported only when you configure a store that needs them, and an injection classifier brings its own runtime.

Quick start

1. Write a policy

mcp-rbac-gateway init            # writes a commented sentinel.yaml
mcp-rbac-gateway validate        # shows the effective policy for each agent
# sentinel.yaml
default_agent: guest
default_action: deny            # tools no rule mentions are denied

agents:
  guest:
    allow: ["read_*", "search_*"]
  researcher:
    inherits: [guest]
    allow: ["fetch_url"]
    arguments:
      read_file:
        path: { pattern: '/workspace/.*', deny_pattern: '\.\.' }
  operator:
    inherits: [researcher]
    allow: ["*"]
    deny: ["drop_database"]
    require_approval: ["delete_*", "send_email"]

hitl:
  mode: cli                     # cli | webhook | auto_approve | auto_deny

2a. Put it in front of an MCP server (no code changes)

mcp-rbac-gateway wrap --config sentinel.yaml --agent researcher -- \
    npx -y @modelcontextprotocol/server-filesystem /workspace

In Claude Desktop, Cursor or any other MCP client, use that command in place of the server's own (see examples/claude_desktop_config.json). For HTTP servers:

mcp-rbac-gateway serve --config sentinel.yaml --upstream-url http://localhost:8000/mcp --port 8765
# clients connect to http://localhost:8765/mcp (or /sse for legacy SSE clients)

# MCP 2026-07-28 (stateless: no initialize, no Mcp-Session-Id)
mcp-rbac-gateway proxy-http --config sentinel.yaml --upstream-url http://localhost:8000/mcp

2b. Or guard Python tools directly

from langchain_core.tools import tool
from mcp_rbac_gateway import Sentinel, agent_context, guard

sentinel = Sentinel.from_yaml("sentinel.yaml")

@tool
@guard(sentinel, on_block="return")      # under @tool, so LangChain sees the guarded function
async def read_file(path: str) -> str:
    """Read a file from the workspace."""
    return open(path).read()

with agent_context("researcher"):        # identity for every call in this block
    result = await graph.ainvoke(...)

3. See what happened

mcp-rbac-gateway report --since 24h
╭────────────────────────── mcp-rbac-gateway report ───────────────────────────╮
│   6        2         4          5              1                             │
│ calls   allowed   blocked   redactions   injection hits                      │
╰──────────────────── 2026-11-26 21:52:43 → 2026-11-26 21:52:43 ───────────────╯
  decision              count   share
 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  blocked_policy            3   ██████████░░░░░░░░░░
  allowed                   2   ███████░░░░░░░░░░░░░
  blocked_injection         1   ███░░░░░░░░░░░░░░░░░
  ...

4. Turn on what production needs

Each 0.4.0 feature is one or two keys. This is a starting point for a gateway that runs as several replicas behind a load balancer:

enforcement_mode: shadow            # first week: log would-be blocks, block nothing
agents:
  support-bot:
    allow: ["read_*", "search_*", "run_sql"]
    rate_limit: 60/minute           # per tool, per tenant + session + agent
    max_consecutive_identical_calls: 3
    arguments:
      run_sql:
        rate_limit: 10/minute
        query: { pattern: '(?is)\s*select\b.*' }
scanner:
  prompt_injection:
    classifier_min_score: 0.30      # used only if you pass Sentinel(classifier=...)
hitl:
  mode: api
  store: redis                      # or postgres; pending approvals shared by replicas
  store_url: ${SENTINEL_REDIS_URL}
tasks:
  store: redis
  store_url: ${SENTINEL_REDIS_URL}
audit:
  tamper_evident: true
  signing_key_env: AUDIT_HMAC_KEY
pip install "mcp-rbac-gateway[server,redis]"
mcp-rbac-gateway report --since 24h     # the yellow shadow panel lists what would be blocked
mcp-rbac-gateway verify-audit -c sentinel.yaml

When the shadow panel shows only blocks you want, change enforcement_mode to enforce.


Architecture

Components

flowchart LR
    subgraph Clients
        A1["MCP client<br/>(Claude Desktop, Cursor, IDE)"]
        A2["LangGraph / LangChain agent"]
        A3["FastAPI service"]
    end

    subgraph Sentinel["mcp-rbac-gateway"]
        direction TB
        T1["StdioProxy<br/>mcp-rbac-gateway wrap"]
        T2["HttpProxy<br/>Streamable HTTP + SSE"]
        T4["StatelessHttpProxy<br/>MCP 2026-07-28"]
        T3["@guard decorator"]
        I["MessageInterceptor<br/>JSON-RPC inspection"]
        S["Sentinel engine<br/>(enforce / shadow)"]
        P["PolicyEngine<br/>policy.py"]
        LIM["CallLimiter<br/>limiter.py"]
        SC["Scanner<br/>scanner.py"]
        CL["InjectionClassifier<br/>(yours, optional)"]
        H["ApprovalGate + Broker<br/>hitl.py"]
        TR["TaskRegistry<br/>mcp.py"]
        AU[("AuditLog<br/>SQLite, optional hash chain")]
        T1 --> I
        T2 --> I
        T4 --> I
        I --> S
        I --> TR
        T3 --> S
        S --> P
        S --> LIM
        S --> SC
        SC -. "gray zone" .-> CL
        S --> H
        S --> AU
    end

    subgraph Stores["Shared state (optional)"]
        AS[("ApprovalStore<br/>memory / SQLite / Redis / Postgres")]
        TS[("TaskStore<br/>memory / Redis")]
    end

    subgraph Upstream
        U1["stdio MCP server"]
        U2["HTTP MCP server"]
        U3["Python tool function"]
    end

    A1 --> T1 --> U1
    A1 --> T2 --> U2
    A1 --> T4 --> U2
    A2 --> T3 --> U3
    A3 --> T3
    H --> AS
    TR --> TS
    H -.->|"prompt"| Human(("Human"))
    H -.->|"POST"| W["Webhook / Slack relay"]
    AU --> R["report / verify-audit"]

What lives where:

State Where Shared between replicas?
Policy, scanner rules sentinel.yaml, loaded into each process Yes, if every replica loads the same file
Pending approvals hitl.store: memory, sqlite, redis or postgres sqlite on one host or volume; redis and postgres on any host
Task ownership tasks.store: memory or redis Only with redis
Rate-limit and loop counters CallLimiter, in memory No. Each process counts its own traffic
Audit trail and hash chain the SQLite file at audit.path Only by processes that share that file

Life of a tool call

sequenceDiagram
    autonumber
    participant Agent
    participant Proxy as mcp-rbac-gateway
    participant Judge as Your classifier
    participant Human
    participant Server as MCP server
    participant DB as Audit DB

    Agent->>Proxy: tools/list
    Proxy->>Server: tools/list
    Server-->>Proxy: all tools + annotations
    Proxy-->>Agent: only the tools this agent may call (shadow agents see all)

    Agent->>Proxy: tools/call delete_file {path}
    Proxy->>Proxy: policy: allow/deny globs, argument regexes
    Proxy->>Proxy: scanner: redact secrets in arguments
    Proxy->>Proxy: limits: rate window and identical-call streak
    alt needs approval
        Proxy->>DB: pending_approval
        Proxy->>Human: approve delete_file? (redacted args)
        Human-->>Proxy: approve / deny / timeout
    end
    alt blocked (enforce mode)
        Proxy->>DB: blocked_policy / blocked_rate_limit / blocked_loop /<br/>denied_by_human / approval_timeout
        Proxy-->>Agent: isError: "[mcp-rbac-gateway] Tool call blocked ..."
    else allowed (or an automatic block in shadow mode)
        opt shadow mode
            Proxy->>DB: shadow_blocked (the would-be decision and reason)
        end
        Proxy->>Server: tools/call (sanitised arguments)
        Server-->>Proxy: result
        Proxy->>Proxy: scanner: redact output, score prompt injection
        opt heuristic score in the gray zone
            Proxy->>Judge: classify(redacted text)
            Judge-->>Proxy: score 0..1 (error or timeout fails closed)
        end
        Proxy->>DB: allowed / approved / blocked_injection + latency
        Proxy-->>Agent: redacted result (or withheld)
    end

With audit.tamper_evident: true, every row written above also gets prev_hash and row_hash.

Decision order

flowchart TD
    C["tools/call (agent, tool, args)"] --> D{"deny glob matches?"}
    D -- yes --> X1["BLOCKED_POLICY"]
    D -- no --> AL{"allow glob matches?"}
    AL -- "no, default_action=deny" --> X1
    AL -- yes --> ARG{"argument constraints pass?"}
    ARG -- no --> X1
    ARG -- yes --> RED["redact secrets in arguments<br/>(+ injection score if scan_inputs_for_injection)"]
    RED -- "injection in arguments" --> X7["BLOCKED_INJECTION"]
    RED --> LIM{"rate_limit used up, or<br/>too many identical calls in a row?"}
    LIM -- "rate limit" --> X5["BLOCKED_RATE_LIMIT<br/>(retryable)"]
    LIM -- "loop" --> X6["BLOCKED_LOOP"]
    LIM -- no --> APP{"approval needed?<br/>require_approval / hitl.tools /<br/>hitl.rules / destructiveHint"}
    APP -- yes --> HU{"human decision"}
    HU -- deny --> X2["DENIED_BY_HUMAN"]
    HU -- timeout --> X3["APPROVAL_TIMEOUT"]
    HU -- approve --> RUN
    APP -- no --> RUN["call upstream tool"]
    RUN --> OUT["redact output + heuristic injection score"]
    OUT --> GZ{"score in<br/>[classifier_min_score, threshold)<br/>and a classifier is set?"}
    GZ -- yes --> CLS["combine with classifier score<br/>(max or noisy_or)"]
    GZ -- no --> INJ
    CLS --> INJ{"score ≥ threshold<br/>and action=block?"}
    INJ -- yes --> X4["BLOCKED_INJECTION<br/>(output withheld)"]
    INJ -- no --> OK["ALLOWED / APPROVED"]

In shadow mode the automatic blocks (BLOCKED_POLICY, BLOCKED_INJECTION, BLOCKED_RATE_LIMIT, BLOCKED_LOOP) do not stop the call: the gateway writes a shadow_blocked row with the first block it hit and lets the call run. The pre-call checks after that first block are skipped, except approval: a shadowed call still waits for a human when an approval rule matches, and DENIED_BY_HUMAN and APPROVAL_TIMEOUT are never shadowed. The output is still redacted and scanned. See Shadow mode.


Configuration: sentinel.yaml

Every section is optional. Unknown keys are errors, so a typo like alow: fails loudly instead of quietly weakening a policy. ${VAR} and ${VAR:-default} are expanded from the environment.

Key Default Meaning
default_agent default Policy applied to agents not listed in agents.
default_action deny Outcome for tools that no allow/deny rule mentions.
enforcement_mode enforce enforce blocks denied calls. shadow lets them run and logs a shadow_blocked row instead. See Shadow mode.
agents.<name>.allow / deny [] Tool-name globs (fnmatch, case-sensitive).
agents.<name>.inherits [] Parent agents whose rules are merged in.
agents.<name>.require_approval [] Tool globs that need a human.
agents.<name>.arguments.<tool-glob>.<arg> - pattern, deny_pattern, max_length, allowed_values, required.
agents.<name>.methods.allow / deny [] Globs of JSON-RPC methods other than tools/call (tasks/*, skills/get, prompts/get ...). Deny wins. With no allow list, unmentioned methods are allowed.
agents.<name>.skills.allow / deny [] Globs of skill paths (skill://<path>/SKILL.md). Unmentioned skills follow default_action.
agents.<name>.token_env - Env var holding this agent's token for the HTTP proxy.
agents.<name>.enforcement_mode inherited Overrides enforcement_mode for this agent. Unset: the first value along inherits, else the top-level one.
agents.<name>.rate_limit - Sliding-window limit per tool, such as 20/minute, 100/hour, 5/10s. Counted per tenant, session, agent and tool. See rate limits.
agents.<name>.max_consecutive_identical_calls - Block a call that repeats the previous call of the session (same tool, same arguments) more than this many times in a row.
agents.<name>.arguments.<tool-glob>.rate_limit / max_consecutive_identical_calls - The same limits for matching tools only, overriding the agent-level value. unlimited and 0 switch a limit off.
scanner.redact_inputs / redact_outputs true Redact tool arguments / results.
scanner.input_detectors secrets only Detectors applied to arguments.
scanner.output_detectors all Detectors applied to results.
scanner.custom_patterns [] {name, pattern, replacement?}
scanner.prompt_injection block @ 0.7 enabled, action: warn|block, threshold, extra_patterns.
scanner.prompt_injection.classifier_min_score 0.30 With a classifier plugged in, heuristic scores in [classifier_min_score, threshold) go to it. 0.0 sends everything.
scanner.prompt_injection.classifier_combine max max or noisy_or (1 − (1 − h)(1 − c)).
scanner.prompt_injection.classifier_timeout_seconds 5.0 Longest one classifier call may take.
scanner.prompt_injection.classifier_on_error block On a classifier error or timeout: block fails closed, warn keeps the heuristic score.
scanner.scan_inputs_for_injection false Also score arguments for injection.
scanner.strip_invisible true Strip zero-width and Unicode tag characters from results.
hitl.mode cli cli, webhook, api, auto_approve, auto_deny. See which mode.
hitl.store memory Where pending approvals live: memory (this process), sqlite (survives restarts, shared by every process using the file), or redis / postgres (shared by replicas on any host).
hitl.store_path audit.path SQLite file for store: sqlite.
hitl.store_url - redis://… or postgresql://… for store: redis / postgres. Required for those stores; loading fails without it. Use ${VAR} for the password.
hitl.timeout_seconds 300 After this, the call is blocked (approval_timeout).
hitl.tools [] Tool globs that always need approval, for every agent.
hitl.rules [] {tool, when: {arg: regex}, reason} for approval that depends on arguments.
hitl.destructive_hint true Require approval for tools annotated destructiveHint: true.
hitl.webhook - url, headers, callback_base_url, token_env.
audit.path .sentinel/audit.db SQLite file.
audit.log_arguments / log_results true / false What to store (always after redaction).
audit.writer sync sync: one committed transaction per row. batched: a bounded queue and a background writer; see Performance.
audit.batch_size / flush_interval_ms / queue_size 100 / 50 / 10000 Batched writer tuning. A full queue blocks the caller; rows are never dropped.
audit.tamper_evident false Hash-chain every row; check it with verify-audit. See Tamper-evident hash chain.
audit.signing_key_env - Env var holding an HMAC-SHA256 key for the chain. Unset: plain SHA-256. If named but not set, the audit log refuses to start.
tasks.bind_to_agent true Only the agent whose tools/call created a task may get, update or cancel it.
tasks.ttl_seconds 3600 How long the gateway remembers which agent owns a task.
tasks.store / store_url memory / - memory or redis. redis shares task ownership between replicas, so task requests need no sticky routing; it needs store_url.
upstream.command / url - Default upstream for wrap / serve / proxy-http.

The full annotated example is in examples/sentinel.yaml, and mcp-rbac-gateway init writes another one.

Keys added in 0.4.0: enforcement_mode (top level and per agent), rate_limit and max_consecutive_identical_calls (per agent and per arguments glob), the classifier_* keys under scanner.prompt_injection, hitl.store: redis | postgres with hitl.store_url, tasks.store and tasks.store_url, and audit.tamper_evident with audit.signing_key_env. All of them default to the 0.3 behaviour.

Policy & RBAC

Rules are evaluated in a fixed order, so you can predict the outcome without running anything:

  1. deny wins. If any deny glob matches, the call is blocked, including when an inherited allow would match.
  2. allow: an allow glob must match, unless default_action: allow.
  3. arguments: each constraint whose tool glob matches must pass, checked against the raw arguments before redaction.
    • pattern must match the whole value (re.fullmatch).
    • deny_pattern must not appear anywhere (re.search).
    • Non-string values are matched as JSON (42, true, {"a": 1}).
  4. require_approval sends the call to the approval gate.

Inheritance never loosens a rule. A child agent gets its parents' allows and their denies and argument constraints. Constraints add up, so a child cannot replace a parent's pattern with a weaker one. If two roles need different constraints, inherit from a common, smaller parent (see ops-agent in the example config).

Deny wins along the whole chain. If a parent denies X, no child can allow X, not even with an exact allow: ["X"] or allow: ["*"]. To give one role a tool its parent denies, move the deny out of the shared parent into the roles that need it.

# roles.yaml
default_agent: base
agents:
  base:
    allow: ["read_*", "search"]
    deny: ["read_secrets"]
  writer:
    inherits: [base]
    allow: ["write_file", "read_secrets"]
    require_approval: ["write_file"]
  admin:
    inherits: [writer]
    allow: ["*"]
    deny: ["drop_*"]
$ mcp-rbac-gateway check-policy roles.yaml -t read_secrets -t write_file -t drop_table
effective policy: roles.yaml
╭────────────────┬───────────────┬────────────────────────────┬──────────────────────┬────────────┬──────────────┬────────────┬────────────╮
│ agent          │ inherits      │ allow                      │ deny                 │ approval   │ read_secrets │ write_file │ drop_table │
├────────────────┼───────────────┼────────────────────────────┼──────────────────────┼────────────┼──────────────┼────────────┼────────────┤
│ base (default) │ -             │ read_*, search             │ read_secrets         │ -          │     deny     │    deny    │    deny    │
│ writer         │ base          │ write_file, read_secrets,  │ read_secrets         │ write_file │     deny     │  approval  │    deny    │
│                │               │ read_*, search             │                      │            │              │            │            │
│ admin          │ writer > base │ *, write_file,             │ drop_*, read_secrets │ write_file │     deny     │  approval  │    deny    │
│                │               │ read_secrets, read_*,      │                      │            │              │            │            │
│                │               │ search                     │                      │            │              │            │            │
╰────────────────┴───────────────┴────────────────────────────┴──────────────────────┴────────────┴──────────────┴────────────┴────────────╯
default_action=deny (tools no rule matches)  deny wins over allow along the inheritance chain

The same answers from Python, for building the tool list you give the model and for deciding whether to pause before a call:

sentinel.visible_tools("writer", ["read_file", "read_secrets", "shell"])  # ["read_file"]
sentinel.needs_approval("writer", "write_file", {"path": "a"})  # "tool 'write_file' requires human approval ..."
sentinel.needs_approval("base", "write_file", {"path": "a"})    # None: it would be denied anyway

Tool visibility. The proxy filters tools/list per agent, so a model never sees a tool it can't call. That saves tokens and gives it fewer chances to try.

Dry-run any decision:

$ mcp-rbac-gateway check -a researcher read_file '{"path": "/workspace/../etc/passwd"}'
╭──────────────────────────────── read_file ─────────────────────────────────╮
│ agent    researcher                                                        │
│ decision deny                                                              │
│ reason   argument 'path' of 'read_file' matches forbidden pattern /\.\./    │
│ rule     agents.researcher.arguments[read_file].path                       │
╰────────────────────────────────────────────────────────────────────────────╯

Shadow mode

Roll out a new or stricter policy without breaking agents that are already running. With enforcement_mode: shadow, a call that would be blocked still runs, and the audit trail gets a shadow_blocked row with the exact denial reason and the rule that matched. Read the report, fix the policy or the agent, then switch to enforce.

enforcement_mode: enforce        # the default, for every agent
agents:
  billing-bot:
    enforcement_mode: shadow     # trial the new rules on this agent only
    allow: ["invoices_*"]
    deny: ["invoices_delete"]

What shadow mode lets through:

  • policy denials: deny, allow/default_action, argument constraints, methods and skills rules;
  • prompt-injection blocks, in arguments (scan_inputs_for_injection) and in tool output (the output reaches the agent, still redacted);
  • rate limits (blocked_rate_limit) and runaway-loop blocks (blocked_loop), see Rate limits and loop detection;
  • any automatic block added later, because shadow mode applies to every automatic block rather than a fixed list.

What it does not change:

  • Approvals still apply. A call matching require_approval, hitl.tools, hitl.rules or destructiveHint waits for a human, even if policy would have denied it. A human's denied_by_human or approval_timeout is never shadowed.
  • Redaction still applies. Secrets are redacted from arguments and results as usual.
  • tools/list and skills/list are not filtered for a shadow agent, because hiding a tool would change what the agent does.

Each would-be block writes two rows: the shadow_blocked row (its labels hold shadow_decision, for example blocked_policy) and the call's own outcome (allowed, error ...). In Python the verdict shows the same thing:

v = await sentinel.check_call("billing-bot", "invoices_delete", {"id": 7})
v.allowed          # True
v.shadow_decision  # AuditDecision.BLOCKED_POLICY
v.shadow_reason    # "tool 'invoices_delete' is denied for agent 'billing-bot' (agents.billing-bot.deny[invoices_delete])"

mcp-rbac-gateway report shows these in a yellow Shadow mode: would-be blocks panel, grouped by agent, tool and reason. They are kept out of every blocked count and block rate, because those calls ran; report --json has them as shadow_blocked and shadow.

One block per call. A shadowed call records the first check that would have stopped it. A call that policy denies is not then rate-limited or loop-checked, so fix the policy denials first; the limit and loop blocks show up once policy lets the call through.

With the other 0.4.0 features.

  • Rate limits: an over-limit call in shadow mode runs, gets a shadow_blocked row with labels.shadow_decision: blocked_rate_limit, and is not counted against the window, just as a refused call is not counted in enforce mode. The shadow panel therefore shows the refusals that enforce would produce for the same traffic.
  • Injection classifier: a gray-zone payload that the classifier pushes over the threshold is shadowed like any other injection block, so shadow mode is also a safe way to see what a new classifier would withhold before you trust it.
  • Hash chain: shadow_blocked rows are chained like every other row. The chain covers their decision and reason, but not labels, so the would-be decision name itself is not protected; the reason text is.

A rollout recipe.

  1. Add the new rules with enforcement_mode: shadow on the agents they affect.
  2. Run for a representative period, then read mcp-rbac-gateway report --since 7d, or AuditLog(path).query(decision="shadow_blocked") for the exact reasons.
  3. For each would-be block, either fix the rule (it was a false positive) or fix the agent (it really was doing something it should not).
  4. Remove the per-agent override, or set it to enforce. check-policy marks shadow denials as deny (shadow), so you can confirm which agents are still in shadow mode.

Rate limits and loop detection

Agents get stuck. A model that misreads a tool result can call the same tool with the same arguments forever, and a buggy planner can hammer an expensive API. Two optional limits stop both, per agent and per tool:

agents:
  researcher:
    allow: ["search_*", "read_file", "run_sql"]
    rate_limit: 20/minute                 # every tool, counted separately
    max_consecutive_identical_calls: 3    # the 4th identical call in a row is blocked
    arguments:
      run_sql:
        rate_limit: 5/minute              # overrides 20/minute for run_sql
        query: { pattern: '(?is)\s*select\b.*' }
      "search_*":
        rate_limit: unlimited             # lift the agent-level limit for these tools
        max_consecutive_identical_calls: 0

rate_limit is <calls>/<window>. The window is a unit (second, minute, hour, day, or s, m, h, d), optionally with a count: 5/10s, 100/2 hours. It is a true sliding window: a call is refused when that many calls were already let through in the last window, and the refusal says how long until the oldest one expires. Calls are counted per (tenant, session, agent, tool), so two tenants, two conversations or two tools never share a budget. A refused call is not counted.

max_consecutive_identical_calls compares each call with the previous one in the same session (or, when the call has no session id, the same agent): same tool name and the same arguments as canonical JSON (key order does not matter). With 3, three identical calls in a row go through and the fourth is refused, and so is every further repeat until a different call breaks the streak.

Where the limits come from. An arguments.<tool-glob> entry that sets a limit wins for matching tools. Otherwise the agent-level value applies. Both follow inherits, and the nearest agent in the chain wins, so unlike argument constraints a child can loosen a parent's limit. A scalar under rate_limit or max_consecutive_identical_calls inside arguments.<tool-glob> is a limit; a mapping is still a constraint on an argument of that name.

What the model sees. Both outcomes are audited and returned as a ToolDenial with on_block="result":

[mcp-rbac-gateway] tool_denied
tool: run_sql
decision: blocked_rate_limit
retryable: true
reason: rate limit 5/minute for tool 'run_sql' reached by agent 'researcher'; retry after 41.2s (agents.researcher.arguments[run_sql].rate_limit)
hint: You have called this tool too often. Wait at least retry_after_seconds before calling it again, and do not retry in a tight loop; continue with other work meanwhile.
retry_after_seconds: 41.2

blocked_loop is retryable: false and tells the model to change its approach instead of repeating the call. CallVerdict.retry_after_seconds and ToolDenial.retry_after_seconds carry the wait for code. Both decisions count as blocks in report, summary() and query(blocked_only=True).

The limits are checked after policy and the input-injection scan and before approval, so denied calls never use up a budget. Counts live in memory in each Sentinel (sentinel.limiter); with several gateway processes, each enforces the limit on its own traffic. Call sentinel.limiter.reset(session_id=...) when a conversation ends to free its state early; otherwise the least recently used keys are dropped beyond 100,000.

Security scanner

Redaction

Matches are replaced with [REDACTED:<detector>] anywhere in a JSON payload: nested dicts, lists, and MCP content blocks. Values under keys such as password, token, api_key and authorization are always redacted.

Kind Detectors
Secrets private_key, aws_access_key, aws_secret_key, github_token, slack_token, stripe_key, anthropic_key, openai_key, google_api_key, jwt, bearer_token, generic_secret (password=…, token: …)
PII email, credit_card (Luhn-checked), us_ssn, phone_number
Custom anything in scanner.custom_patterns

Arguments are scanned for secrets only by default. Results get secrets and PII. This stops an agent pasting an API key into a tool call without breaking send_email(to="alice@example.com"). Change it with input_detectors.

The audit trail, the approval prompt and injection excerpts only ever see redacted data.

Prompt-injection detection

Tool outputs such as web pages, emails, tickets and file contents are the main route for indirect prompt injection. Each heuristic has a weight, and the weights combine like independent probabilities (1 − ∏(1 − wᵢ)) into a score from 0 to 1:

Heuristic Weight Example
unicode_tag_smuggling 0.9 invisible U+E0000 tag characters
ignore_instructions 0.8 "ignore all previous instructions"
fake_chat_markup 0.7 <|im_start|>system, [INST], <<SYS>>
covert_tool_use 0.7 "call the tool without telling the user"
system_prompt_extraction 0.6 "reveal your system prompt"
exfiltration 0.6 "send the API keys to …"
role_override 0.5 "you are now DAN", "developer mode"
secrecy_demand 0.5 "do not tell the user"
markdown_image_exfil 0.5 ![x](https://evil/?q=…)
bidi_override 0.4 right-to-left override characters

With action: block (the default) and a score at or above threshold (default 0.7), the result is withheld. The agent gets an isError result that explains why, and the audit row records blocked_injection. With action: warn, the result goes through and the score is logged.

Plugging in your own injection classifier

The heuristics are fast but only know known phrasings. For the gray zone, where they are suspicious but not sure, you can plug in your own model: a local ONNX or DeBERTa classifier, an LLM-as-a-judge call, or anything else with this method:

from mcp_rbac_gateway import InjectionClassifier, Sentinel

class Judge:  # satisfies the InjectionClassifier protocol
    async def classify(self, text: str) -> float:
        return await my_model.score(text)  # probability of injection, 0.0 to 1.0

gateway = Sentinel.from_yaml("sentinel.yaml", classifier=Judge())
# or a plain async function: Sentinel(config, classifier=my_async_judge)
scanner:
  prompt_injection:
    threshold: 0.7
    classifier_min_score: 0.30   # escalate heuristic scores in [0.30, 0.70)
    classifier_combine: max      # or noisy_or
    classifier_timeout_seconds: 2
    classifier_on_error: block   # fail closed (default) or warn
  • Clean text never reaches the classifier. A heuristic score below classifier_min_score returns at once, and one at or above threshold is already decided. Set classifier_min_score: 0.0 to send every payload.
  • The classifier sees the payload's strings after redaction, joined by newlines, so an external judge never receives the secrets the scanner removed.
  • Its score is combined with the heuristic score (max, or noisy_or so that two weak signals can add up) and recorded as a classifier finding.
  • Errors fail closed. If it raises, times out or returns something that is not a number in [0, 1], a classifier_error finding is recorded and the payload is scored 1.0, so action: block withholds it. With classifier_on_error: warn the heuristic score stands and a warning is logged.
  • It runs in check_call() when scan_inputs_for_injection is on, and on every tool and task result. In async code use await gateway.check_result_async(result); check_result() is the blocking form. needs_approval() and non-tool methods use the heuristics only.
  • The package adds no dependency for this: the model and its runtime are yours.

Human-in-the-loop approvals

A call needs approval when any of these match:

  • the agent's require_approval globs,
  • hitl.tools (applies to every agent),
  • a hitl.rules entry, for example "run_sql when query matches drop|delete|truncate",
  • the MCP tool annotation destructiveHint: true (cached from tools/list).

The call fails closed. It only reaches the tool after an explicit approve. A deny, an error, an unreachable approver or a timeout all block it.

Mode How it asks
cli [y/N] prompt on /dev/tty, so it works while stdin and stdout carry the MCP protocol.
webhook POSTs the request to hitl.webhook.url. The receiver answers inline with {"approved": true} or later calls the approval API.
api Waits for the approval API only (your own UI calls POST /approvals/{id}/approve).
auto_approve / auto_deny For tests and CI.

Webhook payload:

{
  "type": "mcp_rbac_gateway.approval_request",
  "request": {"id": "9f1c…", "agent_id": "ops-agent", "tool": "delete_file",
              "arguments": {"path": "docs/old.md"}, "reason": "…", "timeout_seconds": 300},
  "approve_url": "https://sentinel.internal/approvals/9f1c…/approve",
  "deny_url": "https://sentinel.internal/approvals/9f1c…/deny"
}

The approval API is a FastAPI router you can mount in your own app. mcp-rbac-gateway serve includes it. To run it next to a stdio proxy, pass --approval-port:

mcp-rbac-gateway wrap -c sentinel.yaml --approval-port 8787 -- python my_server.py

To mount it in your own FastAPI app:

from mcp_rbac_gateway import create_approval_router
app.include_router(create_approval_router(sentinel.broker, token="shared-secret"))
# or reuse your own auth:  create_approval_router(sentinel.broker, dependencies=[Depends(current_user)])
# GET  /approvals                 pending requests
# POST /approvals/{id}/approve    {"approver": "alice", "comment": "ok"}   409 if already decided
# POST /approvals/{id}/deny

The router fails closed: with neither token nor dependencies it raises ValueError, unless you pass allow_unauthenticated=True. serve and proxy-http mount /approvals only with a token (hitl.webhook.token_env) or --allow-unauthenticated-approvals, and refuse to start in webhook/api mode without one, because calls would wait on an API anyone could answer.

Which mode when you mount the router

hitl.mode With the router mounted by your app
api Calls wait for a decision on your router. Use this when people decide in your UI.
webhook The same, plus a POST per request to hitl.webhook.url (Slack, paging).
auto_deny Nothing waits on the router: approvals are denied at once and the queue stays empty. Use it to switch approvals off in an environment.
cli Prompts on the server's terminal. Wrong for a server.

With check_call(..., wait=False) the mode doesn't matter: the request goes to the store and your code decides (see Multi-tenant hosts).

Durable, multi-replica approvals. hitl.store: sqlite keeps pending requests in a table of the audit database (WAL mode). A restart loses nothing, any replica that shares the file can list and decide a request, and a waiting call notices the decision by polling the store with backoff. Decisions are atomic: of two concurrent approvals, exactly one wins and the other gets 409. For replicas on different hosts, use hitl.store: redis or hitl.store: postgres (see Running several replicas). For anything else, implement the five-method ApprovalStore protocol (mcp_rbac_gateway.approvals); a store may add a wait_for_change hook so waiters don't poll. Requests carry tenant_id, session_id and request_id, so GET /approvals can be scoped per tenant (require_scope=) and an approval links to its audit rows.

Custom logic, such as Slack buttons, a ticketing system or a second model as a reviewer, is one class:

from mcp_rbac_gateway import ApprovalRequest, ApprovalResponse, Sentinel

class SlackApprover:
    async def request_approval(self, request: ApprovalRequest) -> ApprovalResponse:
        ok = await post_to_slack_and_wait(request)
        return ApprovalResponse(approved=ok, approver="slack")

sentinel = Sentinel.from_yaml("sentinel.yaml", approver=SlackApprover())

Stateless MCP (2026-07-28)

The 2026-07-28 revision of MCP removes the initialize handshake and Mcp-Session-Id. Every request carries its protocol version and client info in params._meta, and Streamable HTTP requests carry routing headers so that load balancers can route without parsing the body. mcp-rbac-gateway proxy-http is a reverse proxy for that transport:

mcp-rbac-gateway proxy-http -c sentinel.yaml --upstream-url http://localhost:8000/mcp --port 8765

Header checks. Before anything is forwarded, the proxy checks the headers against the body and answers 400 with a JSON-RPC error when they disagree. Policy is then decided on the body. A router that trusts Mcp-Name: echo can't be used to slip a delete_file call past the gateway.

Header Rule Error
MCP-Protocol-Version required, a supported version, equal to _meta["io.modelcontextprotocol/protocolVersion"] -32022 / -32020
Mcp-Method required, equal to the JSON-RPC method -32020
Mcp-Name required for tools/call, prompts/get (params.name), resources/read (params.uri) and tasks/get|update|cancel (params.taskId); =?base64?…?= values are decoded -32020
Mcp-Param-* forwarded. When redaction changes an argument that the tool's inputSchema mirrors with x-mcp-header, the header is rewritten to match -

The proxy also strips any Mcp-Session-Id, rejects JSON-RPC batches (send one message per POST), and answers GET and DELETE with 405. Keep using serve for 2025-era clients and servers.

_meta is preserved and audited. Only params.arguments is ever rewritten (by redaction). _meta reaches the server exactly as the client sent it, in every transport. The audit trail stores method, protocol_version, client_name, client_version, traceparent, tracestate and the full _meta (after redaction), so you can find a gateway decision from a trace id:

AuditLog(".sentinel/audit.db").query(trace_id="0af7651916cd43dd8448eb211c80319c")

clientInfo is self-reported, so it is recorded but never used for identity. Identity still comes from --agent, X-Sentinel-Agent or X-Sentinel-Token.

Tasks (io.modelcontextprotocol/tasks). When a tools/call returns resultType: "task", the gateway remembers which agent and tool created it.

  • tasks/get, tasks/update and tasks/cancel carry only a taskId, and they are refused (-32602, as for an unknown task) unless the same agent created it. This is tasks.bind_to_agent.
  • Task results get the same redaction and injection check as tool results. A poisoned result is replaced with an error. Polls of a running task aren't audited one by one; the final state is, and its row is attributed to the original tool.
  • tasks/update inputResponses are redacted before they reach the server.

By default the task map lives in memory. Behind several gateway replicas, set tasks.store: redis (see Running several replicas), or route on Mcp-Name so that polls reach the replica that saw the task.

Skills (io.modelcontextprotocol/skills). skills/list is filtered per agent, like tools/list. skills/get, resources/read and resources/directory/read on skill:// URIs need a matching skills rule. Skill content is scanned for prompt injection before the model sees it.

agents:
  researcher:
    allow: ["search_*"]
    skills:
      allow: ["pdf-processing", "acme/*"]   # globs on skill://<path>/SKILL.md
      deny: ["acme/internal"]               # also covers every file under it
    methods:
      deny: ["tasks/cancel"]                # this agent may poll tasks but not cancel them

Running several replicas

A stateless gateway scales by adding replicas behind a plain load balancer. Each replica loads the same sentinel.yaml, so policy needs no coordination. Two pieces of runtime state must be shared, and 0.4.0 can keep both outside the process:

  • pending approvals, so a human can approve on any replica and the waiting call, on whichever replica holds it, wakes up;
  • task ownership, so tasks/get, tasks/update and tasks/cancel work on any replica, not only the one that saw the tools/call that created the task.
pip install "mcp-rbac-gateway[server,redis]"      # or [server,postgres] for approvals
hitl:
  mode: api
  store: redis                              # or: postgres
  store_url: ${SENTINEL_REDIS_URL}          # postgresql://user:${PGPASSWORD}@db/sentinel
tasks:
  store: redis
  store_url: ${SENTINEL_REDIS_URL}

Which approval store?

hitl.store Survives a restart Shared by Waiters learn of a decision
memory (default) no this process only at once (in-process future)
sqlite yes processes on one host or one shared volume store re-read at the poll interval, 50 ms backing off to 1 s
redis yes (with Redis persistence) replicas on any host Redis pub/sub, at once
postgres yes replicas on any host LISTEN/NOTIFY, at once

How the shared stores work:

Store Atomic decision How a waiting call learns of it
RedisApprovalStore A Lua script: only a request still pending and unexpired is changed Redis pub/sub on {prefix}:approvals
PostgresApprovalStore UPDATE … WHERE id = %s AND status = 'pending' AND expires_at > now pg_notify in the same transaction, LISTEN on one connection per event loop
RedisTaskStore One key per task, with a Redis TTL (no waiting)
  • Of two replicas deciding the same request at once, exactly one wins and the other gets 409, as with SQLite.
  • A decision made on any replica wakes the waiting call at once: the broker waits on its own future and on the store's wait_for_change() (pub/sub or NOTIFY) together. If a message is lost, the waiter still re-reads the store at its poll interval (50 ms, backing off to 1 s).
  • The Postgres store creates its table (mcp_rbac_gateway_approvals) on first use. Pass create_schema=False if your migrations own it. If you pass your own pool=, also pass the dsn, because LISTEN needs its own connection; without it waiters poll.
  • Approval keys in Redis share the hash tag {mcp-rbac-gateway}, so they live in one slot on Redis Cluster. Decided requests are kept for an hour after their deadline, then Redis drops them.
  • Task ownership has no Postgres store; use Redis, or sticky routing on Mcp-Name.
  • The client libraries are imported only when such a store is created; the core install doesn't need them. Sentinel.close() closes the stores it built from the config, but not stores you pass in.

In code, pass the stores yourself:

from mcp_rbac_gateway import (
    ApprovalBroker, PostgresApprovalStore, RedisTaskStore, Sentinel,
)

sentinel = Sentinel(
    config,
    broker=ApprovalBroker(PostgresApprovalStore("postgresql://app@db/sentinel")),
    task_store=RedisTaskStore("redis://cache:6379/0"),
)

What is still per replica. Know these before you scale out:

  • Rate limits and loop detection are counted in memory by each process. With N replicas and no sticky routing, an agent can make up to N times rate_limit calls, and a loop is only caught when the repeats land on the same replica. Route by session (for example on a session header or cookie) if you need tighter limits.
  • The audit trail is a SQLite file per audit.path. Replicas on different hosts write different files, each with its own hash chain, so report and verify-audit run per file. Ship rows to central storage if you need one view.
  • The tools/list annotation cache (for destructiveHint) fills per process from the tools/list responses that replica has seen.

Python API & decorator

from mcp_rbac_gateway import Sentinel, ToolBlockedError, agent_context, guard

sentinel = Sentinel.from_yaml("sentinel.yaml")

@guard(sentinel)                          # async or sync functions
async def delete_file(path: str) -> str: ...

@guard(sentinel, tool="db.query", agent_id="reporting", on_block="return")
def run_query(sql: str) -> list[dict]: ...

try:
    with agent_context("support-bot"):    # contextvars: follows awaits and worker threads
        await delete_file("/workspace/a")
except ToolBlockedError as exc:
    print(exc.decision, exc.reason)       # AuditDecision.BLOCKED_POLICY, "tool 'delete_file' …"
  • The function receives sanitised arguments, with secrets already redacted, and its return value is redacted and scanned before it reaches the caller.
  • on_block="result" returns a ToolDenial instead of raising: tool, decision, reason, retryable, hint, request_id, approval_id. denial.to_text() is safe to put in a prompt: it never echoes the blocked arguments, withheld output or an exception message, and it tells the model whether to retry (retryable is true only for approval_timeout and tool errors). This is usually what you want inside an agent loop.
  • on_block="return" (0.2 behaviour) returns a "[mcp-rbac-gateway] …" string.
  • Sync code. @guard works on plain def functions, and sentinel.call_sync(...) / check_call_sync(...) / resume_call_sync(...) are blocking forms. With no running event loop they use asyncio.run. Inside a running loop (a sync tool called by LangGraph, for example) they never call asyncio.run: the async part runs on a worker thread with your context variables, and your function still runs in the calling thread. Don't call them from a coroutine on the loop itself; that blocks the loop. Use the async forms there.
  • Request context. call(), @guard and check_call() take context=CallContext(...), or read it from with call_context(...). See Multi-tenant hosts.
  • Lower-level building blocks: sentinel.check_call(...), sentinel.check_result(...), sentinel.record(...), sentinel.call(tool, args, fn), sentinel.visible_tools(...), sentinel.needs_approval(...), plus PolicyEngine, Scanner, ApprovalGate and AuditLog, which you can use on their own.
  • 0.4.0 additions. Sentinel(classifier=..., task_store=...); await sentinel.check_result_async(result); CallVerdict.retry_after_seconds, shadow_decision and shadow_reason; ToolDenial.retry_after_seconds; ResultCheck.shadow_reason; sentinel.limiter (a CallLimiter, with reset(tenant_id=..., session_id=...)); PolicyEngine.call_limits(agent, tool) and enforcement_mode(agent); AuditLog.verify_chain(key=...) returning a ChainVerificationResult; and the stores RedisApprovalStore, PostgresApprovalStore, MemoryTaskStore and RedisTaskStore behind the ApprovalStore and TaskStore protocols.

Multi-tenant hosts

A host that serves many tenants needs every audit row and approval tagged with the tenant and the model's tool-call id, an audit API that can't leak across tenants, approvals that survive restarts and replicas, and a way to pause with its own durable mechanism (LangGraph interrupt, a Temporal signal) instead of a waiting coroutine. The full runnable version is examples/multi_tenant.py.

# sentinel.yaml
agents:
  member: {allow: ["read_*", "search"]}
  admin:  {inherits: [member], allow: ["delete_*"], require_approval: ["delete_*"]}
hitl:
  mode: api            # decisions come from your app, not a terminal
  store: sqlite        # pending approvals live in the audit DB: restart- and replica-safe
  timeout_seconds: 3600
audit:
  path: /data/gateway.db

1. Tag every call with its tenant. Bind the context once around the agent run (or per tool call). It is a context variable, so it follows await and worker threads and never leaks between concurrent requests. Every row the call writes (allowed, blocked, injection, error, approval) carries it, and traceparent is filled from the current OpenTelemetry span when OpenTelemetry is installed.

from mcp_rbac_gateway import CallContext, Sentinel, ToolDenial, call_context

gateway = Sentinel.from_yaml("sentinel.yaml")

with call_context(tenant_id=user.tenant, session_id=thread_id, request_id=tool_call.id,
                  labels={"plan": "pro"}):
    out = await gateway.call(tool_call.name, tool_call.args, run_tool,
                             agent_id=user.role, wait=False, on_block="result")
# or explicitly: gateway.call(..., context=CallContext(tenant_id=..., request_id=...))

2. Pause your own way, resume later. With wait=False a call that needs approval returns at once (decision == "pending_approval", with approval_id). The request is in the store and on the audit trail. Pause, then finish with resume_call, which writes the decision with the same tenant and request ids:

from langgraph.types import interrupt

if isinstance(out, ToolDenial):
    if out.decision == "pending_approval":
        answer = interrupt({"approval_id": out.approval_id, "tool": out.tool})  # checkpointed
        out = await gateway.resume_call(out.approval_id, answer["approved"], run_tool)
    else:
        return out.to_text()          # tell the model; never echoes the blocked payload

A second decision on the same request raises ApprovalConflict (409 on the router). Deciding a request that has expired writes approval_timeout.

3. A tenant-scoped audit API. create_audit_router serves GET /audit with filters (agent, tool, decision, blocked_only, since, session_id, request_id, tenant_id, trace_id, limit ≤ 500) and keyset pagination (before_id, stable while rows are written). When require_scope returns a tenant, it is forced into the query, whatever the caller asks for:

from fastapi import Depends
from mcp_rbac_gateway import create_approval_router, create_audit_router

def tenant_of(request) -> str:            # e.g. the tenant claim of the verified JWT
    return request.state.user.tenant

app.include_router(create_audit_router(gateway.audit, require_scope=tenant_of,
                                       dependencies=[Depends(current_user)]))
app.include_router(create_approval_router(gateway.broker, require_scope=tenant_of,
                                          dependencies=[Depends(current_user)]))

From Python: gateway.audit.query(tenant_id="acme", request_id="call_1") and gateway.audit.page(tenant_id="acme", limit=100, before_id=cursor). The events table is a public, versioned schema (PRAGMA user_version, migrated forward on open, changed only by adding columns), so your own SQL on it is supported too.

4. The same through the HTTP proxy. Give HttpProxy, StatelessHttpProxy or DualHttpProxy a context_resolver(headers, body) -> CallContext (called once per request; its result goes on every row the request writes) and an agent_resolver(headers) -> role that replaces X-Sentinel-Token (for example a role claim of the caller's OAuth token). Either may be async; raising PermissionError answers 401.

def tenant_from_jwt(headers, body) -> CallContext:
    claims = verify_jwt(headers.get("authorization", ""))   # raises PermissionError if invalid
    return CallContext(tenant_id=claims["tenant"], session_id=claims.get("sid"))

def role_from_jwt(headers) -> str | None:
    return verify_jwt(headers.get("authorization", ""))["role"]

proxy = DualHttpProxy(gateway, "http://mcp-server:8000/mcp",
                      context_resolver=tenant_from_jwt, agent_resolver=role_from_jwt,
                      approval_dependencies=[Depends(current_user)])
app = proxy.build_app()

DualHttpProxy (CLI: proxy-http --dual-era) serves both protocol eras on one endpoint: a POST whose MCP-Protocol-Version is 2026-07-28 takes the stateless path with its header checks, and everything else (a 2025-era initialize, session requests, GET, /sse) takes the HttpProxy path.

To test a proxy without sockets, pass transport=httpx.ASGITransport(app=upstream_app): the proxy then reaches your in-process ASGI MCP server through it.

Performance

Measured with benchmarks/overhead.py (python benchmarks/overhead.py): Sentinel.call around a no-op async tool, 2,000 calls per case, Python 3.13, 4 vCPU Linux cloud VM, local SSD. Times are gateway overhead per call in milliseconds.

case p50 p95 p99
allowed, audit off 0.07 0.10 0.12
allowed, SQLite audit (writer: sync) 0.62 0.91 1.54
allowed, SQLite audit (writer: batched) 0.09 0.15 0.22
denied by policy, SQLite audit (sync) 0.59 0.90 1.90
output scan of a 2 kB result 0.82 1.19 1.32

Most of the cost of an audited call is the committed SQLite write. audit.writer: batched moves it off the hot path: rows go to a bounded queue and one thread writes them in batches. Reads through the same AuditLog flush first, and close() flushes, but rows still queued when the process is killed are lost. Keep sync when every row must be on disk before the call returns. Run the script on your own hardware: disk fsync time dominates the sync numbers.

What the 0.4.0 features add to that path (not yet in the benchmark table):

  • Rate limits and loop detection: in-memory dictionary work under one lock, with no I/O. Only agents with a limit configured pay it.
  • Hash chain: each write also reads the chain head inside the same BEGIN IMMEDIATE transaction and hashes the row. It is still one transaction per row (sync) or per batch (batched).
  • Classifier: nothing for payloads outside the gray zone. Inside it, one call to your model, bounded by classifier_timeout_seconds.
  • Redis and Postgres stores: network round trips only when a call needs approval or touches a task. Ordinary allowed and denied calls never reach the store.

Audit trail & dashboard

Every call produces one row in SQLite (WAL mode, so report can read while a proxy writes):

column
ts, agent_id, tool, decision, reason what happened and why (including the rule that matched)
latency_ms end-to-end time, including any approval wait
transport, request_id, session_id stdio / http / http-stateless / sse / python
method tools/call, or tasks/get, skills/get, resources/read ...
protocol_version, client_name, client_version, traceparent, tracestate, meta from the request's params._meta
approver who approved or denied
arguments, result after redaction; result only with log_results: true
findings, redactions, injection_score what the scanner found (never the secret itself)
tenant_id, labels, approval_id from the call's CallContext; approval_id links the pending_approval row to its decision
prev_hash, row_hash the hash chain, with audit.tamper_evident: true (schema 4, 0.4.0)

The decision column takes these values:

decision Counts as a block Retryable (ToolDenial) Since
allowed, approved no - 0.1
blocked_policy yes no 0.1
blocked_injection yes no 0.1
denied_by_human yes no 0.1
approval_timeout yes yes 0.1
error (the tool raised) no yes 0.1
pending_approval (an approval was requested; the decision is a second row) no no 0.3
blocked_rate_limit yes yes, after retry_after_seconds 0.4
blocked_loop yes no 0.4
shadow_blocked (shadow mode: would have been blocked, ran anyway) no - 0.4

A call that shadow mode let through also has a shadow_blocked row (see Shadow mode). summary() and report count calls, so neither pending_approval nor shadow_blocked rows add to the call or block totals.

Since 0.3.0 this is a public schema, versioned with PRAGMA user_version and migrated forward on open. Columns are only ever added.

mcp-rbac-gateway report --since 7d                 # dashboard
mcp-rbac-gateway report --agent ops-agent --limit 50
mcp-rbac-gateway report --watch 2                  # live refresh
mcp-rbac-gateway report --json | jq .by_decision   # for scripts and alerts

Or query it from Python with AuditLog(path).query(blocked_only=True, tenant_id="acme"), .page(...) and .summary(), or mount create_audit_router (see Multi-tenant hosts).

Tamper-evident hash chain

Off by default. Turn it on and every new row is linked to the one before it:

audit:
  tamper_evident: true
  signing_key_env: AUDIT_HMAC_KEY   # optional: HMAC-SHA256 instead of plain SHA-256

row_hash covers the previous row's row_hash plus the row's ts, agent_id, tool, decision, reason, arguments (as stored, after redaction), tenant_id and approval_id. The head of the chain is read and the row written in one BEGIN IMMEDIATE transaction, so the sync and batched writers, and several processes sharing the file, all extend one chain.

$ mcp-rbac-gateway verify-audit -c sentinel.yaml
audit chain OK: 1,204 row(s) verified
head: id 1204 hmac-sha256:9f2c…

$ sqlite3 .sentinel/audit.db "UPDATE events SET decision='allowed' WHERE id=812"
$ mcp-rbac-gateway verify-audit -c sentinel.yaml; echo $?
audit chain BROKEN at row id 812 (1 problem(s) shown)
  id 812: row_hash does not match the row: modified
1

A modified row is reported at its own id, and a deleted row at the id of the row after it. --json prints the full ChainVerificationResult; from Python, call AuditLog(path).verify_chain(). Exit codes: 0 verified, 1 broken, 2 missing database, missing key, or no chained rows.

What it does and does not prove:

  • With plain SHA-256, anyone who can write the file can also recompute every later hash. Use signing_key_env and keep the key away from the machine that holds the database if that matters to you.
  • Deleting the newest rows leaves a shorter chain that still verifies. Record head_hash somewhere else (a log line, a ticket, a WORM bucket) to catch that.
  • Rows written before the chain was turned on have no hash and are reported as unchained_rows. Turning the chain off again later makes new rows show up as breaks.
  • verify-audit checks with one key. A file whose rows mix plain SHA-256 and HMAC, or two different keys, does not verify, so start a new audit.path when you add or rotate the key.
  • The hash covers the fields listed above. The others (latency_ms, findings, labels, meta, result ...) are not covered, so an edit to them is not detected.
  • A chain is per database file. Replicas that write different files have separate chains.

CLI reference

Command Purpose
mcp-rbac-gateway wrap -c CFG [--agent A] [--approval-port P] -- CMD… stdio proxy around an MCP server process
mcp-rbac-gateway serve -c CFG --upstream-url URL [--port 8765] HTTP proxy (Streamable HTTP at /mcp, legacy SSE at /sse), with the approval API when it has a token
mcp-rbac-gateway proxy-http -c CFG --upstream-url URL [--dual-era] stateless Streamable HTTP proxy for MCP 2026-07-28; --dual-era also serves 2025-era clients on the same endpoint
mcp-rbac-gateway report [--db DB] [--since 24h] [--agent A] [--json] [--watch N] Rich dashboard; shadow-mode would-be blocks get their own yellow panel
mcp-rbac-gateway verify-audit [--db DB] [-c CFG] [--key-env VAR] [--json] check the audit hash chain (0.4); exit 0 verified, 1 broken (prints the first bad row id), 2 no database, key not set, or nothing chained
mcp-rbac-gateway validate -c CFG validate the config and print effective policies
mcp-rbac-gateway check-policy CFG [-t TOOL]… [-a AGENT]… each agent's inheritance chain and effective allow/deny/approval, plus a decision per --tool; a shadow agent's denials show as deny (shadow)
mcp-rbac-gateway check TOOL 'JSON' -a AGENT dry-run one decision (exit code 1 if denied)
mcp-rbac-gateway init [PATH] write a starter config

wrap, serve and proxy-http take --allow-unauthenticated-approvals to serve /approvals without a token on purpose.

In wrap, stdout carries the MCP protocol, so all logs and prompts go to stderr and /dev/tty.

verify-audit reads audit.path and audit.signing_key_env from -c (default ./sentinel.yaml when it exists); --db and --key-env override them. Run it from cron or CI and alert on a non-zero exit, and keep the printed head: line somewhere the gateway host can't write.

Upgrading from 0.3

Nothing in 0.4.0 is on by default, so a 0.3 sentinel.yaml keeps its meaning. Check these points before you deploy:

  • The audit database moves to schema version 4. The first 0.4 process to open it adds the prev_hash and row_hash columns and sets PRAGMA user_version = 4, whether or not tamper_evident is on. A 0.3 process then refuses the file ("has schema version 4"), so upgrade every process that shares an audit file together, and back the file up first if you may need to roll back.
  • New decision values: blocked_rate_limit, blocked_loop and shadow_blocked. If your own SQL, dashboards or alerts on events list decisions explicitly, add them. The first two are blocks; shadow_blocked is not, and like pending_approval it is an extra row next to the call's own row, so exclude it when you count calls.
  • report --json and AuditSummary gain shadow_blocked and shadow.
  • rate_limit and max_consecutive_identical_calls under arguments.<tool-glob> with a scalar value are now limits. A mapping under those names is still a constraint on an argument with that name.
  • check_result() takes agent_id=. Pass it if you call check_result yourself, so that a shadow-mode agent's withheld output is shadowed rather than blocked.
  • Turning on the hash chain on an existing file leaves the old rows unchained; they are reported as unchained_rows, not as breaks.
  • The [server] extra caps opentelemetry-api below 1.46, because FastAPI 0.165's request telemetry fails with 1.46. Pin accordingly if you install FastAPI yourself.
  • New optional extras: [redis] (redis>=5.0) and [postgres] (psycopg[binary,pool]>=3.1), needed only for those stores.

Examples

File What it shows
examples/langgraph_agent.py A LangGraph StateGraph + ToolNode agent with guarded tools: a poisoned search result is withheld, customer PII is redacted, path traversal and write SQL are denied. Runs offline with a scripted model; set ANTHROPIC_API_KEY to use Claude.
examples/fastapi_app.py A FastAPI service with guarded tool endpoints, the same agent behind /agent/run, the approval API, and /audit/summary. The ops agent pauses on delete_file and DROP TABLE until someone calls /approvals/{id}/approve.
examples/multi_tenant.py A multi-tenant FastAPI host: call_context, wait=False with an external pause and resume_call, the SQLite approval store, and a tenant-scoped audit router.
examples/sentinel.yaml The policy both examples use.
examples/claude_desktop_config.json Guarding an off-the-shelf MCP server in Claude Desktop.
python examples/langgraph_agent.py
uvicorn examples.fastapi_app:create_app --factory --port 8000

Both examples run as part of the test suite (tests/test_examples.py).

Security model and limits

mcp-rbac-gateway is defence in depth, not a sandbox.

  • Detection is heuristic. The injection scanner catches common attack patterns, not all of them. A plugged-in classifier helps in the gray zone but is a model, not a proof. Pair both with least-privilege policies and approvals for anything destructive.
  • Redaction is pattern-based. Add custom_patterns for secret formats specific to your organisation.
  • Identity comes from the transport. With wrap, whoever launches the proxy picks --agent. With serve, set token_env on agents so callers must present X-Sentinel-Token; the X-Sentinel-Agent header alone is then ignored.
  • Rate limits are per process. rate_limit and max_consecutive_identical_calls are counted in memory, so N replicas allow up to N times the limit in total. They stop runaway agents; they are not a billing-grade quota.
  • Shadow mode enforces nothing. An agent in enforcement_mode: shadow can call every tool its policy would deny, and sees every tool in tools/list. Only approvals and redaction still apply. Use it on trial rules, not as a standing configuration for an agent you don't trust.
  • The audit trail is tamper-evident only when you turn it on, and then only within its limits: plain SHA-256 can be recomputed by anyone who can write the file, truncation of the newest rows is caught only if you kept the head_hash, and columns outside the hash are not covered. See Tamper-evident hash chain.
  • A classifier is a dependency of your security path. By default its errors and timeouts fail closed (classifier_on_error: block), so an outage of an external judge withholds gray-zone results. That is the safe default; size classifier_timeout_seconds for it.
  • Shared stores are trusted. Anyone who can write to the Redis or Postgres used for hitl.store can approve requests, and anyone who can write tasks.store can reassign task ownership. Protect them like the approval API's token.
  • Fail closed. Unknown agents get default_agent. Unknown tools are denied by default. Approval errors and timeouts block the call.
  • JSON-RPC batches are inspected item by item (serve, wrap); proxy-http rejects them. Messages the proxy doesn't need to understand pass through unchanged.

See SECURITY.md for how to report a vulnerability.

Development

pip install -e ".[dev,langgraph]"   # dev includes redis, psycopg and fakeredis[lua]
pytest -q          # unit tests, plus integration against mock stdio/HTTP/SSE MCP servers
python benchmarks/overhead.py
ruff check src tests examples && mypy src

The integration tests start real mcp-rbac-gateway wrap processes and real uvicorn servers in front of mock MCP servers (tests/mock_mcp_server.py, tests/mock_http_server.py). They also check that a blocked call never reaches the upstream server.

The Redis and Postgres store tests run offline by default: Redis on fakeredis, which executes the real Lua scripts, and Postgres on a SQLite-backed fake of the psycopg pool. To run the same tests against real servers, set MCP_RBAC_GATEWAY_TEST_REDIS_URL and MCP_RBAC_GATEWAY_TEST_POSTGRES_DSN. CI does this too, in a separate job with Redis 7 and Postgres 16 service containers.

See CONTRIBUTING.md. Released under the MIT License.

Metadata

Release files for mcp-rbac-gateway 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mcp-rbac-gateway 0.4.0
File Size Uploaded Provenance Actions
mcp_rbac_gateway-0.4.0.tar.gz 203.4 kB With provenance Details for mcp_rbac_gateway-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mcp-rbac-gateway 0.4.0
File Interpreter ABI Platform Actions
mcp_rbac_gateway-0.4.0-py3-none-any.whl Python 3 none any Details for mcp_rbac_gateway-0.4.0-py3-none-any.whl

Total release size: 327.2 kB

Release files / mcp_rbac_gateway-0.4.0.tar.gz

Download URL mcp_rbac_gateway-0.4.0.tar.gz
Size 203.4 kB
Tags Source
SHA-256 checksum
How to use checksums
bfde766213674c089dc1af71b9362b894f00412c3d35fcafa213b06308873bc9
BLAKE2b-256 checksum
How to use checksums
1201a1688e3f325610eeeb6a33f22d158bb46dd8bdf40921cce78c1e2f7a42d8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Release files / mcp_rbac_gateway-0.4.0-py3-none-any.whl

Download URL mcp_rbac_gateway-0.4.0-py3-none-any.whl
Size 123.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
06caeb09bdca4177bf1b7ecf69c474abbb22e798cdf69042722d3efb304f7e40
BLAKE2b-256 checksum
How to use checksums
1daa01c6d192f2c75e9541dafd1508e6627b850ce8727ed973dbcde9e52dd7fa
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Security for mcp-rbac-gateway 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for mcp_rbac_gateway-0.4.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page