Skip to main content
Glama
mcp-gatekeeper
by vaibhav4046

mcp-gatekeeper

A deterministic, model-free safety proxy that sits between AI agents and PostgreSQL, exposed as an MCP server. Every statement an agent sends passes a role-based sqlglot AST policy, an optimistic-concurrency check, post-write invariants and a per-session circuit breaker, inside a savepoint-backed transaction. Every call lands in a hash-chained, optionally HMAC-signed JSONL trace. There are no LLM calls anywhere in the path.

demo

make demo: an agent talking to the gatekeeper over MCP (terminal capture rendered by examples/demo.py).

Quickstart (under a minute with Docker and uv installed)

git clone https://github.com/vaibhav4046/mcp-gatekeeper && cd mcp-gatekeeper
make up                       # PostgreSQL 16 with demo schema and a least-privilege role
uv run mcp-gatekeeper doctor  # connectivity, policy validity, role permissions
make demo

Add it to Claude Code (stdio; the server's identity and role come from your policy, not the model):

claude mcp add gatekeeper \
  -e DATABASE_URL=postgresql://gatekeeper_app:gatekeeper_app@localhost:5432/gatekeeper \
  -e GATEKEEPER_AGENT=default \
  -- uvx --from git+https://github.com/vaibhav4046/mcp-gatekeeper mcp-gatekeeper serve

or in a project .mcp.json:

{
  "mcpServers": {
    "gatekeeper": {
      "command": "uvx",
      "args": ["--from", "git+https://github.com/vaibhav4046/mcp-gatekeeper", "mcp-gatekeeper", "serve"],
      "env": {
        "DATABASE_URL": "postgresql://gatekeeper_app:gatekeeper_app@localhost:5432/gatekeeper",
        "GATEKEEPER_AGENT": "default"
      }
    }
  }
}

The container image serves streamable HTTP: docker compose --profile app up -d, then point a client at http://localhost:8000/mcp.

Related MCP server: mcp-postgres-guard

Results

50 adversarial scenarios, 10 per category. Each runs twice with the same agent code: once against a plain SQL executor (autocommit, no checks, which is how a typical SQL MCP tool behaves) and once through the gatekeeper with the default policy. From benchmarks/results.json, generated by make benchmark at 2026-11-22T01:27:31Z (WSL2 Ubuntu 24.04, Python 3.11.18, PostgreSQL 16.16 in Docker, on a laptop whose CPU was 40-70% busy with other jobs).

Category

Corrupted, unprotected

Corrupted, protected

Expected block/rollback verdict

Destructive queries

8/10 (80%)

0/10 (0%)

10/10 (100%)

Prompt-injected SQL / boundary probing

9/10 (90%)

0/10 (0%)

10/10 (100%)

Concurrent write races

9/10 (90%)

0/10 (0%)

9/10 (90%)

Runaway retry / mutation loops

8/10 (80%)

0/10 (0%)

10/10 (100%)

Multi-step partial failures

10/10 (100%)

0/10 (0%)

10/10 (100%)

All 50

44/50 (88%)

0/50 (0%)

49/50 (98%)

Reading the table honestly:

  • The one "expected verdict" miss (X04) is not a safety miss: the two opposite transfers happened not to overlap in that run, so no conflict was needed and the final state was correct. Race timing varies; the previous run (one small performance change earlier) scored 50/50 on that column. Protected corruption was 0/50 in both runs.

  • An earlier version of this project scored 2/50 protected. Two policy features closed those cases; the scenarios were not changed:

    • I10 (semantic injection: credit an account with 1,000,000 using a correct row version) is now refused by a declarative change_limits rule (accounts.balance may change by at most 10,000 per row per statement). Without that rule in the policy it passes, because the SQL is structurally fine.

    • R10 (a loop that deletes and commits every iteration) used to lose the 20 rows committed before the breaker tripped. The breaker now compensates: it replays before-images captured at write time to reverse the session's committed changes, all or nothing, and only where the row is still exactly as the session left it.

  • In the unprotected column, two destructive scenarios were stopped by PostgreSQL's own foreign keys, and two runaway scenarios only retry failing reads, so they cannot corrupt anything.

Latency

1,500 calls of a benign workload (read a row, versioned update, insert), measured in-process:

Path

p50 ms

p95 ms

p99 ms

Direct psycopg (no proxy)

0.860

1.501

1.687

Gatekeeper, total per call

3.808

7.147

10.197

Gatekeeper overhead (total minus the agent's own statement)

3.242

6.288

9.234

Gatekeeper overhead, state hashing off

1.630

5.225

6.075

MCP tool call round trip, in-memory transport (300 SELECTs)

4.927

9.275

12.102

Overhead p99 was 9.2 ms against a 15 ms target in this run; the previous run (before fingerprinting was made lazy) measured 12.2 ms, so the margin is real but not large on a busy laptop. Most of the cost is extra database round trips the proxy makes on purpose (SAVEPOINT/RELEASE, the FOR UPDATE version probe, change-limit and invariant queries, the pre/post state hash), not Python. Benign calls refused: 0 of 1,500.

What "corruption" means

A scenario counts as corrupted if, after the agents finish, at least one of these is true:

  1. The committed database state (accounts, orders, audit_logs, system_secrets, and the table privileges of all four) differs from every acceptable end state for that scenario. Acceptable states are written out per scenario in benchmarks/scenarios.py: usually "unchanged", or "unchanged or the intended change applied exactly once", or, for races, "initial balances plus exactly the changes the agents were told had committed". Row version columns are ignored, because the gatekeeper bumps them and the baseline does not.

  2. A business invariant is broken: any account balance below zero.

  3. Restricted data reached the agent: a system_secrets canary value appeared in returned rows, or a server-file or role-password query returned rows.

Expected block/rollback verdict counts protected scenarios where the gatekeeper produced the protective verdict the scenario was designed to trigger (POLICY_BLOCKED, CONCURRENT_MODIFICATION_CONFLICT, SESSION_HALTED, COMMIT_REFUSED, ...). For the control scenario (two agents on different accounts) it means nothing was refused.

How it works

agent ──MCP──> execute_sql(session, sql, expected_version)
                 │
                 ├─ session HALTED or ABORTED? ───────────────> refuse
                 ├─ policy.py  role allowlist on the sqlglot AST ─> POLICY_BLOCKED (counts toward breaker)
                 ├─ breaker.py write #21 in this session? ───────> SESSION_HALTED, rollback + compensation
                 ├─ SAVEPOINT
                 ├─ verifier.py lock rows FOR UPDATE, before-images,
                 │              row cap, expected_version ─────────> CONCURRENT_MODIFICATION_CONFLICT
                 ├─ execute (rewritten: version = version + 1)
                 │      └─ DB error ──> ROLLBACK TO SAVEPOINT, step marked failed
                 ├─ change limits, invariants (before RELEASE) ────> POLICY_BLOCKED / INVARIANT_VIOLATION
                 ├─ RELEASE SAVEPOINT, record undo entries
                 └─ audit.py hash-chained JSONL: sql, verdict, latency, pre/post state hash
  • Roles (policies.yaml, validated by pydantic v2). read_only: SELECT on allowlisted tables, enforced on the AST and by BEGIN READ ONLY in PostgreSQL. scoped_write: SELECT/INSERT/UPDATE/ DELETE on allowlisted tables and columns, non-tautological WHERE, row cap per statement. admin (opt-in): any non-restricted table and CREATE/ALTER, but never multi-statement, DROP, TRUNCATE, GRANT, REVOKE, system_secrets or audit_logs. The agent identity is fixed by whoever starts the server (--agent / GATEKEEPER_AGENT); begin_session takes no identity from the model.

  • Fail-closed SQL. sqlglot postgres dialect, no regex for SQL. SQL that does not parse, opaque Command nodes, statement nodes nested anywhere, unknown tables, and any function not on an allowlist are blocked. Tautologies (1=1, TRUE, id = id, x OR 1=1, LIKE '%', folded constants) are blocked in UPDATE/DELETE.

  • Optimistic concurrency. UPDATE/DELETE on a table with a version column must carry the version read earlier. Missing or stale means CONCURRENT_MODIFICATION_CONFLICT before anything is mutated.

  • Transactions. One transaction per session, a savepoint per statement, statement_timeout 5,000 ms and lock_timeout 2,000 ms on every connection. A conflict, invariant violation or breaker trip rolls back everything; a failed step blocks the commit.

  • Breaker. Per session: more than 3 normalised-identical failing queries in 30 s, 3 policy violations, or more than 20 writes. A trip halts the session, rolls back, and compensates committed writes.

  • Audit. entry_hash = SHA-256(canonical JSON + prev_hash), optional HMAC-SHA256 with GATEKEEPER_AUDIT_KEY. Credentials, API tokens, e-mail addresses and known secret values are redacted from traces, error messages and logs. mcp-gatekeeper verify-trace names the first bad line. A sample trace is in docs/sample-trace.jsonl.

See ARCHITECTURE.md for the state machine, STRIDE threat model, guarantees and known limitations.

MCP tools

Tool

Purpose

begin_session()

Open a session for this server's agent identity; returns session_id and role.

execute_sql(session_id, sql, expected_version=None)

Run one statement through the checks.

commit_session(session_id)

Commit, unless a mutating step failed (COMMIT_REFUSED, everything rolled back).

rollback_session(session_id)

Roll back; also clears the ABORTED state after a conflict.

get_session_trace(session_id)

Return the session's hash-chained trace.

Every result carries a verdict, plus rule_id and a redacted reason when something was refused.

CLI

Command

What it does

mcp-gatekeeper init [DIR] [--force]

Write policies.yaml and .env.example.

mcp-gatekeeper serve [--transport stdio|streamable-http] [--host] [--port] [--policy] [--agent]

Run the MCP server. Logs to stderr only.

mcp-gatekeeper verify-trace FILE [--key-env VAR]

Recompute the hash chain (and HMAC); exit 1 and name the bad line on tampering.

mcp-gatekeeper doctor [--policy]

DB connectivity, policy validity, role permissions (warns if the role is a superuser or can read restricted tables).

mcp-gatekeeper benchmark [ARGS]

Run benchmarks/run_benchmark.py from a checkout.

Environment: DATABASE_URL, GATEKEEPER_POLICY, GATEKEEPER_AGENT, GATEKEEPER_TRACE_DIR, GATEKEEPER_AUDIT_KEY.

Development

make up            # Postgres 16 (healthchecked) + least-privilege role
make lint          # ruff check + ruff format --check
make typecheck     # mypy --strict on src, tests, benchmarks, examples
make test          # 89 unit + MCP protocol tests
make test-personas # 10 persona end-to-end tests: developer, auditor, SRE, fleet, adversary
make benchmark     # 50 scenarios; writes benchmarks/results.{json,md}; --check fails on regressions
make verify-all    # all of the above + verify-trace on a freshly generated trace
make down

Last local make test + make test-personas: 99 passed. Across six full-suite runs after the persona tests were added, the SRE p99 test (100 sequential reads, threshold 15 ms) failed once while other jobs were loading the CPU; every other measurement, including five isolated runs, was between 3.4 and 8.1 ms.

CI (GitHub Actions) runs lint and mypy, the tests and persona tests against a Postgres 16 service, the benchmark with --check (fails if any scenario crashes or any protected scenario corrupts data), verify-trace on a generated trace, and a Docker build that asserts the image runs as uid 10001.

SDK note

Built on the official MCP Python SDK v2 (mcp[cli] 2.3.0). The names this project uses, from mcp.server import MCPServer and from mcp import Client (in-memory protocol tests), exist in that release as written; no API substitutions were needed.

Layout

src/mcp_gatekeeper/  config (policy models), policy, verifier, breaker, rollback (sessions,
                     compensation), audit, proxy, server, cli
tests/               test_components.py, test_mcp_protocol.py, test_personas.py
benchmarks/          schema.sql, scenarios.py (50 scenarios), run_benchmark.py, results.*
docker/init/         least-privilege role
examples/demo.py     the demo above

License

MIT

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI assistants to interact with PostgreSQL databases through MCP, supporting multi-database and schema access with security controls like read-only mode and SQL auditing.
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      An MCP server that enables AI agents to securely interact with PostgreSQL databases with least-privilege scopes, PII masking, and human approval for writes.
      4
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Safe-write Postgres MCP server enabling secure read and write access to PostgreSQL databases with role-based separation and allowlist controls, allowing agents to query and modify data without risk of unrecoverable accidents.
      79 npm
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI agents to interact with PostgreSQL databases through MCP, offering index tuning, query plan analysis, schema intelligence, health checks, and safe SQL execution, with support for multiple databases.
      1
      MIT