pg-guard-mcp
Summary: A read-only PostgreSQL MCP server for safe querying, schema inspection, and migration-safety linting.
Run a single read-only SQL statement (SELECT/WITH/EXPLAIN/SHOW) and get rows back.
Get PostgreSQL query plans for SELECT/WITH statements without executing them.
List tables and views in a schema.
Describe a table's columns: name, data type, nullability, and default.
Check whether the connected role holds any write privileges (expected result: empty).
Statically check migration SQL (from a string or file) for dangerous DDL patterns such as non-concurrent index creation, unsafe ADD COLUMN NOT NULL, and table-rewriting alterations.
Provides read-only PostgreSQL database access, with tools for running read-only queries, explaining query plans, listing tables, describing table columns, and checking write privileges.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@pg-guard-mcp show me the columns of the users table"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
pg-guard-mcp
A PostgreSQL MCP server that enforces read-only access at the protocol and privilege level — not by parsing the query string and hoping.
Install
pip install pg-guard-mcp
# or, without installing anything permanently:
uvx pg-guard-mcpRelated MCP server: PostgreSQL MCP Server
Why this exists
The official @modelcontextprotocol/server-postgres shipped a read-only mode that a single COMMIT; could bypass: it wrapped the agent's query in BEGIN TRANSACTION READ ONLY and sent the whole thing as one string. Postgres accepts semicolon-separated multiple statements in that mode, so SELECT 1; COMMIT; DROP SCHEMA public CASCADE; closed the read-only transaction early and ran the drop as an ordinary write. The package was deprecated over it. (Datadog Security Labs writeup)
pg-guard-mcp exists because that bug class — "read-only" enforced only by string inspection — is still common across the MCP ecosystem. It defends in three independent layers, so no single mistake is fatal:
Protocol layer (the real boundary). Every query runs through Postgres's extended query protocol (
Parse/Bind/Execute), never the simple query protocol. The extended protocol structurally rejects more than one statement perParsemessage — Postgres itself refuses it, before any of our code runs. This is why the Datadog exploit cannot work here regardless of what string is submitted.Session layer. Every connection sets
default_transaction_read_only = onat the session level, so even a query that somehow reached the database as a write is rejected by Postgres.Pre-flight layer. Before a query is even sent, it's checked for multiple statements and transaction-control keywords (
COMMIT,ROLLBACK,BEGIN,SAVEPOINT, ...) and rejected with a clear error. This exists to fail fast and loud, not as the primary defense.
On top of that, connecting with a database role that has had write privileges REVOKEd is the recommended (and startup-checked) setup — belt and suspenders at the privilege layer too.
Tools
Tool | Does |
| Run one read-only statement, return rows |
| Return the query plan without running it |
| List tables/views in a schema |
| List a table's columns |
| Report any write grant the connected role actually holds — should always come back empty |
| Static-check DDL for lock/downtime/breakage patterns before anyone runs it — never touches the database |
| Same check, reading the SQL from a file on disk |
Migration safety linting
An agent asked to "add this migration and run it" is exactly the moment a
CREATE INDEX without CONCURRENTLY locks writes on a busy table for the
next ten minutes, or an ADD COLUMN ... NOT NULL with no default fails
outright the instant it hits a populated table. pg_check_migration_safety
and pg_check_migration_file catch these before they run — pure text
analysis, no database connection involved, so they work with no PG_GUARD_DSN
configured at all.
This is the same rule class as Squawk and strong_migrations, which exist as standalone linters but not, as far as a deliberate search turned up, as an MCP tool an agent can call mid-conversation:
Rule | Catches |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
This is regex-based pattern matching over one statement at a time, not a
real SQL parser — see migration_safety.py's module docstring for the
exact scope limitation (a single hand-written statement combining several
actions in one comma-separated ALTER TABLE is checked as a whole, not
action-by-action; every common migration tool generates one action per
statement by default, so this covers the overwhelming majority of
real-world migrations). An empty findings list means no known-unsafe
pattern was found, not a guarantee.
Setup
pip install pg-guard-mcp
export PG_GUARD_DSN="host=127.0.0.1 dbname=mydb user=myapp_readonly password=..."
pg-guard-mcpPoint your MCP client at the pg-guard-mcp command (or uvx pg-guard-mcp to skip a permanent install) with PG_GUARD_DSN set in its env config.
See .env.example for all supported environment variables, and scripts/setup_dev_db.sh for a working example of setting up a properly-restricted read-only role (the setup this project's own tests run against).
Testing
pip install -e ".[dev]"
pytest tests/ -vtests/test_safety.py is pure-Python and needs no database. tests/test_db.py and tests/test_server.py run against a real local PostgreSQL instance — including the exact exploit payload that deprecated the official Postgres MCP server — and skip automatically if pgguard_test isn't reachable. Run scripts/setup_dev_db.sh once to create it.
Status
v0.2.0. 99 passing tests (unit + live-Postgres integration, including the exact exploit that deprecated the official server-postgres, run against a fresh pip install of the published package) plus 16 DB-dependent tests that skip automatically without a local pgguard_test database.
License
MIT
Available Tools
5 toolspg_check_privilegesA
Report any write privilege (INSERT/UPDATE/DELETE/TRUNCATE) the connected role actually holds on any table. An empty list is the expected, safe result — anything else means the privilege layer of defense is missing and the role should be locked down (see README.md), even though the protocol and session layers still hold on their own.
Inputs: no named parameters.
pg_describe_tableA
List the columns of a table: name, data type, nullability, and default, in column order.
Inputs: table_name (required), schema.
pg_explain_queryA
Return the PostgreSQL query plan for a read-only SELECT/WITH statement, without running it. Useful for checking whether a query will be slow before running it for real.
Inputs: sql (required).
pg_list_tablesA
List the tables and views visible to the connected role in the given schema (default: public).
Inputs: schema.
pg_run_queryA
Run a single read-only SQL statement (SELECT / WITH / EXPLAIN / SHOW) against the configured PostgreSQL database and return the rows.
Rejects anything that isn't exactly one plain read-only statement — multiple statements, transaction-control keywords (COMMIT, ROLLBACK, BEGIN, ...), and any write/DDL/admin keyword anywhere in the query are all refused before the query is sent to the database. Results are capped at PG_GUARD_ROW_LIMIT rows (default 1000).
Inputs: sql (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 5 tools
Each tool has a clearly distinct role: executing read-only queries, explaining query plans, listing tables, describing table schemas, and checking write privileges. There is no functional overlap or ambiguity between them.
All tool names follow the same pg_ prefix with a consistent verb_noun pattern: run_query, explain_query, list_tables, check_privileges, describe_table. The naming is uniform and predictable.
Five tools is well-scoped for a PostgreSQL guard/observer server. Each tool serves a clear, non-redundant purpose and the set feels complete without being bloated.
The tool surface covers the core read-only workflow: exploring available tables, inspecting schemas, validating query plans, running queries, and verifying the security posture. No obvious dead ends or missing security-relevant operations are apparent.
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 40 databases from Claude, ChatGPT, or Cursor — on any device. Read-only, encrypted, audited.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables secure read-only access to PostgreSQL databases through SELECT queries only, with tools for exploring schemas, listing tables, and executing common queries while preventing any data modification operations.1,430 npmMIT
- AlicenseNot gradedqualityDmaintenanceProvides secure, read-only access to PostgreSQL databases for schema inspection and data querying. It enables users to list tables, describe structures, and execute SELECT statements while strictly blocking destructive operations.7 npm1MIT
- AlicenseNot gradedqualityDmaintenanceEnables safe interaction with PostgreSQL databases through read-only queries, schema exploration, and performance analysis.129 npmMIT
- AlicenseNot gradedqualityDmaintenanceRead-only access to PostgreSQL databases, enabling schema inspection and safe SQL queries.20 npmMIT