pgleash
Acts as a guarded proxy in front of a Postgres database: every statement from the agent is parsed with Postgres's own parser and checked against a policy (read-only by default, or guarded writes with a real WHERE clause), with denials for tables, columns and dangerous functions, row caps, statement/idle-in-transaction timeouts, and a JSON-lines audit log. MCP mode exposes query, list_tables and describe_table tools that run through the same proxy and rules, and the agent only ever sees a pgleash token while pgleash holds the real credentials.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
pgleash
A Postgres proxy that keeps AI agents on a leash.
Point your coding agent at pgleash instead of at your database. pgleash parses every statement with Postgres's own parser and stops the dangerous ones before they reach the server. Reads go through. DROP, TRUNCATE, a DELETE with no WHERE, writes hidden inside a CTE or an EXPLAIN ANALYZE, and the stacked COMMIT; trick do not.
$ npx pgleash check "SELECT 1; COMMIT; DROP TABLE users"
blocked [multi-statement]: send one statement at a time (this query has 3)Why
Giving an agent database access usually means one of two things: the real connection string, or an MCP server with a "read-only" switch inside it. Both have failed in public.
In July 2025 an AI agent on Replit deleted a production database during a code freeze.
Anthropic's reference Postgres MCP server wrapped each query in
BEGIN TRANSACTION READ ONLY. Datadog Security Labs showed that a query could end that transaction itself and then run any SQL. The server has been archived, and the npm package still had about 21,000 weekly downloads when they wrote it up.AWS's Postgres MCP server needed a fix for an incomplete list of blocked SQL (CVE-2025-59333).
pgleash enforces the rules on the wire, outside the agent. The agent connects with a pgleash token and never sees the real credentials.
Related MCP server: MCP Postgres Guard
Quick start
export PGLEASH_UPSTREAM='postgres://readonly_user:secret@db.internal:5432/app?sslmode=require'
npx pgleashpgleash 0.1.0 (read-only, max 1000 rows, 10s statement timeout)
upstream: db.internal:5432/app as readonly_user (sslmode=require)
listening: 127.0.0.1:6433
Give your agent this connection string (not the upstream one):
postgres://agent:Yq3v...@127.0.0.1:6433/apppgleash speaks the Postgres wire protocol, so psql, node-postgres, psycopg and ORMs connect to it like any other database. (The test suite uses node-postgres.) When a query is blocked, the agent gets a normal Postgres error with the reason and a hint:
app=> DELETE FROM orders;
ERROR: pgleash blocked this query: DELETE is not allowed in read-only mode
HINT: pgleash only lets this connection run the statements its mode allows. Ask a person to run this one.As an MCP server
For Claude Code:
claude mcp add pgleash -e PGLEASH_UPSTREAM='postgres://...' -- npx -y pgleash mcpFor Cursor and other MCP clients:
{
"mcpServers": {
"pgleash": {
"command": "npx",
"args": ["-y", "pgleash", "mcp", "--deny-column", "email"],
"env": { "PGLEASH_UPSTREAM": "postgres://..." }
}
}
}MCP mode gives the agent three tools: query, list_tables and describe_table. Every call goes through the same proxy and the same rules.
What it does
Read-only by default. Only reads, EXPLAIN, SHOW, cursors and transaction control get through. The session is also pinned with default_transaction_read_only = on, and the agent can't undo that: SET, RESET ALL, DISCARD ALL, BEGIN READ WRITE and set_config() are blocked. So a write the parser can't see, such as one inside a user-defined function, still fails in the database.
Guarded writes when you want them. --mode guarded-write allows INSERT, plus UPDATE and DELETE with a WHERE clause that names a column. WHERE true and WHERE 1 = 1 don't count. DDL, TRUNCATE, COPY, DO, CALL, GRANT and MERGE stay blocked.
Off-limits tables and columns. --deny-table api_tokens blocks every reference to the table. --deny-column email blocks queries that name the column, pass a whole row to a function (row_to_json(u)), or SELECT * from a table that has it. pgleash looks those tables up in the live schema and refreshes the list every minute. As a second layer, any result column with a denied name comes back as NULL.
Dangerous functions blocked. These include pg_terminate_backend, pg_read_file, lo_import, dblink, pg_sleep, advisory locks, query_to_xml (which runs SQL passed in as a string), replication slot functions and setval. Add your own with --deny-function, and end a name with * to block a whole prefix.
Limits. Each result stops at 1,000 rows by default, and the agent gets a notice saying how many rows the query really returned. There is a 10 second statement timeout and a 60 second idle-in-transaction timeout.
Audit log. --audit pgleash.jsonl writes one line per query, allowed or blocked, with the rule that blocked it.
{"ts":"2026-11-29T10:02:11.412Z","session":3,"user":"agent","app":"psql","kind":"query","sql":"DROP TABLE users","allowed":false,"rule":"statement-type","reason":"DROP is not allowed in read-only mode"}Configuration
Flags, environment variables or a pgleash.json in the working directory:
{
"upstream": "postgres://readonly_user:secret@db.internal:5432/app?sslmode=verify-full&sslrootcert=/etc/ssl/rds-global-bundle.pem",
"mode": "read-only",
"maxRows": 500,
"statementTimeout": "5s",
"denyTables": ["api_tokens", "billing.cards"],
"denyColumns": ["email", "phone", "password_hash"],
"denyFunctions": ["app_purge_*"],
"audit": "pgleash.jsonl"
}Flag | Default | |
|
| The real database. |
|
| Where pgleash listens. |
|
| The password the agent uses. |
|
| Or |
|
|
|
|
| |
| Repeat for more than one. | |
| Lets the agent | |
| off | Each statement is still checked. |
| JSON lines. |
pgleash check runs the same policy without a database, so you can try rules or use it in CI and agent hooks. It exits 1 when a query is blocked, and --json prints the decision.
How it works
agent ──(token)──▶ pgleash ──(real credentials, TLS)──▶ Postgres
│
├─ parse with libpg-query (Postgres's own parser)
├─ check statement types, functions, tables, columns
└─ cap rows, null denied columns, write the audit logpgleash speaks the Postgres wire protocol on both sides and checks the simple and the extended (prepared statement) protocol. A blocked statement isn't simply dropped. pgleash swaps it for a query that fails on the server, then replaces that error with its own. So the error comes back in the order the client expects, and an open transaction is aborted just as Postgres would abort it. Anything the parser can't parse is blocked.
Limits
pgleash is a guardrail, not a sandbox. Use it together with these:
A least-privilege role for the upstream. For read-only work, something like:
CREATE ROLE agent_ro LOGIN PASSWORD '...'; GRANT CONNECT ON DATABASE app TO agent_ro; GRANT USAGE ON SCHEMA public TO agent_ro; GRANT SELECT ON orders, products TO agent_ro; GRANT SELECT (id, name, created_at) ON users TO agent_ro; -- leaves out email and phoneGrant column lists rather than revoking columns: a column
REVOKEhas no effect while the role holdsSELECTon the whole table.Keep the real connection string away from the agent. If it's in a
.envfile the agent can read, the agent can skip pgleash. On AWS, let only the pgleash host reach the database through its security group.
pgleash also has gaps you should know about:
Tables and columns are matched by name. A view over a denied table, or a view that renames a denied column, isn't caught. Deny the view too, or use column privileges.
In guarded-write mode, a user-defined function can write whatever its owner can. Block such functions with
--deny-function.The agent's side of the connection is plain TCP, meant for loopback. pgleash won't listen on another address without a token.
Not supported yet:
COPY, fast-path function calls, replication connections, and TLS between the agent and pgleash.
Development
npm install
npm test # starts an embedded Postgres; or set PGLEASH_TEST_URL to a superuser URL
npm run buildThe tests run a real Postgres with TLS, connect through pgleash with node-postgres, and check each guardrail end to end. They also cover the CLI and MCP mode.
License
MIT
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Deterministic safety, correctness & cost gate that vets Postgres SQL before your AI agent runs it.
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Query your Postgres from ChatGPT or Claude without exposing the database or handing over credentials. Run npx boltschema connect next to your database and it dials out over HTTPS — no inbound firewall rule, no open port, works with localhost and VPC-private databases. Read-only is enforced by a SQL guard, a Postgres READ ONLY transaction, and a scoped role generated for you.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to query Postgres databases read-only over the Model Context Protocol through three narrow tools, validating every statement as a single SELECT with an enforced row limit before it reaches the database. Guards against destructive statements, banned functions, system catalogs, and runaway queries via AST parsing plus a SELECT-only Postgres role.MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to safely query PostgreSQL by intercepting and auditing every generated SQL statement before it reaches the database, blocking destructive commands like DROP/TRUNCATE, unbounded DELETE/UPDATE statements, stacked queries, and SQL injection probes. It exposes tools for validating query safety and enforcing a strict read-only (SELECT/EXPLAIN) policy.MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to query a Postgres database read-only through a policy layer rather than a raw connection string. Enforces table and column allowlists, row limits, mandatory predicates, PII masking and append-only audit logging, while refusing writes, joins, subqueries and unlisted functions.MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to query Postgres, BigQuery and DuckDB read-only through policy-checked SQL, with AST-based guards that refuse writes and dangerous functions, column masking on the way out, and an audit log of every query. Also exposes schema browsing and query-planning tools so agents can see allowed tables, columns and costs before running anything.MIT