Kenning PG MCP
Provides tools for interacting with a PostgreSQL database, including listing schemas and objects, describing table structures, executing read-only queries, explaining query plans, listing extensions, and (in unrestricted mode) executing DML statements.
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., "@Kenning PG MCP show me the schema of the orders 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.
Kenning PG MCP
A PostgreSQL Model Context Protocol server built on two convictions:
Dependencies are pinned exactly. Every dependency is resolved once, recorded in a committed lockfile, and upgraded only as a deliberate, reviewed act. The published package carries
==pins; the Docker image is built withuv sync --frozen. Nothing resolves at launch time.Read-only means the database says no — not a regex. Access control is transaction- and role-based. The server never inspects SQL text to decide whether a statement is "safe," because that model is unwinnable: a data-modifying CTE, a
VOLATILEfunction that writes, orCOPY ... TO PROGRAMall pass keyword filters. PostgreSQL itself is the enforcement.
Built on the MCP Python SDK v2 (2026-07-28 stateless protocol revision),
psycopg 3, and pydantic-settings. Serves stdio and streamable HTTP from
one set of handlers.
The security model
Four layers, none of which parse SQL:
Read-only transactions. Every read path runs inside
BEGIN ... READ ONLY. PostgreSQL rejects any write attempt with SQLSTATE25006— including data-modifying CTEs,SELECT ... FOR UPDATE, and volatile functions that write.One statement per call, enforced by the server. Every user statement is executed through the extended query protocol, where PostgreSQL rejects multi-command strings outright. Statement stacking dies in the database, not in a parser.
A purpose-built role, checked at startup. Connect as a minimal role (SQL below). This is what blocks
COPY ... TO PROGRAM,pg_read_file(),lo_export(), andpg_terminate_backend()— capabilities that begin withSELECTorCOPYand would sail through any keyword guard. A read-only transaction does not stop them: none writes to a relation, so25006never fires (verified against PostgreSQL 18, whereCOPY (SELECT ...) TO PROGRAMexecutes arbitrary commands insideBEGIN TRANSACTION READ ONLYas a superuser). Because documentation is not enforcement, the server verifies the role itself rather than trusting the deployment to have followed it. Privilege, not pattern matching.Timeouts on every session.
statement_timeoutandidle_in_transaction_session_timeoutare set at connection time, so a badly planned query cannot pin a connection indefinitely.
On startup (in restricted mode) the server runs two probes before serving a
single query, and exits non-zero rather than silently serving a read-only
server that isn't:
A write inside a read-only transaction must fail with
25006.The connection role must not be a superuser and must hold none of
pg_read_server_files,pg_write_server_files, orpg_execute_server_program. Override withPG_MCP_ALLOW_SUPERUSER=trueon a trusted, disposable database; the override logs a prominent warning.
In unrestricted mode the privilege probe warns rather than refuses:
enabling writes is consent to modify data, not consent to read server files
or execute programs as the database OS user.
An adversarial test suite attempts every bypass listed above against a real PostgreSQL as a low-privilege role; every case must fail at the database.
Write access is never inferred. In the default restricted mode the write
tool is not merely refused — it is not registered, so it never appears in
tools/list. Setting PG_MCP_ACCESS_MODE=unrestricted registers a single
DML tool; read tools still run read-only transactions.
The role
The requirement is negative: do not connect as a superuser. An ordinary
application or reporting role already satisfies it — not a superuser, no
filesystem roles — and needs no configuration. restricted mode still blocks
every write such a role could otherwise make, because the transaction layer
does not care what the role is permitted to do. Point the server at the
least-privileged existing role that can see your data.
Creating a dedicated role, below, narrows what is visible. It is a refinement for organizations that provision service accounts per consumer, not a prerequisite for read-only safety:
CREATE ROLE mcp_ro LOGIN PASSWORD '...';
GRANT CONNECT ON DATABASE mydb TO mcp_ro;
GRANT USAGE ON SCHEMA public TO mcp_ro;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_ro;
ALTER ROLE mcp_ro SET default_transaction_read_only = on;
ALTER ROLE mcp_ro SET statement_timeout = '30s';
ALTER ROLE mcp_ro SET idle_in_transaction_session_timeout = '60s';For read-write deployments, the equivalent role carries INSERT, UPDATE,
DELETE and nothing more. DDL is an operator decision, not a server feature.
Related MCP server: PostgreSQL Multi-Schema MCP Server
Install
The server is a deployable tool, not a library — install it isolated, where exact pins are a feature:
uv tool install kenning-pg-mcp # or: pipx install kenning-pg-mcpOr use the Docker image (the primary distribution artifact — resolution happens at build time, never at launch):
docker build -t kenning-pg-mcp:0.2.0 .Do not run this server via uvx. uvx re-resolves against PyPI on every
invocation, which is the exact failure mode this project exists to eliminate.
Install once, pin the version, upgrade deliberately.
Configuration
Setting | Env var | Default |
Connection URI (required) |
| — |
Access mode |
|
|
Allow a privileged role |
|
|
Transport |
|
|
HTTP bind host / port |
|
|
Max rows / response bytes |
|
|
Statement timeout |
|
|
Pool min / max |
|
|
Schema allowlist (comma-sep) |
| all non-system |
Log level |
|
|
Flags --access-mode, --transport, --host, --port override the
environment. The effective configuration is logged at startup with the
connection password redacted.
Tools
Tool | Purpose |
| Schemas, honoring the allowlist. |
| Tables, views, matviews, sequences in a schema. |
| Columns, PK, FKs both directions, indexes, constraints, comments, approximate row count. |
| One read statement in a read-only transaction; capped results with an explicit truncation notice (no |
|
|
| Installed and available extensions. |
| Version, role, database, access mode, key settings. |
| Single DML statement — registered only in |
Results serialize honestly: numeric → string (never float), timestamps →
ISO 8601 with timezone, bytea → base64 with a length note, json/jsonb →
nested structures, NULL → null.
max_bytes bounds the result as the model receives it — the
pretty-printed text block, columns, truncation object and notice included —
not the row payload and not compact JSON, both of which understate the real
cost. The default is sized against the model's context rather than the
transport: 50 KB is roughly 12k tokens, where the 1 MiB response limit hosts
commonly enforce would be ~250k — a result that transits successfully and then
consumes the conversation it was meant to inform. Truncation is
self-correcting, since the notice tells the model to add LIMIT, filter, or
aggregate.
Claude Desktop
{
"mcpServers": {
"postgres": {
"command": "docker",
"args": ["run", "-i", "--rm", "-e", "DATABASE_URI", "kenning-pg-mcp:0.2.0"],
"env": {
"DATABASE_URI": "postgresql://mcp_ro:PASSWORD@host.docker.internal:5432/mydb"
}
}
}
}Or with a tool install:
{
"mcpServers": {
"postgres": {
"command": "/absolute/path/to/kenning-pg-mcp",
"env": {
"DATABASE_URI": "postgresql://mcp_ro:PASSWORD@localhost:5432/mydb"
}
}
}
}HTTP mode
PG_MCP_TRANSPORT=http kenning-pg-mcpClients connect to http://127.0.0.1:8000/mcp. Binding beyond loopback
requires PG_MCP_ALLOW_REMOTE=true, and there is no built-in
authentication — put the server behind a reverse proxy that authenticates,
and set PG_MCP_ALLOWED_HOSTS / PG_MCP_ALLOWED_ORIGINS to match your
deployment.
Development
uv sync --frozen
make check # lint + type-check + full test suiteThe test suite has three layers: unit (no database), integration against a real PostgreSQL via testcontainers, and an adversarial layer that attempts every write-bypass in the threat model as a low-privilege role — each case must fail at the database. Docker is required for the latter two.
License
Licensed under the MIT License. Use it for anything.
Available Tools
7 toolsdescribe_objectA
Describe one relation: columns (name, type, nullable, default, comment), primary key, foreign keys in both directions, indexes, check and unique constraints, and an approximate row count from pg_class.reltuples. Cheap. Prefer this over querying catalogs by hand; use it before writing queries against unfamiliar tables.
Inputs: name (required), schema (required). Returns: object
execute_queryA
Run a single read-only SQL statement inside a READ ONLY transaction and return {columns, rows, row_count, truncated, notice?}. Exactly one statement per call. Use %s placeholders with the params list for user-supplied values. Results are capped at the configured row and byte limits with an explicit truncation notice when more data exists — no LIMIT is ever injected into your SQL. Cost depends entirely on the query; run explain_query first for anything potentially expensive.
Inputs: sql (required), params. Returns: object
explain_queryA
Return the PostgreSQL execution plan (EXPLAIN, FORMAT JSON) for a single statement. Cheap without analyze. With analyze=true the statement is actually executed to collect real timing — the transaction is always rolled back, so even in read-write mode nothing persists, but the statement's runtime cost is fully paid. Parameters are not supported here; inline literal values instead.
Inputs: sql (required), analyze. Returns: object
list_extensionsA
List installed and available PostgreSQL extensions with versions and descriptions. Cheap. Check here whether an extension (pg_stat_statements, postgis, hypopg, ...) exists before writing queries that depend on it.
Inputs: no named parameters. Returns: result
list_objectsA
List tables, views, materialized views, sequences, and foreign tables in a schema, with comments and approximate row counts. Cheap. Filter by object_type and/or a SQL LIKE name_pattern (e.g. 'order%'). Prefer describe_object for the full shape of a single relation.
Inputs: schema (required), object_type, name_pattern. Returns: result
list_schemasA
List database schemas visible to this server, honoring the configured schema allowlist. Cheap. Call this first to see what exists; then use list_objects to look inside a schema.
Inputs: no named parameters. Returns: result
server_infoA
Report server version, current role and database, effective access mode, and key settings (timeouts, search_path, recovery state). Cheap. Useful for orientation and for diagnosing permission or timeout surprises.
Inputs: no named parameters. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 7 tools
Each tool has a clearly distinct purpose: describe_object inspects a single relation's shape, execute_query runs SQL, explain_query plans SQL, list_extensions and list_schemas enumerate namespaces, list_objects lists relations in a schema, and server_info reports environment. No two tools overlap in function.
Most tools follow a consistent verb_object pattern (describe_object, execute_query, explain_query, list_extensions, list_schemas, list_objects, server_info). The only slight deviation is the phrase-based server_info which could be get_server_info, but it's still clearly readable and consistent with the snake_case convention.
Seven tools is a well-scoped count for a PostgreSQL inspection server. Each tool earns its place covering discovery, planning, execution, and environment introspection without bloat.
The surface covers the full inspection lifecycle: orientation (server_info, list_schemas, list_extensions), table discovery (list_objects), full schema detail (describe_object), planning (explain_query), and execution (execute_query). The guidance embedded in descriptions (e.g., run explain first, check extensions before depending on them) chains the tools into a complete workflow with no dead ends.
Maintenance
Related MCP Connectors
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Managed Postgres MCP: projects, SQL, docs search, and storage buckets via OAuth.
Hosted MCP server for PostgreSQL diagnostics: slow queries, missing indexes, connection pressure.
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
- -licenseNot gradedqualityBmaintenanceA Model Context Protocol server that provides read-only access to PostgreSQL databases. This server enables LLMs to inspect database schemas and execute read-only queries.139,311 npm92,139MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that provides read-only access to PostgreSQL databases with enhanced multi-schema support, allowing LLMs to inspect database schemas across multiple namespaces and execute read-only queries while maintaining schema isolation.145 npm3MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that provides read-only access to PostgreSQL databases, enabling LLMs to inspect database schemas and execute read-only queries.MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that provides AI assistants with secure, read-only access to PostgreSQL databases while offering comprehensive tools for schema exploration, query validation, and performance optimization.MIT