Enables safe PostgreSQL database interaction with tools for schema exploration, query execution, performance analysis, data quality checks, and maintenance operations. Supports both read-only and read-write modes with built-in safety features including SQL injection prevention, rate limiting, and query timeouts.
Postgres Scout MCP
Model Context Protocol server for safe PostgreSQL database interaction. Enables AI assistants to explore, analyze, and maintain PostgreSQL databases with built-in safety features.
Features
Safety First: Read-only mode by default, explicit opt-in for write operations
SQL Injection Prevention: All queries use parameterization
Rate Limiting: Prevent accidental DoS attacks
Comprehensive Logging: Audit trail of all operations
Query Timeouts: Configurable timeout protection
Connection Pooling: Efficient database resource management
Installation
Quick Start
Read-Only Mode (Default)
Safe for production database exploration:
Read-Write Mode
Requires explicit flag:
Configuration
Environment Variables
Claude Desktop Configuration
Add to your Claude Desktop config file:
Available Tools
Database Operations
listDatabases
List all databases the user has access to.
getDatabaseStats
Get comprehensive database statistics.
Note: the database parameter must match the current connection; reconnect to target a different database.
Schema Operations
listSchemas
List all schemas in the database.
listTables
List tables with detailed information.
Notes:
rowEstimateis based on PostgreSQL statistics; whenneedsAnalyzeistrue, runANALYZEfor a reliable estimate.
describeTable
Get comprehensive table information including columns, constraints, and indexes.
Query Operations
executeQuery
Execute SELECT queries with safety checks.
explainQuery
Analyze query performance with EXPLAIN ANALYZE. In read-only mode, analyze is forced to false to avoid executing statements.
Maintenance & Diagnostics
getHealthScore
Calculate overall database health score.
Note: the database parameter must match the current connection; reconnect to target a different database.
getSlowQueries
Analyze slow queries using pg_stat_statements (extension required).
Enum Parameter Reference
exportTable.format:csv,json,jsonl,sqlgetSlowQueries.orderBy:total_time,mean_time,callsgetLiveMetrics.metrics:queries,connections,locks,transactions,cachegetHottestTables.orderBy:seq_scan,idx_scan,writes,sizedetectAnomalies.type:query_performance,data_volume,connections,errors,alldetectAnomalies.sensitivityLevel:low,medium,highanalyzeTimeSeries.groupBy:hour,day,week,monthanalyzeTimeSeries.aggregation:sum,avg,count,min,maxdetectSeasonality.groupBy:day_of_week,day_of_month,month,quarter
Usage Examples
Exploring Database Schema
Analyzing Query Performance
Database Health Check
Security
Read-Only vs Read-Write Mode
Read-Only Mode (default):
SELECT queries
EXPLAIN ANALYZE
Schema inspection
Performance monitoring
Read-Write Mode (requires --read-write flag):
All read-only operations
INSERT, UPDATE, DELETE
CREATE, ALTER, DROP
VACUUM, ANALYZE
SQL Injection Prevention
Multiple layers of protection:
Parameterized Queries: All user data passed as parameters
Input Validation: WHERE clauses, conditions, and ORDER BY validated for dangerous patterns
Identifier Sanitization: Table/column names validated against whitelist pattern
Pattern Detection: Blocks SQL comments, UNION SELECT, and other injection patterns
Rate Limiting
Prevents accidental DoS:
Default: 100 requests per minute
Configurable via environment variables
Can be disabled for trusted environments
Query Timeouts
All queries have configurable timeouts:
Default: 30 seconds
Prevents long-running queries
Protects database resources
Development
Build
Watch Mode
Project Structure
Troubleshooting
Connection Issues
Solutions:
Verify connection string format:
postgresql://user:password@host:port/databaseCheck database server is running
Verify network connectivity
Check firewall rules
Verify credentials
Permission Errors
Solutions:
Verify database user has necessary permissions
In read-only mode, SELECT permission is required
In read-write mode, additional permissions needed
Contact database administrator
Rate Limit Exceeded
Solutions:
Wait for the rate limit window to expire
Increase
RATE_LIMIT_MAX_REQUESTSif neededDisable rate limiting for trusted environments:
ENABLE_RATE_LIMIT=false
Logging
All operations are logged to:
logs/tool-usage.log- All tool executionslogs/error.log- Errors onlyConsole (stderr) - Real-time output
Log format:
Implemented Features
Core Features ✅
Database operations (list databases, stats, health scoring)
Schema inspection (tables, columns, constraints, indexes)
Query execution with safety checks
Query performance analysis (EXPLAIN ANALYZE)
Data Quality Tools ✅
Find duplicates
Find missing values (NULL analysis)
Find orphaned records
Check constraint violations
Analyze type consistency
Export Tools ✅
Export to CSV, JSON, JSONL, SQL
Generate INSERT statements with batching
Temporal Tools ✅
Find recent records
Time series analysis with anomaly detection
Seasonality detection
Monitoring Tools ✅
Current activity monitoring
Lock analysis
Index usage analysis
Mutation Tools ✅ (read-write mode)
Preview UPDATE/DELETE operations
Safe UPDATE with row limits
Safe DELETE with row limits
Roadmap
Future Enhancements
AI-powered index recommendations
Partitioning suggestions
Bloat analysis and VACUUM recommendations
Query optimization suggestions
License
ISC
Contributing
Contributions welcome! Areas of focus:
Additional tools and features
Performance optimizations
Better error messages
Documentation improvements
Test coverage
Support
Issues: GitHub Issues
Repository: GitHub