Postgres MCP Server
Supports local LLM inference through Ollama for the ask tool, generating SQL from natural-language questions against the live PostgreSQL schema.
Uses OpenAI-compatible APIs for the ask tool to translate plain-English questions into SQL against the live database schema, with one repair attempt for rejected SQL.
Allows AI assistants to explore PostgreSQL schemas and run safe, read-only SELECT queries with schema discovery, query plans, row limits, and timeouts.
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., "@Postgres MCP Server Show me the top 10 customers by total spend last quarter."
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.
Postgres MCP Server
An MCP server that lets AI assistants like Claude Desktop, Cursor or Claude Code explore and query a PostgreSQL database in plain English, safely.
Ask "Which customers spent the most last quarter?" and the assistant inspects the live schema, writes the SQL, runs it read-only and answers from the results.
Why it's safe to point at a real database
Letting an AI run SQL is only useful if it can't break anything. Every query passes through three layers:
Layer | What it does |
SQL guard ( | Parses the query with |
Row cap | Adds or tightens a |
Database session | Every query runs in a |
For production, connect with a database user that only has SELECT grants as well.
Related MCP server: PostgreSQL MCP Server
Tools
Tool | Description |
| Configured databases (you can connect several at once) |
| Tables and views with approximate row counts |
| Columns, types, primary key and foreign keys |
| Run a read-only |
| Show the query plan without running the query |
| Plain-English question → SQL written from the live schema → results. Rejected SQL is sent back to the model once to fix. |
How ask works
question ──► schema overview (tables, columns, PKs, FKs) ──► LLM writes SQL
│
rejected? ◄── SQL guard ◄─────────────┘
└─► one repair attempt with the error message
│
read-only execution ──► rows (JSON)ask works with any OpenAI-compatible API: OpenAI, Groq, OpenRouter, or a local model through Ollama.
Quick start
git clone https://github.com/Zotriq/postgres-mcp-server.git
cd postgres-mcp-server
pip install -e .
cp .env.example .env # set DATABASE_URL (and LLM_API_KEY for the ask tool)Want sample data? Load the demo shop database:
psql "$DATABASE_URL" -f examples/shop_schema.sqlUse it in Claude Desktop
Add this to claude_desktop_config.json (see examples/claude_desktop_config.json):
{
"mcpServers": {
"postgres": {
"command": "pg-mcp",
"env": { "DATABASE_URL": "postgresql://readonly_user:password@localhost:5432/shop" }
}
}
}Several databases
PG_MCP_DATABASES={"shop": "postgresql://...", "analytics": "postgresql://..."}Every tool takes an optional database argument; the first one is the default.
Configuration
Variable | Default | Purpose |
| – | Single database connection |
| – | JSON map of name → URL (overrides |
|
| Maximum rows returned per query |
|
| Per-query timeout |
| – | Key for the |
| OpenAI | Any OpenAI-compatible endpoint |
|
| Model used to write SQL |
Tests
34 tests cover the SQL guard (17 attack patterns), the read-only session, timeouts, schema discovery and the full MCP tool flow against a real PostgreSQL database. The LLM is mocked.
pip install -e ".[dev]"
PG_TEST_URL=postgresql://postgres@localhost:5432/postgres pytestGitHub Actions runs the suite against PostgreSQL 16 on every push.
Project structure
pg_mcp/
server.py MCP server and tool definitions
database.py read-only sessions, schema discovery, query execution
sql_guard.py SQL parsing and safety rules
nl2sql.py plain-English → SQL with validation and one repair attempt
config.py settings from environment variables
examples/ demo schema and Claude Desktop config
tests/ pytest suiteLicense
MIT © Zohaib Tariq
Available Tools
6 toolsaskB
Answer a plain-English question: writes safe SQL from the live schema and (optionally) runs it.
Inputs: question (required), run, database. Returns: object
describe_tableB
Show columns, types, primary key and foreign keys for a table (e.g. 'public.orders').
Inputs: table (required), database. Returns: object
explain_queryB
Show the PostgreSQL query plan for a SELECT without running it.
Inputs: sql (required), database. Returns: result
list_databasesA
List the configured database names.
Inputs: no named parameters. Returns: result
list_tablesB
List tables and views with approximate row counts.
Inputs: schema, database. Returns: result
run_queryA
Run a single read-only SELECT. Writes, DDL and unsafe functions are rejected; rows are capped.
Inputs: sql (required), database. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 6 tools
Most tools target clearly distinct actions: listing databases/tables, describing a table, running a SELECT, and explaining a query plan. The only real overlap is between 'ask' and 'run_query', since 'ask' can also generate and execute SQL, but the natural-language vs raw-SQL distinction and the optional execution flag make them separable.
Five of six tools follow a clean verb_noun or verb_object pattern (list_databases, list_tables, describe_table, run_query, explain_query). 'ask' is a stylistic outlier but is still a single readable verb, so the set remains predictable.
Six tools is well-scoped for a read-only Postgres inspection server — each one covers a distinct step in the explore-inspect-query workflow. Nothing feels padded or missing at the count level.
The surface covers the core read-only lifecycle: discover databases, browse tables, inspect schema, execute, and plan queries, with 'ask' as a convenience layer. Minor gaps exist — no schema-level listing beyond table names, no index/constraint detail beyond PK/FK, and writes/DDL are intentionally excluded, which an agent can work around for read-only tasks.
Maintenance
Related MCP Connectors
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
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 40 databases from Claude, ChatGPT, or Cursor — on any device. Read-only, encrypted, audited.
Related MCP Servers
- AlicenseAqualityNot gradedmaintenanceEnables AI assistants to interact with PostgreSQL databases using natural language queries, providing secure read-only access to database schemas and SQL translation capabilities.6ISC
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to safely interact with PostgreSQL databases through read-only operations, providing schema discovery, table inspection, and query execution capabilities with structured context awareness.MIT
- AlicenseNot gradedqualityCmaintenanceEnables an AI assistant to run guarded, read-only SQL queries against a Postgres database with enforced limits and validation.MIT
- AlicenseAqualityBmaintenanceEnables AI clients to safely query PostgreSQL databases using plain English, with read-only access and built-in SQL safety checks.4MIT