Enterprise PostgreSQL MCP Server
Provides tools for PostgreSQL schema exploration, object inspection, index and query analysis, database health checks, and safe SQL execution; production mode restricts access to allowlisted parameterized queries with RLS and tenant isolation.
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.
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 schemasdba.list_objects()- Explore tables, views, sequencesdba.get_object_details()- Detailed table/view information with columns and indexes
โก Index Tuning & Performance:
dba.analyze_workload_indexes()- Microsoft DTA-inspired workload analysisdba.analyze_query_indexes()- Analyze specific queries for optimizationdba.explain_query()- EXPLAIN plans with hypothetical index simulationdba.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.yamlTenant-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
Related MCP server: PostgreSQL MCP Server
๐ฏ 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:
# 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 80002. Using Docker Compose (Alternative)
# 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/health3. Quick Local Development
# 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
# 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 productionDatabase Setup
The server requires a PostgreSQL database with:
Read-only role with
default_transaction_read_only=onRow Level Security enabled on all tables
Tenant isolation via RLS policies
See 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):
{
"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):
{
"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
{
"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
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
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 contextauth.set_context(purpose)- Set audit purposectx.set_tenant(tenant_id)- Switch tenant contextctx.get_limits()- Get current limits/quotas
Discovery
db.list_views(schema)- List allowed viewsdb.describe_view(name)- Get view schema with masking info
Querying
db.list_queries()- List allowlisted queriesdb.run_query(name, params, page_size, page)- Execute parameterized query
Analytics
db.count(view, filter)- Count rows with filteringdb.aggregate(view, group_by, metrics)- Aggregate datadb.search_text(view, q, fields)- Full-text searchdb.sample(view, limit, method)- Sample data
Export
export.csv(name_or_view, params, max_rows)- Export to CSV
Observability
health.check()- System health statushealth.limits()- Usage and limitsaudit.begin_span(purpose)- Start audit spanaudit.end_span(span_id, status)- End audit spanmetrics.timeseries(kind, window)- Get metrics data
๐๏ธ Query Registry
Queries are defined in queries.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
SELECTMust include tenant filtering:
current_setting('app.tenant_id', true)::uuidNo dangerous keywords (
INSERT,UPDATE,DELETE, etc.)Parameters are validated and type-cast
๐ก๏ธ Security Model
Database Security
-- 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:
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:
{
"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
# 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
# Run tests
pytest tests/
# Test specific areas
pytest tests/test_security.py
pytest tests/test_limits.py
pytest tests/test_registry.pyKey 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
FROM python:3.12-slim
# ... (see Dockerfile)# 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 httpKubernetes
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
# Check connection
psql $MCP_DATABASE_URI -c "SELECT 1"
# Verify role exists
psql $MCP_DATABASE_URI -c "\du mcp_readonly"RLS Not Working
-- 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
# 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
Fork the repository
Create feature branch:
git checkout -b feature/amazing-featureAdd tests for your changes
Ensure tests pass:
pytestSubmit pull request
๐ License
MIT License - see LICENSE for details.
๐ Support
Issues: GitHub Issues
Security: security@yourcompany.com
Documentation: Wiki
Built for production. Secured by design. Ready to scale. ๐
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.
Database intelligence, AST SQL injection auditing, query optimization & schema guards.
Governed SQL access to your databases: redaction, query review and an audit log.
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables interaction with PostgreSQL databases through both HTTP and stdio transports. Supports executing read-only SQL queries, listing tables, and retrieving schema information with stateful session management.MIT
- FlicenseNot gradedqualityDmaintenanceProvides read-only access to PostgreSQL databases with schema inspection, query execution in multiple formats (JSON, CSV, Markdown), and query history tracking with built-in security features.-
- AlicenseNot gradedqualityDmaintenanceEnables interaction with PostgreSQL databases through both HTTP and Stdio transports, supporting read-only SQL queries, table listing, and schema inspection. Features stateful session management for HTTP transport and flexible deployment options including Docker support.MIT
- AlicenseBqualityDmaintenanceEnables comprehensive PostgreSQL database management including index tuning, query plan analysis, health monitoring, schema-aware SQL generation, and safe SQL execution with configurable access control for both development and production environments.9MIT