A TypeScript-based Model Context Protocol (MCP) server that provides AI assistants with read-only access to PostgreSQL databases for comprehensive analysis and optimization recommendations.
npm install -g blankbrackets-postgres-mcp-serverPackage: blankbrackets-postgres-mcp-server
docker pull blankbrackets/postgres-mcp-server:latestImage: blankbrackets/postgres-mcp-server
git clone https://github.com/blankbrackets/postgres-mcp.git
cd postgres-mcp
npm install && npm run build🎯 Comprehensive Database Analysis - Systematic analysis of entire database with prioritized action plans
🔒 Read-Only by Design - Multi-layer protection ensures no data modifications
📊 10 Specialized Tools - From table discovery to query performance analysis
🤖 AI-Optimized - Designed specifically for LLM-based database optimization
📈 Production-Ready - Extensive logging, error handling, and security features
⚡ Fast Performance - Sub-50ms tool execution for interactive use
- Performance Issues: Slow queries, missing indexes, excessive sequential scans
- Index Problems: Unused indexes, unindexed foreign keys, duplicate indexes
- Schema Issues: Poor data types, high null rates, bloat
- Health Problems: Replication lag, invalid constraints, sequences near max value
- Maintenance Needs: Tables needing VACUUM/ANALYZE, connection issues
Install the published package globally:
npm install -g blankbrackets-postgres-mcp-serverThen configure in Claude Desktop:
{
"mcpServers": {
"postgres-analyzer": {
"command": "blankbrackets-postgres-mcp-server",
"env": {
"DATABASE_URL": "postgresql://readonly_user:password@127.0.0.1:5432/your_db"
}
}
}
}Restart Claude Desktop and start analyzing!
# Build the image
docker build -t postgres-mcp-server .
# Run with your database
docker run -i \
-e DATABASE_URL="postgresql://readonly_user:password@host.docker.internal:5432/your_db" \
-v $(pwd)/logs:/app/logs \
postgres-mcp-serverSee docs/DOCKER.md for detailed Docker instructions.
# Clone the repository
git clone https://github.com/blankbrackets/postgres-mcp.git
cd postgres-mcp
# Install dependencies
npm install
# Build
npm run build
# Configure
cp env.example .env
# Edit .env with your DATABASE_URL
# Run
npm startEnvironment Variables:
DATABASE_URL=postgresql://readonly_user:password@127.0.0.1:5432/your_database
LOG_LEVEL=info # Optional: error, warn, info, debug
QUERY_TIMEOUT=30000 # Optional: Query timeout in msClaude Desktop (~/Library/Application Support/Claude/claude_desktop_config.json):
Using NPM package (recommended after npm install -g blankbrackets-postgres-mcp-server):
{
"mcpServers": {
"postgres-analyzer": {
"command": "blankbrackets-postgres-mcp-server",
"env": {
"DATABASE_URL": "postgresql://readonly_user:password@127.0.0.1:5432/your_database"
}
}
}
}Using local build (for development):
{
"mcpServers": {
"postgres-analyzer": {
"command": "node",
"args": ["/absolute/path/to/postgres-mcp/build/index.js"],
"env": {
"DATABASE_URL": "postgresql://readonly_user:password@127.0.0.1:5432/your_database"
}
}
}
}See examples/ for more configuration examples including Cursor and Docker.
Restart your MCP client (Claude Desktop, Cursor, etc.) and ask:
Do a comprehensive analysis and optimization of my database
The AI will systematically analyze your database and provide actionable recommendations.
Scans the entire database for issues and creates a complete action plan.
Use when: "Optimize my database", "Find all issues", "Complete analysis"
Returns:
- Health score and critical issues summary
- Prioritized list of tables requiring attention
- Step-by-step analysis workflow
- Quick wins and long-term improvements
Database-wide metrics and health assessment.
Returns:
- Cache performance (hit ratios)
- Table statistics (vacuum, analyze, bloat)
- Index statistics (unused indexes)
- Connection utilization (active vs idle)
- Replication health (lag, slots)
- Constraint health (invalid constraints)
- Sequence health (near max value warnings)
Lists all tables with schemas, types, row counts, and sizes.
Use before any table-specific tools to get exact table names.
Identifies slowest queries using pg_stat_statements or analyzes specific queries with EXPLAIN.
Returns:
- Top N slowest queries by execution time
- Query statistics (calls, mean/max time, cache hits)
- EXPLAIN plans for specific queries
- Optimization recommendations
Note: Install pg_stat_statements extension for best results.
Essential for table analysis! Provides detailed query/IO statistics for a specific table.
Returns:
- Sequential vs index scan counts
- Cache hit ratios (buffer cache, index cache)
- Insert/update/delete statistics
- Per-index usage statistics
- Bloat estimation
- Last vacuum/analyze timestamps
Analyzes indexing for a specific table.
Returns:
- Index usage statistics
- Unused indexes (never scanned)
- Missing indexes on foreign keys
- Duplicate/redundant indexes
- High sequential scan warnings
Analyzes schema design for a specific table.
Returns:
- Column statistics (nullability, cardinality, average width)
- Foreign key analysis (indexed vs unindexed)
- Table bloat metrics
- Data type issues (TEXT with low cardinality, oversized VARCHAR)
Returns table structure: columns, data types, indexes, and constraints.
Execute custom READ-ONLY SQL queries.
Use only when specialized tools cannot provide the data.
Allowed: SELECT, WITH, EXPLAIN, SHOW, TABLE, VALUES
Blocked: INSERT, UPDATE, DELETE, DROP, CREATE, ALTER, and all write operations
Complete schema structure with all schemas, tables, columns, indexes, and constraints.
PostgreSQL system catalog documentation to prevent common query errors.
Read this before using execute_query!
The server is read-only by design with multiple protection layers:
- Connection Level:
default_transaction_read_only=on - SQL Validation: Blocks write keywords (INSERT, UPDATE, DELETE, etc.)
- Code Level: No write operations exposed in any tool
- Database User: Recommend SELECT-only privileges (see below)
-- Create read-only user
CREATE USER postgres_mcp_readonly WITH PASSWORD 'secure_password';
GRANT CONNECT ON DATABASE your_database TO postgres_mcp_readonly;
GRANT USAGE ON SCHEMA public TO postgres_mcp_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO postgres_mcp_readonly;
GRANT pg_read_all_stats TO postgres_mcp_readonly;See examples/setup-readonly-user.sql for complete setup.
- ✅ Use a dedicated read-only database user
- ✅ Never commit
.envfiles to version control - ✅ Use SSL/TLS for database connections in production
- ✅ Rotate credentials regularly
- ✅ Limit database access by IP if possible
See examples/example-prompts.md for comprehensive examples.
Recommended workflow:
1. "Do a comprehensive analysis and optimization of my database"
→ Creates complete action plan
2. "What are my slowest queries?"
→ Identifies performance bottlenecks
3. "List all tables"
→ Discovers database structure
4. "Analyze the [table_name] table"
→ Deep dive into specific tables
DATABASE_URL=postgresql://user:password@host:port/database # Required
QUERY_TIMEOUT=30000 # Optional: Query timeout in ms (default: 30000)
LOG_LEVEL=info # Optional: error, warn, info, debug (default: info)Logs are written to:
- File:
logs/postgres-mcp-server.log(rotated at 10MB, 5 files kept) - stderr: Captured by Claude Desktop/Cursor for debugging
# View logs
tail -f logs/postgres-mcp-server.log
# Enable debug logging
# Add to config: "LOG_LEVEL": "debug"# Install dependencies
npm install
# Development mode (with auto-reload)
npm run dev
# Build for production
npm run build
# Run production build
npm start
# Clean build directory
npm run clean- TypeScript with official
@modelcontextprotocol/sdk - Stdio transport for Claude Desktop and Cursor compatibility
- PostgreSQL client via
pglibrary - Winston logging with file rotation
- ES2022 modules with full type safety
See docs/ARCHITECTURE.md for detailed architecture documentation.
Server won't start:
- Check
DATABASE_URLis set - Verify database is accessible
- View logs:
tail -f logs/postgres-mcp-server.log
Tool execution fails:
- Use
list_tablesfirst to discover exact table names - Check PostgreSQL permissions
- Read
postgres://system/catalog-referenceresource
Case sensitivity errors:
- PostgreSQL is case-sensitive with quoted identifiers
- Use exact table names from
list_tables - Quote mixed-case tables:
"MyTable"
See docs/TROUBLESHOOTING.md for detailed troubleshooting.
- Connection: Connects to PostgreSQL with read-only mode enforced
- Discovery: LLM uses
list_tablesto see available tables - Analysis: Uses specialized tools to gather metrics
- Recommendations: LLM analyzes data and suggests optimizations
All operations are read-only - the database cannot be modified.
- Node.js: 18.0.0 or higher
- PostgreSQL: 9.6 or higher
- Database Access: Read permissions (SELECT)
Optional but recommended:
pg_stat_statementsextension for query performance analysis
The server queries PostgreSQL system tables like:
information_schema.*- ANSI SQL standard metadatapg_stat_user_tables- Table statisticspg_stat_user_indexes- Index usagepg_indexes- Index definitions
Important: Column names vary between views. See docs/POSTGRESQL_REFERENCE.md.
# Build
docker build -t postgres-mcp-server .
# Run
docker run -i \
-e DATABASE_URL="postgresql://user:pass@host.docker.internal:5432/db" \
postgres-mcp-serverSee examples/docker-compose.yml:
docker-compose -f examples/docker-compose.yml upPre-built multi-architecture images available:
# Pull latest version
docker pull blankbrackets/postgres-mcp-server:latest
# Or specific version
docker pull blankbrackets/postgres-mcp-server:1.0.0
# Run directly
docker run -i \
-e DATABASE_URL="postgresql://user:pass@host.docker.internal:5432/db" \
blankbrackets/postgres-mcp-server:latestSupported platforms: linux/amd64, linux/arm64
See docs/DOCKER.md for comprehensive Docker documentation.
This server is available on:
- ✅ NPM Registry -
blankbrackets-postgres-mcp-server(View on NPM) - ✅ Docker Hub -
blankbrackets/postgres-mcp-server(View on Docker Hub) - ✅ GitHub - Source code and releases (View on GitHub)
Contributions are welcome! Please see docs/CONTRIBUTING.md for guidelines.
- Additional analysis tools
- Performance improvements
- Better error messages
- Documentation improvements
- Bug fixes
- Translations
- Integration examples
MIT License - see LICENSE file for details.
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Logs: Check
logs/postgres-mcp-server.logfor debugging - Documentation: See
docs/folder
Built with:
- Model Context Protocol by Anthropic
- PostgreSQL
- Node.js and TypeScript
- Winston for logging
- MCP Specification
- MCP TypeScript SDK
- PostgreSQL Documentation
- Postgres MCP Pro - Python-based alternative
Made with ❤️ for the MCP and PostgreSQL communities