|
| 1 | +# PostgreSQL MCP Server |
| 2 | + |
| 3 | +A comprehensive Model Context Protocol (MCP) server for PostgreSQL database integration. This server provides extensive tools, resources, and prompts for complete PostgreSQL database management through AI assistants like Claude. |
| 4 | + |
| 5 | +## Features |
| 6 | + |
| 7 | +This server offers over 200 specialized PostgreSQL tools covering all aspects of database administration, monitoring, and optimization. |
| 8 | + |
| 9 | +### 🔧 Core Database Operations |
| 10 | +- **Database Management**: Create, list, and manage databases |
| 11 | +- **Schema Operations**: Create, drop, and manage schemas |
| 12 | +- **Table Operations**: List, describe, analyze tables with detailed statistics |
| 13 | +- **Query Execution**: Safe SELECT queries and controlled UPDATE/INSERT/DELETE operations |
| 14 | +- **Index Management**: Create, drop, analyze index usage and effectiveness |
| 15 | + |
| 16 | +### 📊 Advanced Analytics & Monitoring |
| 17 | +- **Performance Analysis**: Query performance, slow query analysis, execution plan examination |
| 18 | +- **Resource Monitoring**: Buffer cache analysis, memory usage, I/O statistics |
| 19 | +- **Lock Analysis**: Deadlock detection, lock contention monitoring, blocking queries |
| 20 | +- **Replication Monitoring**: Replication status, lag analysis, slot management |
| 21 | +- **Vacuum & Maintenance**: Autovacuum monitoring, table bloat analysis, maintenance recommendations |
| 22 | + |
| 23 | +### 🛡️ Security & Administration |
| 24 | +- **User Management**: Create, drop, manage users and roles with detailed permissions |
| 25 | +- **Privilege Management**: Grant/revoke permissions, security auditing |
| 26 | +- **Connection Management**: Monitor active connections, analyze connection patterns |
| 27 | +- **Backup Analysis**: Backup status monitoring and recovery readiness assessment |
| 28 | + |
| 29 | +### 🚀 Performance Optimization |
| 30 | +- **Index Optimization**: Unused index detection, redundancy analysis, effectiveness metrics |
| 31 | +- **Query Optimization**: Plan cache analysis, query complexity assessment |
| 32 | +- **Buffer Pool Tuning**: Hit ratio analysis, cache efficiency metrics |
| 33 | +- **Configuration Tuning**: Parameter recommendations and system health checks |
| 34 | + |
| 35 | +### 📈 Advanced Diagnostics |
| 36 | +- **Transaction Analysis**: Long-running transactions, wraparound monitoring |
| 37 | +- **Checkpoint Monitoring**: Checkpoint efficiency and timing analysis |
| 38 | +- **WAL Analysis**: Write-ahead log generation and archiving status |
| 39 | +- **Extension Management**: Installed extensions and usage analysis |
| 40 | + |
| 41 | +### 📊 Resources |
| 42 | +- **postgres://tables/{schema}**: Get table information for a schema |
| 43 | +- **postgres://table/{schema}/{table_name}**: Get detailed table structure |
| 44 | + |
| 45 | +### 💬 Prompts |
| 46 | +- **analyze_table**: Generate analysis prompts for database tables |
| 47 | +- **query_builder**: Help build SQL queries with proper guidance |
| 48 | + |
| 49 | +## Installation |
| 50 | + |
| 51 | +1. Create a virtual environment (recommended): |
| 52 | +```bash |
| 53 | +# Create virtual environment |
| 54 | +python -m venv venv |
| 55 | + |
| 56 | +# Activate virtual environment |
| 57 | +# On Windows: |
| 58 | +venv\Scripts\activate |
| 59 | +# On macOS/Linux: |
| 60 | +source venv/bin/activate |
| 61 | +``` |
| 62 | + |
| 63 | +2. Install dependencies: |
| 64 | +```bash |
| 65 | +pip install -r requirements.txt |
| 66 | +``` |
| 67 | + |
| 68 | +3. Set up your database connection: |
| 69 | +```bash |
| 70 | +# Copy the example environment file |
| 71 | +copy .env.example .env |
| 72 | + |
| 73 | +# Edit .env with your PostgreSQL connection details |
| 74 | +DATABASE_URL=postgresql://username:password@localhost:5432/database_name |
| 75 | +``` |
| 76 | + |
| 77 | +## Usage |
| 78 | + |
| 79 | +### Running the Server |
| 80 | + |
| 81 | +#### Direct execution: |
| 82 | +```bash |
| 83 | +python postgres_server.py |
| 84 | +``` |
| 85 | + |
| 86 | +#### With MCP development tools (if mcp CLI is installed): |
| 87 | +```bash |
| 88 | +mcp dev postgres_server.py |
| 89 | +``` |
| 90 | + |
| 91 | +### Configuration with Claude Desktop |
| 92 | + |
| 93 | +Add the following to your Claude Desktop configuration file (`claude_desktop_config.json`): |
| 94 | + |
| 95 | +**Windows:** |
| 96 | +```json |
| 97 | +{ |
| 98 | + "mcpServers": { |
| 99 | + "postgres": { |
| 100 | + "command": "python", |
| 101 | + "args": [ |
| 102 | + "postgres_server.py" |
| 103 | + ], |
| 104 | + "cwd": "C:\\path\\to\\postgres-mcp-server", |
| 105 | + "env": { |
| 106 | + "DATABASE_URL": "postgresql://username:password@localhost:5432/database_name" |
| 107 | + } |
| 108 | + } |
| 109 | + } |
| 110 | +} |
| 111 | +``` |
| 112 | + |
| 113 | +**macOS/Linux:** |
| 114 | +```json |
| 115 | +{ |
| 116 | + "mcpServers": { |
| 117 | + "postgres": { |
| 118 | + "command": "python", |
| 119 | + "args": [ |
| 120 | + "postgres_server.py" |
| 121 | + ], |
| 122 | + "cwd": "/absolute/path/to/postgres-mcp-server", |
| 123 | + "env": { |
| 124 | + "DATABASE_URL": "postgresql://username:password@localhost:5432/database_name" |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | +} |
| 129 | +``` |
| 130 | + |
| 131 | +## Tool Categories |
| 132 | + |
| 133 | +### Database Structure & Metadata |
| 134 | +- `PostgreSQL_list_tables` - List all tables in a schema |
| 135 | +- `PostgreSQL_describe_table` - Get detailed table column information |
| 136 | +- `PostgreSQL_list_schemas` - List all database schemas |
| 137 | +- `PostgreSQL_list_indexes` - Show indexes for a table |
| 138 | +- `PostgreSQL_get_foreign_keys` - Display foreign key relationships |
| 139 | +- `PostgreSQL_get_table_constraints` - Show all table constraints |
| 140 | + |
| 141 | +### Query Execution & Analysis |
| 142 | +- `PostgreSQL_execute_select_query` - Execute SELECT queries safely |
| 143 | +- `PostgreSQL_execute_update_query` - Execute INSERT/UPDATE/DELETE queries |
| 144 | +- `PostgreSQL_explain_query` - Show query execution plans |
| 145 | +- `PostgreSQL_get_slow_queries` - Analyze slow running queries |
| 146 | +- `PostgreSQL_analyze_query_complexity` - Assess query performance characteristics |
| 147 | + |
| 148 | +### Performance Monitoring |
| 149 | +- `PostgreSQL_get_cache_hit_ratios` - Buffer cache performance metrics |
| 150 | +- `PostgreSQL_get_index_usage_stats` - Index utilization analysis |
| 151 | +- `PostgreSQL_get_table_statistics` - Comprehensive table statistics |
| 152 | +- `PostgreSQL_check_long_running_queries` - Monitor active long queries |
| 153 | +- `PostgreSQL_get_blocking_locks` - Identify blocking transactions |
| 154 | + |
| 155 | +### Maintenance & Optimization |
| 156 | +- `PostgreSQL_get_bloated_tables` - Find tables needing maintenance |
| 157 | +- `PostgreSQL_get_unused_indexes` - Identify unused indexes |
| 158 | +- `PostgreSQL_vacuum_analyze_table` - Perform table maintenance |
| 159 | +- `PostgreSQL_get_autovacuum_activity` - Monitor autovacuum operations |
| 160 | +- `PostgreSQL_analyze_database` - Update table statistics |
| 161 | + |
| 162 | +### Security & User Management |
| 163 | +- `PostgreSQL_create_user` - Create database users |
| 164 | +- `PostgreSQL_grant_privileges` - Assign user permissions |
| 165 | +- `PostgreSQL_get_active_connections` - Monitor user connections |
| 166 | +- `PostgreSQL_list_users_and_roles` - Display all users and roles |
| 167 | +- `PostgreSQL_get_table_permissions` - Show table-level permissions |
| 168 | + |
| 169 | +### Replication & Backup |
| 170 | +- `PostgreSQL_get_replication_status` - Monitor replication health |
| 171 | +- `PostgreSQL_get_replication_slots` - Manage replication slots |
| 172 | +- `PostgreSQL_get_backup_status` - Check backup configuration |
| 173 | +- `PostgreSQL_get_wal_stats` - Write-ahead log statistics |
| 174 | + |
| 175 | +## Example Interactions |
| 176 | + |
| 177 | +### Database Exploration |
| 178 | +``` |
| 179 | +"Show me all tables in the public schema" |
| 180 | +"What's the structure of the users table?" |
| 181 | +"List all foreign key relationships for the orders table" |
| 182 | +``` |
| 183 | + |
| 184 | +### Performance Analysis |
| 185 | +``` |
| 186 | +"Analyze the performance of my database and suggest optimizations" |
| 187 | +"Show me the slowest queries from the last hour" |
| 188 | +"Which indexes are not being used and can be dropped?" |
| 189 | +"What's the buffer cache hit ratio?" |
| 190 | +``` |
| 191 | + |
| 192 | +### Monitoring & Diagnostics |
| 193 | +``` |
| 194 | +"Are there any blocking queries right now?" |
| 195 | +"Show me tables with high bloat that need maintenance" |
| 196 | +"Check the replication lag status" |
| 197 | +"What connections are currently active?" |
| 198 | +``` |
| 199 | + |
| 200 | +### Maintenance Operations |
| 201 | +``` |
| 202 | +"Run VACUUM ANALYZE on the products table" |
| 203 | +"Update statistics for the entire database" |
| 204 | +"Show me autovacuum activity for today" |
| 205 | +``` |
| 206 | + |
| 207 | +### Security Auditing |
| 208 | +``` |
| 209 | +"Show me all users and their privileges" |
| 210 | +"What permissions does user 'app_user' have?" |
| 211 | +"List all active database connections" |
| 212 | +``` |
| 213 | + |
| 214 | +## Advanced Use Cases |
| 215 | + |
| 216 | +### Database Health Assessment |
| 217 | +The server can perform comprehensive health checks including: |
| 218 | +- Buffer pool efficiency analysis |
| 219 | +- Index usage optimization |
| 220 | +- Table bloat assessment |
| 221 | +- Replication lag monitoring |
| 222 | +- Connection pool analysis |
| 223 | + |
| 224 | +### Performance Tuning |
| 225 | +- Identify slow queries and suggest optimizations |
| 226 | +- Analyze execution plans for query improvement |
| 227 | +- Monitor resource utilization patterns |
| 228 | +- Recommend index strategies |
| 229 | + |
| 230 | +### Proactive Monitoring |
| 231 | +- Set up monitoring for long-running transactions |
| 232 | +- Track database growth trends |
| 233 | +- Monitor backup and recovery readiness |
| 234 | +- Analyze connection patterns and bottlenecks |
| 235 | + |
| 236 | +## Security Features |
| 237 | + |
| 238 | +- **Query Validation**: Only allows specific query types (SELECT for reads, INSERT/UPDATE/DELETE for writes) |
| 239 | +- **Connection Pooling**: Efficient database connection management with proper cleanup |
| 240 | +- **Parameter Sanitization**: Prevents SQL injection through parameterized queries |
| 241 | +- **Error Handling**: Comprehensive error handling with informative messages |
| 242 | +- **Logging**: Contextual logging for monitoring and debugging |
| 243 | +- **Environment Variables**: Secure credential management |
| 244 | +- **Permission Checks**: Respects database user permissions and access controls |
0 commit comments