PostgreSQL MCP Server
Provides tools for securely interacting with PostgreSQL databases, including schema inspection, SELECT/INSERT/UPDATE/DELETE query execution, transaction management, admin monitoring, and AI-powered SQL generation, validation, explanation, and optimization.
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.
PostgreSQL MCP Server
A production-ready Model Context Protocol (MCP) server for PostgreSQL. It gives AI assistants a structured, guarded interface for inspecting schemas, running queries, analysing plans, and operating a PostgreSQL database.
Version 2.0 adds role-based access control, execution-plan analysis, health and index diagnostics, query metrics, streaming, result caching, prepared statement tracking, LISTEN/NOTIFY, pgvector helpers, migrations, and multi-database support — all behind the same MCP interface.
Highlights
70 MCP tools across schema inspection, query execution, transactions, administration, AI assistance, pgvector, migrations, notifications, metrics, and diagnostics
MCP resources and prompts for schema context, live status, configuration, metrics, and common workflows
Role-based access control (RBAC) with five roles and a permission map that covers every registered tool
Defence in depth — SQL injection detection, dangerous-statement blocking, read-only enforcement, identifier validation, parameterised catalog queries, and audit logging
Diagnostics — EXPLAIN plan summaries with recommendations, database health scoring, role/membership inspection, and index recommendations
Operations — async connection pool with retry, health checks, query metrics, slow-query tracking, rate limiting, TTL caches, streaming, and graceful shutdown
Deployment ready — Docker, Docker Compose, stdio/HTTP/SSE transports,
pyproject.tomlpackaging, and apostgres-mcpconsole entry point
Related MCP server: PostgreSQL MCP Server
Prerequisites
Python 3.12+
PostgreSQL 14+
pip (or uv)
Quick Start
# 1. Clone
git clone https://github.com/SaadRiaz99/postgres-mcp-server.git
cd postgres-mcp-server
# 2. Create and activate a virtual environment
python -m venv .venv
.venv\Scripts\activate # Windows
# source .venv/bin/activate # Linux / macOS
# 3. Install
pip install -e ".[dev]" # editable install with dev tools
# or: pip install -r requirements.txt
# 4. Configure
copy .env.example .env # Windows
# cp .env.example .env # Linux / macOS
# Edit .env with your database credentials
# 5. Run
python -m app.server
# or: postgres-mcpThe server uses stdio by default, which is what most MCP clients expect. Set
TRANSPORT=http or TRANSPORT=sse to expose it over the network.
Minimal .env
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_NAME=postgres
DATABASE_USER=postgres
DATABASE_PASSWORD=your_password
READ_ONLY_MODE=true
MCP_ROLE=analyst
DATABASE_URLis used for SQLAlchemy-style access, while the asyncpg pool uses the individualDATABASE_HOST/DATABASE_PORT/DATABASE_NAME/DATABASE_USER/DATABASE_PASSWORDfields. Set both consistently.
Configuration
All settings are typed and validated by Pydantic Settings. See
.env.example for the complete list.
Database
Variable | Default | Description |
|
| SQLAlchemy URL |
|
| asyncpg host |
|
| asyncpg port |
|
| Database name |
|
| Database user |
|
| Database password |
|
| Maximum pool connections |
|
| Minimum pool connections |
|
| Extra connections beyond the pool size |
Server
Variable | Default | Description |
|
|
|
|
| Bind host for HTTP/SSE |
|
| Bind port for HTTP/SSE |
|
|
|
|
| Debug mode |
|
| Pagination / result cap |
|
| Statement timeout in seconds |
Security and access
Variable | Default | Description |
|
| Reject write statements |
|
|
|
|
| Expose AI helper tools |
|
| Structured audit log for tool calls |
|
| Include SQL text in audit records |
|
| Run injection heuristics |
|
| Allow EXPLAIN ANALYZE (executes the query) |
|
| Requests per window per tool |
|
| Window length in seconds |
Performance and services
Variable | Default | Description |
|
| Query cache TTL (seconds) |
|
| Schema cache TTL (seconds) |
|
| Statistics cache TTL (seconds) |
|
| Entries per cache |
|
| Rows per streamed chunk |
|
| Maximum streamed rows |
|
| Uses before a statement is "prepared" |
|
| Tracked prepared statements |
|
| Seconds between health probes |
|
| Failures before unhealthy |
|
| Buffered LISTEN/NOTIFY messages |
Client Configuration
Claude Desktop
Add to claude_desktop_config.json:
{
"mcpServers": {
"postgres": {
"command": "python",
"args": ["-m", "app.server"],
"cwd": "/path/to/postgres-mcp-server",
"env": {
"DATABASE_HOST": "localhost",
"DATABASE_PORT": "5432",
"DATABASE_NAME": "your_db",
"DATABASE_USER": "your_user",
"DATABASE_PASSWORD": "your_password",
"READ_ONLY_MODE": "true",
"MCP_ROLE": "analyst"
}
}
}
}Cursor / VS Code
{
"mcpServers": {
"postgres": {
"command": "python",
"args": ["-m", "app.server"],
"cwd": "/path/to/postgres-mcp-server"
}
}
}If the client does not support cwd, launch through a wrapper script that
changes directory first.
HTTP / SSE
TRANSPORT=http HOST=0.0.0.0 PORT=8000 python -m app.serverThe MCP endpoint is served by FastMCP on the configured host and port.
Available Tools
Database information
Tool | Description |
| List accessible databases |
| Current database name |
| List schemas |
| List tables in a schema |
| List views |
| List functions |
| List indexes |
| List sequences |
| List installed extensions |
Schema inspection
Tool | Description |
| Full table description |
| Column metadata |
| Foreign key relationships |
| Primary key columns |
| Unique constraints |
| Check constraints |
| Table size including indexes |
| Total database size |
Query execution
Tool | Description |
| Structured SELECT with filters and pagination |
| Insert one or more rows |
| Update rows matched by a WHERE clause |
| Delete rows matched by a WHERE clause |
| Raw SQL execution with offset/limit |
Transactions
Tool | Description |
| Start a transaction and return its ID |
| Commit a transaction |
| Roll a transaction back |
Administration
Tool | Description |
| Active connections |
| Running queries |
| Locks and blocking relationships |
| Vacuum and dead-tuple information |
| Update table statistics |
| Server version |
| Server settings, optionally filtered |
AI assistance
Tool | Description |
| Generate SQL from a natural-language description |
| Explain a query in plain English |
| Suggest optimisations |
| Validate without executing |
| Injection-pattern analysis |
| Cost estimate using the planner |
pgvector
Tool | Description |
| Create the |
| Create a table with an embedding column |
| Store an embedding |
| Nearest-neighbour search |
| Update an embedding |
| Delete an embedding |
| Vector table statistics |
Migrations
Tool | Description |
| Current revision |
| Applied revisions |
| Upgrade to a target revision |
| Downgrade to a target revision |
| Pending revisions |
| Generate an autogenerated revision |
Notifications
Tool | Description |
| Send a |
| Start listening on a channel |
| Stop listening ( |
| Read buffered notifications |
Metrics and diagnostics
Tool | Description |
| Dashboard: duration, error rate, top tools, rows |
| Queries above a duration threshold |
| Connection, pool, cache, and service status |
| Detailed health report with issues and recommendations |
| EXPLAIN plan summary and optimisation hints |
| Missing, unused, and duplicate index candidates |
| PostgreSQL roles, attributes, and memberships |
| Configured MCP role and its allowed tools |
| Clear metrics, caches, and prepared counters |
Catalog inspection
Tool | Description |
| Case-insensitive column-name search |
| Trigger events and actions for a table |
| Visible table grants |
| Estimated rows, scans, maintenance timestamps |
| Index scans, size, uniqueness, validity |
| Blocked and blocking PIDs in the current database |
Catalog inspection tools default to the public schema, accept limit values
from 1–1000 (default 100), and use bound parameters. Results include success,
data, count, limit, and duration_ms; invalid input and database errors
return structured error objects. These tools are read-only.
Catalog visibility depends on database grants. Empty results can mean "nothing matches" or "not visible". Statistics are estimates/counters since collection or reset, so zero index scans alone are not a reason to drop an index.
MCP Resources
URI | Description |
| Tables, views, and relationships |
| Detailed table schema |
| Health, pool, and metrics snapshot |
| Non-secret runtime configuration |
| Compact metrics for dashboards |
| Allowed/denied tools for the configured role |
MCP Prompts
optimize_this_query, explain_this_query, design_schema, and debug_query
provide ready-made prompts for common SQL workflows.
Security
Guardrails
The server blocks or flags dangerous operations before execution:
DROP DATABASE,DROP ROLE, and other destructive DDLALTER SYSTEMCOPY ... PROGRAMTRUNCATE(destructive; blocked or confirmation-gated)pg_sleep(),pg_read_file(),pg_write_file()Multi-statement queries (a single trailing semicolon is allowed)
SQL injection patterns (comment-, union-, and stacked-query based)
Statements are comment- and string-aware, so text such as
SELECT 'DROP DATABASE production' is not falsely rejected.
Read-only mode
With READ_ONLY_MODE=true — or MCP_ROLE=viewer / MCP_ROLE=analyst — only
read statements (SELECT, EXPLAIN, and read-only CTEs) are allowed. CTEs that
perform writes are rejected even when they end in SELECT.
Role-based access control
MCP_ROLE selects the active role. Every registered tool is mapped to a minimum
role, and the server denies calls below that level before touching the database.
Role | Access |
Viewer | Metadata, catalog inspection, health, metrics, read-only AI analysis |
Analyst | Viewer + |
Developer | Analyst + INSERT/UPDATE/DELETE, transactions, pgvector writes, NOTIFY |
DBA | Developer + admin tools, blocking queries, role inspection, migrations |
Admin | Everything, including |
Application-level RBAC is a convenience and defence-in-depth layer. It is not a substitute for PostgreSQL grants, row-level security, or authenticated authorization. Use a dedicated low-privilege database role for the server.
Audit logging
When ENABLE_AUDIT_LOG=true, each tool call records the tool name, success,
duration, risk level, and (optionally) the SQL text. Set AUDIT_LOG_SQL=false
for sensitive workloads.
Docker
# Build
docker build -t postgres-mcp .
# Run over stdio (no ports needed)
docker run -i --rm \
-e DATABASE_HOST=host.docker.internal \
-e DATABASE_NAME=your_db \
-e DATABASE_USER=your_user \
-e DATABASE_PASSWORD=your_password \
postgres-mcp
# Run over HTTP
docker run --rm -p 8000:8000 \
-e TRANSPORT=http \
-e DATABASE_HOST=host.docker.internal \
-e DATABASE_NAME=your_db \
postgres-mcpDocker Compose
docker compose up --buildThis starts PostgreSQL and the MCP server. The bundled database is for local development only — do not reuse the default credentials in production.
Architecture
app/
├── server.py # FastMCP wiring: tools, resources, prompts, lifecycle
├── config.py # Typed Pydantic settings
├── database.py # Async pool, transactions, retries, health ping
├── dependencies.py
├── guards/
│ ├── sql_guard.py # Statement classification, injection detection
│ └── permissions.py # Role hierarchy and tool permission map
├── tools/
│ ├── schema_tools.py # Database/schema inspection
│ ├── query_tools.py # CRUD and raw query execution
│ ├── transaction_tools.py # Transaction management
│ ├── admin_tools.py # Monitoring and administration
│ ├── ai_tools.py # SQL generation, explanation, optimisation
│ ├── vector_tools.py # pgvector helpers
│ ├── migration_tools.py # Alembic integration
│ ├── inspection_tools.py # Catalog inspection
│ └── diagnostics_tools.py # Plans, health, roles, indexes
├── services/
│ ├── audit.py # Structured audit logging
│ ├── cache.py # TTL caches (query/schema/stats)
│ ├── rate_limiter.py # Token-bucket limiter per tool
│ ├── metrics.py # Tool metrics and percentiles
│ ├── health.py # Background health checks
│ ├── notifications.py # LISTEN/NOTIFY buffer
│ ├── prepared_cache.py # Prepared-statement tracking
│ ├── streaming.py # Chunked result streaming
│ ├── query_planner.py # EXPLAIN plan parsing and summarisation
│ └── multi_db.py # Multiple database connections
├── models/schemas.py # Pydantic input/output models
└── utils/
├── logging.py # Structured logging
├── errors.py # Error formatting
└── helpers.py # Pagination, hashing, identifiers, timingRequest flow:
MCP client
│
▼
FastMCP tool ──► _guard() ──► RBAC check ──► read-only classification
│ │
│ └─► rate limiter
▼
Tool implementation ──► SQL guard ──► database pool (asyncpg)
│
└─► metrics / audit / cache / prepared-statement trackingDevelopment
# Install dev dependencies
pip install -e ".[dev]"
# Tests
python -m pytest
# Fast run without coverage and verbose output
python -m pytest -o addopts="" -q
# Lint
ruff check app/ tests/
# Format
black app/ tests/
# Type check
mypy app/The suite covers configuration, guards, helpers, caches, rate limiting, metrics, health, notifications, prepared statements, all tool modules, diagnostics, and plan analysis. Database-dependent tests use mocks; run a subset against a real PostgreSQL instance for integration confidence.
Linting and CI
ruffandblackare configured inpyproject.toml.pre-commit-config.yamlruns formatting, linting, and basic hygiene checks.github/workflows/ci.ymlruns lint, tests, and packaging on every push
Enable pre-commit once per clone:
pre-commit installTroubleshooting
Symptom | Likely cause / fix |
| Fix the scheme in |
Connection refused | Check |
Tool returns permission denied | Lower-privilege |
Writes rejected |
|
| Set |
Empty catalog results | Database grants hide objects; test with a more privileged role |
Server exits immediately under Docker | Stdio transport needs |
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
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 Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Related MCP Servers
- AlicenseAqualityDmaintenanceEnables 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 gradedqualityCmaintenanceEnables secure, AI-driven PostgreSQL database administration, observability, and querying with support for extensions like PostGIS and pgvector, connection pooling, and advanced tool filtering.108 npm12MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to safely explore, analyze, and maintain PostgreSQL databases with read-only mode by default, SQL injection prevention, query performance analysis, and optional write operations.55 npmApache 2.0
- AlicenseNot gradedqualityNot gradedmaintenanceProvides AI assistants with safe, controlled access to PostgreSQL databases with read-only defaults, granular permissions, query safety features, and schema introspection capabilities.1-