Skip to content
Back to search

mcp-gatekeeper

Deterministic, model-free MCP safety proxy for PostgreSQL: AST policy, optimistic concurrency, circuit breakers with compensation, savepoint rollback, hash-chained audit traces.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/vaibhav4046--mcp-gatekeeper/badge.svg)](/listings/vaibhav4046--mcp-gatekeeper)

HTML

<a href="/listings/vaibhav4046--mcp-gatekeeper"><img src="/api/listings/vaibhav4046--mcp-gatekeeper/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

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`.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 235 lines
  1. # mcp-gatekeeper
  2. A deterministic, model-free safety proxy that sits between AI agents and PostgreSQL, exposed as an
  3. [MCP](https://modelcontextprotocol.io) server. Every statement an agent sends passes a role-based
  4. sqlglot AST policy, an optimistic-concurrency check, post-write invariants and a per-session circuit
  5. breaker, inside a savepoint-backed transaction. Every call lands in a hash-chained, optionally
  6. HMAC-signed JSONL trace. There are no LLM calls anywhere in the path.
  7. ![demo](docs/demo.svg)
  8. *`make demo`: an agent talking to the gatekeeper over MCP (terminal capture rendered by `examples/demo.py`).*
  9. ## Quickstart (under a minute with Docker and uv installed)
  10. ```bash
  11. git clone https://github.com/vaibhav4046/mcp-gatekeeper && cd mcp-gatekeeper
  12. make up # PostgreSQL 16 with demo schema and a least-privilege role
  13. uv run mcp-gatekeeper doctor # connectivity, policy validity, role permissions
  14. make demo
  15. ```
  16. Add it to Claude Code (stdio; the server's identity and role come from your policy, not the model):
  17. ```bash
  18. claude mcp add gatekeeper \
  19. -e DATABASE_URL=postgresql://gatekeeper_app:gatekeeper_app@localhost:5432/gatekeeper \
  20. -e GATEKEEPER_AGENT=default \
  21. -- uvx --from git+https://github.com/vaibhav4046/mcp-gatekeeper mcp-gatekeeper serve
  22. ```
  23. or in a project `.mcp.json`:
  24. ```json
  25. {
  26. "mcpServers": {
  27. "gatekeeper": {
  28. "command": "uvx",
  29. "args": ["--from", "git+https://github.com/vaibhav4046/mcp-gatekeeper", "mcp-gatekeeper", "serve"],
  30. "env": {
  31. "DATABASE_URL": "postgresql://gatekeeper_app:gatekeeper_app@localhost:5432/gatekeeper",
  32. "GATEKEEPER_AGENT": "default"
  33. }
  34. }
  35. }
  36. }
  37. ```
  38. The container image serves streamable HTTP: `docker compose --profile app up -d`, then point a
  39. client at `http://localhost:8000/mcp`.
  40. ## Results
  41. 50 adversarial scenarios, 10 per category. Each runs twice with the same agent code: once against a
  42. plain SQL executor (autocommit, no checks, which is how a typical SQL MCP tool behaves) and once
  43. through the gatekeeper with the default policy. From `benchmarks/results.json`, generated by
  44. `make benchmark` at 2026-11-22T01:27:31Z (WSL2 Ubuntu 24.04, Python 3.11.18, PostgreSQL 16.16 in
  45. Docker, on a laptop whose CPU was 40-70% busy with other jobs).
  46. | Category | Corrupted, unprotected | Corrupted, protected | Expected block/rollback verdict |
  47. |---|---|---|---|
  48. | Destructive queries | 8/10 (80%) | 0/10 (0%) | 10/10 (100%) |
  49. | Prompt-injected SQL / boundary probing | 9/10 (90%) | 0/10 (0%) | 10/10 (100%) |
  50. | Concurrent write races | 9/10 (90%) | 0/10 (0%) | 9/10 (90%) |
  51. | Runaway retry / mutation loops | 8/10 (80%) | 0/10 (0%) | 10/10 (100%) |
  52. | Multi-step partial failures | 10/10 (100%) | 0/10 (0%) | 10/10 (100%) |
  53. | **All 50** | **44/50 (88%)** | **0/50 (0%)** | **49/50 (98%)** |
  54. Reading the table honestly:
  55. - The one "expected verdict" miss (X04) is not a safety miss: the two opposite transfers happened
  56. not to overlap in that run, so no conflict was needed and the final state was correct. Race timing
  57. varies; the previous run (one small performance change earlier) scored 50/50 on that column.
  58. Protected corruption was 0/50 in both runs.
  59. - An earlier version of this project scored 2/50 protected. Two policy features closed those cases;
  60. the scenarios were not changed:
  61. - **I10 (semantic injection: credit an account with 1,000,000 using a correct row version)** is
  62. now refused by a declarative `change_limits` rule (`accounts.balance` may change by at most
  63. 10,000 per row per statement). Without that rule in the policy it passes, because the SQL is
  64. structurally fine.
  65. - **R10 (a loop that deletes and commits every iteration)** used to lose the 20 rows committed
  66. before the breaker tripped. The breaker now **compensates**: it replays before-images captured
  67. at write time to reverse the session's committed changes, all or nothing, and only where the row
  68. is still exactly as the session left it.
  69. - In the unprotected column, two destructive scenarios were stopped by PostgreSQL's own foreign keys,
  70. and two runaway scenarios only retry failing reads, so they cannot corrupt anything.
  71. ### Latency
  72. 1,500 calls of a benign workload (read a row, versioned update, insert), measured in-process:
  73. | Path | p50 ms | p95 ms | p99 ms |
  74. |---|---|---|---|
  75. | Direct psycopg (no proxy) | 0.860 | 1.501 | 1.687 |
  76. | Gatekeeper, total per call | 3.808 | 7.147 | 10.197 |
  77. | Gatekeeper overhead (total minus the agent's own statement) | 3.242 | 6.288 | 9.234 |
  78. | Gatekeeper overhead, state hashing off | 1.630 | 5.225 | 6.075 |
  79. | MCP tool call round trip, in-memory transport (300 SELECTs) | 4.927 | 9.275 | 12.102 |
  80. 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
  81. not large on a busy laptop. Most of the cost is extra
  82. database round trips the proxy makes on purpose (SAVEPOINT/RELEASE, the `FOR UPDATE` version
  83. probe, change-limit and invariant queries, the pre/post state hash), not Python. Benign calls
  84. refused: 0 of 1,500.
  85. ### What "corruption" means
  86. A scenario counts as **corrupted** if, after the agents finish, at least one of these is true:
  87. 1. The committed database state (accounts, orders, audit_logs, system_secrets, and the table
  88. privileges of all four) differs from every acceptable end state for that scenario. Acceptable
  89. states are written out per scenario in `benchmarks/scenarios.py`: usually "unchanged", or
  90. "unchanged or the intended change applied exactly once", or, for races, "initial balances plus
  91. exactly the changes the agents were told had committed". Row `version` columns are ignored,
  92. because the gatekeeper bumps them and the baseline does not.
  93. 2. A business invariant is broken: any account balance below zero.
  94. 3. Restricted data reached the agent: a `system_secrets` canary value appeared in returned rows, or
  95. a server-file or role-password query returned rows.
  96. **Expected block/rollback verdict** counts protected scenarios where the gatekeeper produced the
  97. protective verdict the scenario was designed to trigger (`POLICY_BLOCKED`,
  98. `CONCURRENT_MODIFICATION_CONFLICT`, `SESSION_HALTED`, `COMMIT_REFUSED`, ...). For the control
  99. scenario (two agents on different accounts) it means nothing was refused.
  100. ## How it works
  101. ```
  102. agent ──MCP──> execute_sql(session, sql, expected_version)
  103. │
  104. ├─ session HALTED or ABORTED? ───────────────> refuse
  105. ├─ policy.py role allowlist on the sqlglot AST ─> POLICY_BLOCKED (counts toward breaker)
  106. ├─ breaker.py write #21 in this session? ───────> SESSION_HALTED, rollback + compensation
  107. ├─ SAVEPOINT
  108. ├─ verifier.py lock rows FOR UPDATE, before-images,
  109. │ row cap, expected_version ─────────> CONCURRENT_MODIFICATION_CONFLICT
  110. ├─ execute (rewritten: version = version + 1)
  111. │ └─ DB error ──> ROLLBACK TO SAVEPOINT, step marked failed
  112. ├─ change limits, invariants (before RELEASE) ────> POLICY_BLOCKED / INVARIANT_VIOLATION
  113. ├─ RELEASE SAVEPOINT, record undo entries
  114. └─ audit.py hash-chained JSONL: sql, verdict, latency, pre/post state hash
  115. ```
  116. - **Roles** (`policies.yaml`, validated by pydantic v2). `read_only`: SELECT on allowlisted tables,
  117. enforced on the AST and by `BEGIN READ ONLY` in PostgreSQL. `scoped_write`: SELECT/INSERT/UPDATE/
  118. DELETE on allowlisted tables and columns, non-tautological WHERE, row cap per statement. `admin`
  119. (opt-in): any non-restricted table and CREATE/ALTER, but never multi-statement, DROP, TRUNCATE,
  120. GRANT, REVOKE, `system_secrets` or `audit_logs`. The agent identity is fixed by whoever starts the
  121. server (`--agent` / `GATEKEEPER_AGENT`); `begin_session` takes no identity from the model.
  122. - **Fail-closed SQL.** sqlglot postgres dialect, no regex for SQL. SQL that does not parse, opaque
  123. `Command` nodes, statement nodes nested anywhere, unknown tables, and any function not on an
  124. allowlist are blocked. Tautologies (`1=1`, `TRUE`, `id = id`, `x OR 1=1`, `LIKE '%'`, folded
  125. constants) are blocked in UPDATE/DELETE.
  126. - **Optimistic concurrency.** UPDATE/DELETE on a table with a `version` column must carry the
  127. version read earlier. Missing or stale means `CONCURRENT_MODIFICATION_CONFLICT` before anything
  128. is mutated.
  129. - **Transactions.** One transaction per session, a savepoint per statement, `statement_timeout`
  130. 5,000 ms and `lock_timeout` 2,000 ms on every connection. A conflict, invariant violation or
  131. breaker trip rolls back everything; a failed step blocks the commit.
  132. - **Breaker.** Per session: more than 3 normalised-identical failing queries in 30 s, 3 policy
  133. violations, or more than 20 writes. A trip halts the session, rolls back, and compensates
  134. committed writes.
  135. - **Audit.** `entry_hash = SHA-256(canonical JSON + prev_hash)`, optional `HMAC-SHA256` with
  136. `GATEKEEPER_AUDIT_KEY`. Credentials, API tokens, e-mail addresses and known secret values are
  137. redacted from traces, error messages and logs. `mcp-gatekeeper verify-trace` names the first bad
  138. line. A sample trace is in [docs/sample-trace.jsonl](docs/sample-trace.jsonl).
  139. See [ARCHITECTURE.md](ARCHITECTURE.md) for the state machine, STRIDE threat model, guarantees and
  140. known limitations.
  141. ## MCP tools
  142. | Tool | Purpose |
  143. |---|---|
  144. | `begin_session()` | Open a session for this server's agent identity; returns `session_id` and `role`. |
  145. | `execute_sql(session_id, sql, expected_version=None)` | Run one statement through the checks. |
  146. | `commit_session(session_id)` | Commit, unless a mutating step failed (`COMMIT_REFUSED`, everything rolled back). |
  147. | `rollback_session(session_id)` | Roll back; also clears the ABORTED state after a conflict. |
  148. | `get_session_trace(session_id)` | Return the session's hash-chained trace. |
  149. Every result carries a `verdict`, plus `rule_id` and a redacted `reason` when something was refused.
  150. ## CLI
  151. | Command | What it does |
  152. |---|---|
  153. | `mcp-gatekeeper init [DIR] [--force]` | Write `policies.yaml` and `.env.example`. |
  154. | `mcp-gatekeeper serve [--transport stdio\|streamable-http] [--host] [--port] [--policy] [--agent]` | Run the MCP server. Logs to stderr only. |
  155. | `mcp-gatekeeper verify-trace FILE [--key-env VAR]` | Recompute the hash chain (and HMAC); exit 1 and name the bad line on tampering. |
  156. | `mcp-gatekeeper doctor [--policy]` | DB connectivity, policy validity, role permissions (warns if the role is a superuser or can read restricted tables). |
  157. | `mcp-gatekeeper benchmark [ARGS]` | Run `benchmarks/run_benchmark.py` from a checkout. |
  158. Environment: `DATABASE_URL`, `GATEKEEPER_POLICY`, `GATEKEEPER_AGENT`, `GATEKEEPER_TRACE_DIR`,
  159. `GATEKEEPER_AUDIT_KEY`.
  160. ## Development
  161. ```bash
  162. make up # Postgres 16 (healthchecked) + least-privilege role
  163. make lint # ruff check + ruff format --check
  164. make typecheck # mypy --strict on src, tests, benchmarks, examples
  165. make test # 89 unit + MCP protocol tests
  166. make test-personas # 10 persona end-to-end tests: developer, auditor, SRE, fleet, adversary
  167. make benchmark # 50 scenarios; writes benchmarks/results.{json,md}; --check fails on regressions
  168. make verify-all # all of the above + verify-trace on a freshly generated trace
  169. make down
  170. ```
  171. Last local `make test` + `make test-personas`: 99 passed. Across six full-suite runs after the persona
  172. tests were added, the SRE p99 test (100 sequential reads, threshold 15 ms) failed once while other
  173. jobs were loading the CPU; every other measurement, including five isolated runs, was between 3.4
  174. and 8.1 ms.
  175. CI (GitHub Actions) runs lint and mypy, the tests and persona tests against a Postgres 16 service,
  176. the benchmark with `--check` (fails if any scenario crashes or any protected scenario corrupts data),
  177. `verify-trace` on a generated trace, and a Docker build that asserts the image runs as uid 10001.
  178. ### SDK note
  179. Built on the official MCP Python SDK v2 (`mcp[cli]` 2.3.0). The names this project uses,
  180. `from mcp.server import MCPServer` and `from mcp import Client` (in-memory protocol tests), exist
  181. in that release as written; no API substitutions were needed.
  182. ## Layout
  183. ```
  184. src/mcp_gatekeeper/ config (policy models), policy, verifier, breaker, rollback (sessions,
  185. compensation), audit, proxy, server, cli
  186. tests/ test_components.py, test_mcp_protocol.py, test_personas.py
  187. benchmarks/ schema.sql, scenarios.py (50 scenarios), run_benchmark.py, results.*
  188. docker/init/ least-privilege role
  189. examples/demo.py the demo above
  190. ```
  191. ## License
  192. MIT

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.