Enterprise PostgreSQL MCP Server
by kd444
README.md
# Enterprise PostgreSQL MCP Server
๐ **The Ultimate Independent PostgreSQL MCP Server** - Enterprise-grade security with developer-friendly features, built from the ground up with zero external dependencies.
## ๐ Two Modes, One Codebase
### ๐ง **Developer Mode** (`MCP_DBA_MODE=true` + `developer` role)
**Advanced database exploration with security** - Perfect for development environments:
**๐ง Schema Intelligence:**
- `dba.list_schemas()` - Browse all database schemas
- `dba.list_objects()` - Explore tables, views, sequences
- `dba.get_object_details()` - Detailed table/view information with columns and indexes
**โก Index Tuning & Performance:**
- `dba.analyze_workload_indexes()` - Microsoft DTA-inspired workload analysis
- `dba.analyze_query_indexes()` - Analyze specific queries for optimization
- `dba.explain_query()` - EXPLAIN plans with hypothetical index simulation
- `dba.get_top_queries()` - Find slowest queries using pg_stat_statements
**๐ Database Health:**
- `dba.analyze_db_health()` - 7-category health analysis:
- Buffer cache hit rates
- Index health (unused/duplicate)
- Connection utilization
- Vacuum health
- Sequence limits
- Replication lag
- Constraint validation
**๐ป Direct SQL Execution:**
- `dba.execute_sql()` - Safe SQL execution with AST parsing and validation
### ๐ก๏ธ **Production Mode** (`MCP_DBA_MODE=false`)
**Enterprise security** - Safe for production environments:
**๐ Security-First Design:**
- **Read-only by default** with PostgreSQL role-based security
- **Row Level Security (RLS)** for tenant isolation
- **JWT authentication** for HTTP transport
- **Rate limiting** and resource caps
- **Audit logging** for all operations
- **Data masking** for PII protection
**๐ Allowlisted Queries Only:**
- **No arbitrary SQL** - only parameterized queries from `queries.yaml`
- **Tenant-scoped data** using `current_setting('app.tenant_id')`
- **Pagination** with configurable limits
- **Export controls** with row caps
### ๐ Dual Transport Support
**stdio** - for IDE clients (Cursor, Claude Desktop)
**HTTP/ASGI** - mountable under Django or FastAPI at `/mcp`
## ๐ฏ Why Choose This MCP Server?
| Our Server | CrystalDBA | Standard MCP |
| ------------------------------------ | --------------------------- | ------------------------- |
| โ
**Best of Both Worlds** | โ
Developer-friendly | โ Basic features only |
| โ
**Production Security** | โ Limited security | โ No enterprise features |
| โ
**Dual Transport** (stdio + HTTP) | โ
Multiple transports | โ Usually stdio only |
| โ
**Enterprise Multi-Tenancy** | โ No RLS/tenant isolation | โ No audit/compliance |
| โ
**All CrystalDBA Tools** | โ
Full feature set | โ Basic queries only |
| โ
**Industrial-Grade Algorithms** | โ
Microsoft DTA algorithms | โ No optimization tools |
## ๐๏ธ Enterprise Features
- **Config-driven** with allowlisted queries
- **Metrics collection** and observability
- **Docker ready** with health checks
- **FastAPI/Django integration** examples
## ๐ฆ Quick Start
### 1. Complete Setup from Scratch (Step-by-Step)
Here are the exact commands used to set up this project:
```bash
# 1. Clone the repository
git clone https://github.com/kd444/enterprise-postgres-mcp.git .
# 2. Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate
# 3. Install dependencies
pip install mcp asyncpg pydantic pydantic-settings fastapi "uvicorn[standard]" starlette "python-jose[cryptography]" httpx structlog pyyaml python-multipart typing-extensions
# 4. Set up environment file
cp env.example .env
# 5. Start PostgreSQL (if using existing installation)
# Make sure PostgreSQL is running on localhost:5432
# 6. Create database and initialize schema
PGPASSWORD=password psql -h localhost -p 5432 -U postgres -c "CREATE DATABASE enterprise_db;"
PGPASSWORD=password psql -h localhost -p 5432 -U postgres -d enterprise_db -f init.sql
# 7. Test the setup
source venv/bin/activate
python -c "import server; print('Server import successful')"
# 8. Test database connectivity
python -c "
import asyncio
import asyncpg
async def test_db():
conn = await asyncpg.connect('postgresql://mcp_readonly:readonly_password@localhost:5432/enterprise_db')
await conn.execute('SET app.tenant_id = \'11111111-1111-1111-1111-111111111111\'')
result = await conn.fetchval('SELECT COUNT(*) FROM api.tenants')
print(f'Connected successfully! Found {result} tenants')
await conn.close()
asyncio.run(test_db())
"
# 9. Run stdio transport (for Cursor/Claude)
python server.py --transport stdio
# 10. Or run HTTP transport
python server.py --transport http --port 8000
```
### 2. Using Docker Compose (Alternative)
```bash
# Clone and start
git clone https://github.com/kd444/enterprise-postgres-mcp.git
cd enterprise-postgres-mcp
# Start PostgreSQL + MCP Server
docker-compose up -d
# Check health
curl http://localhost:8000/health
```
### 3. Quick Local Development
```bash
# Install dependencies
pip install -e .
# Set environment variables
export MCP_DATABASE_URI="postgresql://mcp_readonly:password@localhost:5432/enterprise_db"
export MCP_QUERY_REGISTRY_PATH="queries.yaml"
# Run stdio transport (for Cursor/Claude)
python server.py --transport stdio
# Or HTTP transport
python server.py --transport http --port 8000
```
## ๐ง Configuration
### Environment Variables
```bash
# Database (required)
MCP_DATABASE_URI=postgresql://mcp_readonly:password@localhost:5432/db
# Query Registry
MCP_QUERY_REGISTRY_PATH=queries.yaml
# Security & Limits
MCP_MAX_ROWS=500
MCP_MAX_EXPORT_ROWS=2000
MCP_STATEMENT_TIMEOUT_MS=3000
MCP_RATE_LIMIT_REQUESTS=100
# Authentication (HTTP transport)
MCP_JWT_SECRET_KEY=your_secret_key
MCP_JWT_ISSUER=your_issuer
MCP_JWKS_URL=https://your-auth-provider/.well-known/jwks.json
# Stdio Authentication (development)
MCP_STDIO_TOKEN=dev_token_123
# Features
MCP_AUDIT_ENABLED=true
MCP_METRICS_ENABLED=true
MCP_DBA_MODE=false # Never true in production
```
### Database Setup
The server requires a PostgreSQL database with:
1. **Read-only role** with `default_transaction_read_only=on`
2. **Row Level Security** enabled on all tables
3. **Tenant isolation** via RLS policies
See [`init.sql`](./init.sql) for complete setup.
## ๐ก Usage Examples
### ๐ง Developer Mode Examples
When `MCP_DBA_MODE=true`, you get all CrystalDBA features:
**๐ง Schema Exploration:**
```
Ask: "Show me all schemas in the database"
โ Uses: dba.list_schemas()
Ask: "What tables are in the public schema?"
โ Uses: dba.list_objects(schema="public")
Ask: "Describe the users table structure"
โ Uses: dba.get_object_details(schema="public", name="users", object_type="table")
```
**โก Performance Optimization:**
```
Ask: "My app is slow. How can I make it faster?"
โ Uses: dba.analyze_db_health() + dba.get_top_queries()
Ask: "Analyze this query for optimization: SELECT * FROM orders WHERE customer_id = 123"
โ Uses: dba.explain_query() + dba.analyze_query_indexes()
Ask: "What are the slowest queries in my database?"
โ Uses: dba.get_top_queries(sort_by="total_time")
```
**๐ Database Health:**
```
Ask: "Check the health of my database"
โ Uses: dba.analyze_db_health()
Ask: "Are there any unused indexes I can remove?"
โ Uses: dba.analyze_db_health() (checks index health)
Ask: "What's my buffer cache hit rate?"
โ Uses: dba.analyze_db_health() (includes cache analysis)
```
**๐ป Direct SQL (Safe):**
```
Ask: "Run this query: SELECT COUNT(*) FROM orders WHERE created_at > '2023-01-01'"
โ Uses: dba.execute_sql(sql="...", analyze=true)
```
### ๐ก๏ธ Production Mode Examples
When `MCP_DBA_MODE=false`, you get enterprise security:
**๐ Allowlisted Queries Only:**
```
Ask: "Show me recent orders for my tenant"
โ Uses: db.run_query(name="orders_by_tenant", params={"since": "2023-01-01"})
Ask: "Search for invoices containing 'ACME'"
โ Uses: db.run_query(name="search_invoices", params={"q": "ACME"})
Ask: "Export customer data to CSV"
โ Uses: export.csv(name_or_view="customer_summary")
```
**๐ข Multi-Tenant Security:**
```
All queries automatically filtered by tenant:
- SET LOCAL app.tenant_id = '${your_tenant_uuid}'
- RLS policies enforce data isolation
- No cross-tenant data access possible
```
**๐ Analytics & Insights:**
```
Ask: "How many orders per month this year?"
โ Uses: db.aggregate(view="orders", group_by=["month"], metrics=["count"])
Ask: "Sample some customer data"
โ Uses: db.sample(view="customers", limit=10, method="random")
```
## ๐ Integration Examples
### Cursor IDE
**๐ง Developer Mode** (Full CrystalDBA features):
```json
{
"mcpServers": {
"pg-dev": {
"command": "/path/to/venv/bin/python",
"args": ["/path/to/server.py", "--transport", "stdio"],
"cwd": "/path/to/production-mcp-server",
"env": {
"MCP_DATABASE_URI": "postgresql://dev_user:***@localhost:5432/dev_db",
"MCP_QUERY_REGISTRY_PATH": "/path/to/queries.yaml",
"MCP_STDIO_TOKEN": "dev_token_123",
"MCP_DBA_MODE": "true",
"MCP_LOG_LEVEL": "DEBUG"
}
}
}
}
```
**๐ก๏ธ Production Mode** (Secure, allowlisted queries only):
```json
{
"mcpServers": {
"pg-production": {
"command": "/path/to/venv/bin/python",
"args": ["/path/to/server.py", "--transport", "stdio"],
"cwd": "/path/to/production-mcp-server",
"env": {
"MCP_DATABASE_URI": "postgresql://mcp_readonly:***@prod.host:5432/prod_db",
"MCP_QUERY_REGISTRY_PATH": "/path/to/queries.yaml",
"MCP_STDIO_TOKEN": "prod_token_456",
"MCP_DBA_MODE": "false",
"MCP_AUDIT_ENABLED": "true"
}
}
}
}
```
### Claude Desktop
```json
{
"mcpServers": {
"pg-production": {
"command": "python",
"args": ["server.py"],
"env": {
"MCP_DATABASE_URI": "postgresql://mcp_readonly:***@host/db",
"MCP_QUERY_REGISTRY_PATH": "queries.yaml"
}
}
}
}
```
### FastAPI Mount
```python
from fastapi import FastAPI
from starlette.applications import Starlette
from starlette.routing import Mount
from server import ProductionMCPServer
api_app = FastAPI()
mcp_server = ProductionMCPServer()
app = Starlette(routes=[
Mount("/mcp", app=mcp_server.app),
Mount("/", app=api_app),
])
```
### Django ASGI Mount
```python
import os
from django.core.asgi import get_asgi_application
from starlette.applications import Starlette
from starlette.routing import Mount
from server import ProductionMCPServer
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
django_asgi = get_asgi_application()
mcp_server = ProductionMCPServer()
app = Starlette(routes=[
Mount("/mcp", app=mcp_server.app),
Mount("/", app=django_asgi),
])
```
## ๐งฐ MCP Tools
### Authentication & Context
- `auth.whoami()` - Get current user context
- `auth.set_context(purpose)` - Set audit purpose
- `ctx.set_tenant(tenant_id)` - Switch tenant context
- `ctx.get_limits()` - Get current limits/quotas
### Discovery
- `db.list_views(schema)` - List allowed views
- `db.describe_view(name)` - Get view schema with masking info
### Querying
- `db.list_queries()` - List allowlisted queries
- `db.run_query(name, params, page_size, page)` - Execute parameterized query
### Analytics
- `db.count(view, filter)` - Count rows with filtering
- `db.aggregate(view, group_by, metrics)` - Aggregate data
- `db.search_text(view, q, fields)` - Full-text search
- `db.sample(view, limit, method)` - Sample data
### Export
- `export.csv(name_or_view, params, max_rows)` - Export to CSV
### Observability
- `health.check()` - System health status
- `health.limits()` - Usage and limits
- `audit.begin_span(purpose)` - Start audit span
- `audit.end_span(span_id, status)` - End audit span
- `metrics.timeseries(kind, window)` - Get metrics data
## ๐๏ธ Query Registry
Queries are defined in `queries.yaml`:
```yaml
orders_by_tenant:
description: "Get orders for current tenant"
sql: |
SELECT id, total, status, created_at, customer_name
FROM api.orders
WHERE tenant_id = current_setting('app.tenant_id', true)::uuid
AND created_at >= COALESCE($1, '1900-01-01'::timestamp)
ORDER BY created_at DESC
LIMIT 500
params:
since:
type: datetime
required: false
description: "Filter orders after this date"
mask_columns: []
allow_export: true
max_rows: 500
tags: ["orders", "tenant"]
```
### Query Requirements
- Must start with `SELECT`
- Must include tenant filtering: `current_setting('app.tenant_id', true)::uuid`
- No dangerous keywords (`INSERT`, `UPDATE`, `DELETE`, etc.)
- Parameters are validated and type-cast
## ๐ก๏ธ Security Model
### Database Security
```sql
-- Read-only role
CREATE ROLE mcp_readonly WITH LOGIN PASSWORD '***'
NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT;
-- Default read-only transactions
ALTER ROLE mcp_readonly SET default_transaction_read_only = on;
ALTER ROLE mcp_readonly SET row_security = on;
-- Tenant isolation via RLS
CREATE POLICY tenant_isolation ON api.orders
FOR ALL TO mcp_readonly
USING (tenant_id = current_setting('app.tenant_id', true)::uuid);
```
### Runtime Security
Every request enforces:
```sql
SET LOCAL role mcp_readonly;
SET LOCAL row_security = on;
SET LOCAL statement_timeout = '3s';
SET LOCAL idle_in_transaction_session_timeout = '2s';
SET LOCAL app.tenant_id = '<tenant_uuid>';
```
### Data Protection
- **PII Masking**: Email, phone, SSN, credit cards automatically masked
- **Column Allowlists**: Only approved columns returned
- **Row Limits**: Hard caps prevent data exfiltration
- **Rate Limiting**: Per-client request limits
## ๐ Monitoring & Observability
### Audit Logs
All tool calls logged with:
```json
{
"timestamp": "2025-01-15T10:30:00Z",
"tool_name": "db.run_query",
"tenant_id": "11111111-1111-1111-1111-111111111111",
"user_id": "user123",
"purpose": "monthly_report",
"query_name": "orders_by_tenant",
"duration_ms": 45.2,
"rows_returned": 150,
"truncated": false,
"success": true,
"transport": "http"
}
```
### Metrics
- **Query Performance**: Latency, throughput, error rates
- **Resource Usage**: Connection pool, memory, CPU
- **Security Events**: Failed auth, rate limits, policy violations
### Health Checks
```bash
# Application health
curl http://localhost:8000/health
# Database connectivity
curl -H "Authorization: Bearer <jwt>" \
http://localhost:8000/mcp \
-d '{"method": "tools/call", "params": {"name": "health.check"}}'
```
## ๐งช Testing
```bash
# Run tests
pytest tests/
# Test specific areas
pytest tests/test_security.py
pytest tests/test_limits.py
pytest tests/test_registry.py
```
### Key Test Scenarios
- **RLS Enforcement**: Cross-tenant data access blocked
- **Rate Limiting**: Request limits enforced
- **Parameter Validation**: SQL injection prevention
- **Row Limits**: Truncation and pagination
- **Masking**: PII protection
## ๐ Deployment
### Docker Production
```dockerfile
FROM python:3.12-slim
# ... (see Dockerfile)
```
```bash
# Build
docker build -t mcp-server .
# Run stdio mode
docker run -e MCP_DATABASE_URI="postgresql://..." mcp-server
# Run HTTP mode
docker run -p 8000:8000 -e MCP_DATABASE_URI="postgresql://..." \
mcp-server python server.py --transport http
```
### Kubernetes
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: mcp-server
spec:
replicas: 3
selector:
matchLabels:
app: mcp-server
template:
metadata:
labels:
app: mcp-server
spec:
containers:
- name: mcp-server
image: mcp-server:latest
ports:
- containerPort: 8000
env:
- name: MCP_DATABASE_URI
valueFrom:
secretKeyRef:
name: mcp-secrets
key: database-uri
- name: MCP_JWT_SECRET_KEY
valueFrom:
secretKeyRef:
name: mcp-secrets
key: jwt-secret
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 30
periodSeconds: 10
```
## ๐ง Troubleshooting
### Common Issues
**Database Connection Failed**
```bash
# Check connection
psql $MCP_DATABASE_URI -c "SELECT 1"
# Verify role exists
psql $MCP_DATABASE_URI -c "\du mcp_readonly"
```
**RLS Not Working**
```sql
-- Check RLS is enabled
SELECT schemaname, tablename, rowsecurity
FROM pg_tables WHERE schemaname = 'api';
-- Test tenant isolation
SET app.tenant_id = '11111111-1111-1111-1111-111111111111';
SELECT count(*) FROM api.orders;
```
**JWT Authentication Failed**
```bash
# Test JWT decode
python -c "import jwt; print(jwt.decode('$TOKEN', verify=False))"
# Check JWKS endpoint
curl https://your-auth-provider/.well-known/jwks.json
```
## ๐ค Contributing
1. Fork the repository
2. Create feature branch: `git checkout -b feature/amazing-feature`
3. Add tests for your changes
4. Ensure tests pass: `pytest`
5. Submit pull request
## ๐ License
MIT License - see [LICENSE](LICENSE) for details.
## ๐ Support
- **Issues**: GitHub Issues
- **Security**: security@yourcompany.com
- **Documentation**: [Wiki](./wiki)
---
**Built for production. Secured by design. Ready to scale.** ๐
This server cannot be deployed
Maintenance
ActivityInactive
ResponsivenessOutdated data