Skip to main content
Glama
PostgreSQL MCP Server

PostgreSQL MCP Server

by SaadRiaz99
README.md
# 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.toml` packaging, and a `postgres-mcp` console entry point

---

## Prerequisites

- Python **3.12+**
- PostgreSQL **14+**
- pip (or [uv](https://docs.astral.sh/uv/))

## Quick Start

```bash
# 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-mcp
```

The 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`

```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_URL` is used for SQLAlchemy-style access, while the asyncpg pool uses
> the individual `DATABASE_HOST` / `DATABASE_PORT` / `DATABASE_NAME` /
> `DATABASE_USER` / `DATABASE_PASSWORD` fields. Set both consistently.

---

## Configuration

All settings are typed and validated by Pydantic Settings. See
[`.env.example`](.env.example) for the complete list.

### Database

| Variable | Default | Description |
|----------|---------|-------------|
| `DATABASE_URL` | `postgresql+asyncpg://postgres:postgres@localhost:5432/postgres` | SQLAlchemy URL |
| `DATABASE_HOST` | `localhost` | asyncpg host |
| `DATABASE_PORT` | `5432` | asyncpg port |
| `DATABASE_NAME` | `postgres` | Database name |
| `DATABASE_USER` | `postgres` | Database user |
| `DATABASE_PASSWORD` | `postgres` | Database password |
| `CONNECTION_POOL_SIZE` | `10` | Maximum pool connections |
| `CONNECTION_MIN_SIZE` | `2` | Minimum pool connections |
| `CONNECTION_MAX_OVERFLOW` | `20` | Extra connections beyond the pool size |

### Server

| Variable | Default | Description |
|----------|---------|-------------|
| `TRANSPORT` | `stdio` | `stdio`, `http`, or `sse` |
| `HOST` | `0.0.0.0` | Bind host for HTTP/SSE |
| `PORT` | `8000` | Bind port for HTTP/SSE |
| `LOG_LEVEL` | `INFO` | `DEBUG` … `CRITICAL` |
| `DEBUG` | `false` | Debug mode |
| `MAX_QUERY_ROWS` | `1000` | Pagination / result cap |
| `QUERY_TIMEOUT` | `30` | Statement timeout in seconds |

### Security and access

| Variable | Default | Description |
|----------|---------|-------------|
| `READ_ONLY_MODE` | `false` | Reject write statements |
| `MCP_ROLE` | `admin` | `viewer`, `analyst`, `developer`, `dba`, or `admin` |
| `ENABLE_AI_SQL` | `true` | Expose AI helper tools |
| `ENABLE_AUDIT_LOG` | `true` | Structured audit log for tool calls |
| `AUDIT_LOG_SQL` | `true` | Include SQL text in audit records |
| `ENABLE_SQL_INJECTION_DETECTION` | `true` | Run injection heuristics |
| `ENABLE_EXPLAIN_ANALYZE` | `false` | Allow EXPLAIN ANALYZE (executes the query) |
| `RATE_LIMIT_REQUESTS` | `100` | Requests per window per tool |
| `RATE_LIMIT_WINDOW` | `60` | Window length in seconds |

### Performance and services

| Variable | Default | Description |
|----------|---------|-------------|
| `QUERY_CACHE_TTL` | `60` | Query cache TTL (seconds) |
| `SCHEMA_CACHE_TTL` | `300` | Schema cache TTL (seconds) |
| `STATS_CACHE_TTL` | `15` | Statistics cache TTL (seconds) |
| `CACHE_MAX_SIZE` | `1000` | Entries per cache |
| `STREAM_CHUNK_SIZE` | `500` | Rows per streamed chunk |
| `STREAM_MAX_ROWS` | `100000` | Maximum streamed rows |
| `PREPARED_STATEMENT_THRESHOLD` | `3` | Uses before a statement is "prepared" |
| `PREPARED_CACHE_SIZE` | `200` | Tracked prepared statements |
| `HEALTH_CHECK_INTERVAL` | `30` | Seconds between health probes |
| `HEALTH_CHECK_MAX_FAILURES` | `3` | Failures before unhealthy |
| `NOTIFICATION_BUFFER_SIZE` | `1000` | Buffered LISTEN/NOTIFY messages |

---

## Client Configuration

### Claude Desktop

Add to `claude_desktop_config.json`:

```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

```json
{
  "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

```bash
TRANSPORT=http HOST=0.0.0.0 PORT=8000 python -m app.server
```

The MCP endpoint is served by FastMCP on the configured host and port.

---

## Available Tools

### Database information

| Tool | Description |
|------|-------------|
| `list_databases` | List accessible databases |
| `current_database` | Current database name |
| `list_schemas` | List schemas |
| `list_tables` | List tables in a schema |
| `list_views` | List views |
| `list_functions` | List functions |
| `list_indexes` | List indexes |
| `list_sequences` | List sequences |
| `list_extensions` | List installed extensions |

### Schema inspection

| Tool | Description |
|------|-------------|
| `describe_table` | Full table description |
| `describe_column` | Column metadata |
| `foreign_keys` | Foreign key relationships |
| `primary_keys` | Primary key columns |
| `unique_constraints` | Unique constraints |
| `check_constraints` | Check constraints |
| `table_size` | Table size including indexes |
| `database_size` | Total database size |

### Query execution

| Tool | Description |
|------|-------------|
| `execute_select` | Structured SELECT with filters and pagination |
| `execute_insert` | Insert one or more rows |
| `execute_update` | Update rows matched by a WHERE clause |
| `execute_delete` | Delete rows matched by a WHERE clause |
| `execute_query` | Raw SQL execution with offset/limit |

### Transactions

| Tool | Description |
|------|-------------|
| `begin_transaction` | Start a transaction and return its ID |
| `commit_transaction` | Commit a transaction |
| `rollback_transaction` | Roll a transaction back |

### Administration

| Tool | Description |
|------|-------------|
| `active_connections` | Active connections |
| `running_queries` | Running queries |
| `locks` | Locks and blocking relationships |
| `vacuum_status` | Vacuum and dead-tuple information |
| `analyze_table` | Update table statistics |
| `server_version` | Server version |
| `server_settings` | Server settings, optionally filtered |

### AI assistance

| Tool | Description |
|------|-------------|
| `generate_sql` | Generate SQL from a natural-language description |
| `explain_sql` | Explain a query in plain English |
| `optimize_sql` | Suggest optimisations |
| `validate_sql` | Validate without executing |
| `detect_sql_injection` | Injection-pattern analysis |
| `estimate_query_cost` | Cost estimate using the planner |

### pgvector

| Tool | Description |
|------|-------------|
| `install_pgvector` | Create the `vector` extension |
| `create_vector_table` | Create a table with an embedding column |
| `store_embedding` | Store an embedding |
| `search_similar` | Nearest-neighbour search |
| `update_embedding` | Update an embedding |
| `delete_embedding` | Delete an embedding |
| `vector_stats` | Vector table statistics |

### Migrations

| Tool | Description |
|------|-------------|
| `migration_current` | Current revision |
| `migration_history` | Applied revisions |
| `migration_upgrade` | Upgrade to a target revision |
| `migration_downgrade` | Downgrade to a target revision |
| `migration_pending` | Pending revisions |
| `migration_generate` | Generate an autogenerated revision |

### Notifications

| Tool | Description |
|------|-------------|
| `notify` | Send a `NOTIFY` payload |
| `listen` | Start listening on a channel |
| `unlisten` | Stop listening (`*` removes all) |
| `get_notifications` | Read buffered notifications |

### Metrics and diagnostics

| Tool | Description |
|------|-------------|
| `query_metrics` | Dashboard: duration, error rate, top tools, rows |
| `slow_queries` | Queries above a duration threshold |
| `health_check` | Connection, pool, cache, and service status |
| `database_health` | Detailed health report with issues and recommendations |
| `analyze_query_plan` | EXPLAIN plan summary and optimisation hints |
| `index_recommendations` | Missing, unused, and duplicate index candidates |
| `list_roles` | PostgreSQL roles, attributes, and memberships |
| `role_info` | Configured MCP role and its allowed tools |
| `reset_metrics` | Clear metrics, caches, and prepared counters |

### Catalog inspection

| Tool | Description |
|------|-------------|
| `search_columns` | Case-insensitive column-name search |
| `list_triggers` | Trigger events and actions for a table |
| `table_privileges` | Visible table grants |
| `table_statistics` | Estimated rows, scans, maintenance timestamps |
| `index_statistics` | Index scans, size, uniqueness, validity |
| `blocking_queries` | 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 |
|-----|-------------|
| `schema://overview` | Tables, views, and relationships |
| `schema://tables/{table_name}` | Detailed table schema |
| `server://status` | Health, pool, and metrics snapshot |
| `server://config` | Non-secret runtime configuration |
| `metrics://summary` | Compact metrics for dashboards |
| `diagnostics://tool-access` | 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 DDL
- `ALTER SYSTEM`
- `COPY ... PROGRAM`
- `TRUNCATE` (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 + `SELECT`, AI tools, plan analysis, index recommendations, LISTEN |
| **Developer** | Analyst + INSERT/UPDATE/DELETE, transactions, pgvector writes, NOTIFY |
| **DBA** | Developer + admin tools, blocking queries, role inspection, migrations |
| **Admin** | Everything, including `reset_metrics` |

> 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

```bash
# 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-mcp
```

### Docker Compose

```bash
docker compose up --build
```

This 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, timing
```

Request 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 tracking
```

---

## Development

```bash
# 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

- `ruff` and `black` are configured in `pyproject.toml`
- `.pre-commit-config.yaml` runs formatting, linting, and basic hygiene checks
- `.github/workflows/ci.yml` runs lint, tests, and packaging on every push

Enable pre-commit once per clone:

```bash
pre-commit install
```

---

## Troubleshooting

| Symptom | Likely cause / fix |
|---------|-------------------|
| `DATABASE_URL must use postgresql+asyncpg://` | Fix the scheme in `DATABASE_URL` |
| Connection refused | Check `DATABASE_HOST`/`DATABASE_PORT`; the asyncpg pool uses the separate fields |
| Tool returns permission denied | Lower-privilege `MCP_ROLE`; raise it or use a role with access |
| Writes rejected | `READ_ONLY_MODE=true` or role is viewer/analyst |
| `EXPLAIN ANALYZE` disabled | Set `ENABLE_EXPLAIN_ANALYZE=true` and use a read-only statement |
| Empty catalog results | Database grants hide objects; test with a more privileged role |
| Server exits immediately under Docker | Stdio transport needs `-i`; use `TRANSPORT=http` for a long-running service |

---

## License

MIT