This MCP server provides comprehensive AI-powered PostgreSQL performance tuning through query analysis, index optimization, and database health monitoring.
Query Performance Analysis
Identify slow queries using pg_stat_statements with filtering by execution time, call frequency, and sorting options
Analyze execution plans with EXPLAIN ANALYZE showing actual vs estimated rows, timing, buffer usage, and I/O statistics
Monitor active queries, connection states, blocked queries, idle transactions, and wait events to identify bottlenecks
Index Optimization
Generate AI-powered index recommendations based on query workload patterns, frequency, and performance impact
Test hypothetical indexes using HypoPG extension without creating real indexes, comparing execution plans and estimating improvements
Identify unused, duplicate, or overlapping indexes that waste storage and slow write operations
Manage hypothetical indexes (create, list, drop, estimate size)
Database Health Monitoring
Comprehensive health checks covering connections, cache hit rates, locks, replication lag, transaction ID wraparound risk, and disk space
Detailed table statistics including size, row counts, dead tuple ratios, vacuum/analyze times, and scan frequencies
Configuration review for memory, checkpoints, WAL, autovacuum, and connections with best practice recommendations
Deployment Modes
Standard MCP mode (stdio-based) for MCP clients like Claude Desktop
Streamable HTTP mode with stateful/stateless session support
SSE mode for web applications
Docker support for all modes
Provides AI-powered PostgreSQL performance tuning capabilities including query analysis, index recommendations with HypoPG support, execution plan analysis, and database health monitoring for connections, vacuum operations, replication lag, and buffer cache performance.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@PostgreSQL-Performance-Tuner-Mcpanalyze slow queries from the last hour and recommend indexes"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
PostgreSQL Performance Tuning MCP
A Model Context Protocol (MCP) server that provides AI-powered PostgreSQL performance tuning capabilities. This server helps identify slow queries, recommend optimal indexes, analyze execution plans, and leverage HypoPG for hypothetical index testing.
Features
Query Analysis
Retrieve slow queries from
pg_stat_statementswith detailed statisticsAnalyze query execution plans with
EXPLAINandEXPLAIN ANALYZEIdentify performance bottlenecks with automated plan analysis
Monitor active queries and detect long-running transactions
Index Tuning
AI-powered index recommendations based on query workload analysis
Hypothetical index testing with HypoPG extension (no disk usage)
Find unused and duplicate indexes for cleanup
Estimate index sizes before creation
Test query plans with proposed indexes before implementing
Database Health
Comprehensive health scoring with multiple checks
Connection utilization monitoring
Cache hit ratio analysis (buffer and index)
Lock contention detection
Vacuum health and transaction ID wraparound monitoring
Replication lag monitoring
Background writer and checkpoint analysis
Vacuum Monitoring
Track long-running VACUUM and VACUUM FULL operations in real-time
Monitor autovacuum progress and performance
Identify tables that need vacuuming
View recent vacuum activity history
Analyze autovacuum configuration effectiveness
I/O Performance Analysis
Analyze disk read/write patterns across tables and indexes
Identify I/O bottlenecks and hot tables
Monitor buffer cache hit ratios
Track temporary file usage indicating work_mem issues
Analyze checkpoint and background writer I/O
PostgreSQL 16+ enhanced pg_stat_io metrics support
Configuration Analysis
Review PostgreSQL settings by category
Get recommendations for memory, checkpoint, WAL, autovacuum, and connection settings
Identify suboptimal configurations
MCP Prompts & Resources
Pre-defined prompt templates for common tuning workflows
Dynamic resources for table stats, index info, and health checks
Comprehensive documentation resources
Installation
Standard Installation (for MCP clients like Claude Desktop)
Or using uv:
Manual Installation
Configuration
Environment Variables
Variable | Description | Required |
| PostgreSQL connection string | Yes |
| Comma-separated list of user IDs (OIDs) to exclude from monitoring | No |
Connection String Format: postgresql://user:password@host:port/database
Minimal User Permissions
To run this MCP server, the PostgreSQL user requires specific permissions to query system catalogs and extensions. Below are the minimal permissions needed for different feature sets.
Basic Permissions (Required for Core Functionality)
Extension-Specific Permissions
For pgstattuple (Bloat Detection):
For HypoPG (Hypothetical Index Testing):
Complete Setup Script
Excluding Specific Users from Monitoring
You can exclude specific PostgreSQL users from being included in query analysis and monitoring results. This is useful for filtering out:
Monitoring or replication users
System accounts
Internal application service accounts
Set the PGTUNER_EXCLUDE_USERIDS environment variable with a comma-separated list of user OIDs:
To find the OID for a specific PostgreSQL user:
When configured, the following queries are filtered:
pg_stat_activityqueries (filters onusesysidcolumn)pg_stat_statementsqueries (filters onuseridcolumn)
This affects tools like get_slow_queries, get_active_queries, analyze_wait_events, check_database_health, and get_index_recommendations.
MCP Client Configuration
Add to your cline_mcp_settings.json or Claude Desktop config:
Or Streamable HTTP Mode
Server Modes
1. Standard MCP Mode (Default)
2. HTTP SSE Mode (Legacy Web Applications)
The SSE (Server-Sent Events) mode provides a web-based transport for MCP communication. It's useful for web applications and clients that need HTTP-based communication.
SSE Endpoints:
Endpoint | Method | Description |
| GET | SSE connection endpoint - clients connect here to receive server events |
| POST | Send messages/requests to the server |
MCP Client Configuration for SSE:
For MCP clients that support SSE transport (like Claude Desktop or custom clients):
3. Streamable HTTP Mode (Modern MCP Protocol - Recommended)
The streamable-http mode implements the modern MCP Streamable HTTP protocol with a single /mcp endpoint. It supports both stateful (session-based) and stateless modes.
Stateful vs Stateless:
Stateful (default): Maintains session state across requests using
mcp-session-idheader. Ideal for long-running interactions.Stateless: Creates a fresh transport for each request with no session tracking. Ideal for serverless deployments or simple request/response patterns.
Endpoint: http://{host}:{port}/mcp
Available Tools
Note: All tools focus exclusively on user/application tables and indexes. System catalog tables (
pg_catalog,information_schema,pg_toast) are automatically excluded from all analyses.
Performance Analysis Tools
Tool | Description |
| Retrieve slow queries from pg_stat_statements with detailed stats (total time, mean time, calls, cache hit ratio). Excludes system catalog queries. |
| Analyze a query's execution plan with EXPLAIN ANALYZE, including automated issue detection |
| Get detailed table statistics including size, row counts, dead tuples, and access patterns |
| Analyze disk I/O read/write patterns, identify hot tables, buffer cache efficiency, and I/O bottlenecks. Supports filtering by analysis type (all, buffer_pool, tables, indexes, temp_files, checkpoints). |
Index Tuning Tools
Tool | Description |
| AI-powered index recommendations based on query workload analysis |
| Run EXPLAIN with hypothetical indexes to test improvements without creating real indexes |
| Create, list, drop, or reset HypoPG hypothetical indexes. Supports hide/unhide existing indexes. |
| Find unused and duplicate indexes that can be safely dropped |
Database Health Tools
Tool | Description |
| Comprehensive health check with scoring (connections, cache, locks, replication, wraparound, disk, checkpoints) |
| Monitor active queries, find long-running transactions and blocked queries. By default excludes system processes. |
| Analyze wait events to identify I/O, lock, or CPU bottlenecks. Focuses on client backend processes. |
| Review PostgreSQL settings by category with optimization recommendations |
Bloat Detection Tools (pgstattuple)
Tool | Description |
| Analyze table bloat using pgstattuple extension. Shows dead tuple counts, free space, and wasted space percentage. |
| Analyze B-tree index bloat using pgstatindex. Shows leaf density, fragmentation, and empty/deleted pages. Also supports GIN and Hash indexes. |
| Get a comprehensive overview of database bloat with top bloated tables/indexes, total reclaimable space, and priority maintenance actions. |
Vacuum Monitoring Tools
Tool | Description |
| Track manual VACUUM, VACUUM FULL, and autovacuum operations. Monitor progress percentage, dead tuples collected, index vacuum rounds, and estimated time remaining. Includes autovacuum configuration review and tables needing maintenance. |
Tool Parameters
get_slow_queries
limit: Maximum queries to return (default: 10)min_calls: Minimum call count filter (default: 1)min_mean_time_ms: Minimum mean (average) execution time in milliseconds filterorder_by: Sort bymean_time,calls, orrows
analyze_query
query(required): SQL query to analyzeanalyze: Execute query with EXPLAIN ANALYZE (default: true)buffers: Include buffer statistics (default: true)format: Output format -json,text,yaml,xml
get_index_recommendations
workload_queries: Optional list of specific queries to analyzemax_recommendations: Maximum recommendations (default: 10)min_improvement_percent: Minimum improvement threshold (default: 10%)include_hypothetical_testing: Test with HypoPG (default: true)target_tables: Focus on specific tables
check_database_health
include_recommendations: Include actionable recommendations (default: true)verbose: Include detailed statistics (default: false)
analyze_table_bloat
table_name: Name of a specific table to analyze (optional)schema_name: Schema name (default:public)use_approx: Usepgstattuple_approxfor faster analysis on large tables (default: false)min_table_size_gb: Minimum table size in GB to include in schema-wide scan (default: 5)include_toast: Include TOAST table analysis (default: false)
analyze_index_bloat
index_name: Name of a specific index to analyze (optional)table_name: Analyze all indexes on this table (optional)schema_name: Schema name (default:public)min_index_size_gb: Minimum index size in GB to include (default: 5)min_bloat_percent: Only show indexes with bloat above this percentage (default: 20)
get_bloat_summary
schema_name: Schema to analyze (default:public)top_n: Number of top bloated objects to show (default: 10)min_size_gb: Minimum object size in GB to include (default: 5)
monitor_vacuum_progress
action: Action to perform -progress(monitor active vacuum operations),needs_vacuum(find tables needing vacuum),autovacuum_status(review autovacuum configuration), orrecent_activity(view recent vacuum history)schema_name: Schema to analyze (default:public, used withneeds_vacuumaction)top_n: Number of results to return (default: 20)
analyze_disk_io_patterns
analysis_type: Type of I/O analysis -all(comprehensive),buffer_pool(cache hit ratios),tables(table I/O patterns),indexes(index I/O patterns),temp_files(temporary file usage), orcheckpoints(checkpoint I/O statistics)schema_name: Schema to analyze (default:public)top_n: Number of top I/O-intensive objects to show (default: 20)min_size_gb: Minimum object size in GB to include (default: 1)
MCP Prompts
The server includes pre-defined prompt templates for guided tuning sessions:
Prompt | Description |
| Systematic slow query investigation workflow |
| Comprehensive index analysis and cleanup |
| Full database health assessment |
| Optimize a specific SQL query |
| Generate a baseline report for comparison |
MCP Resources
Static Resources
pgtuner://docs/tools- Complete tool documentationpgtuner://docs/workflows- Common tuning workflows guidepgtuner://docs/prompts- Prompt template documentation
Dynamic Resource Templates
pgtuner://table/{schema}/{table_name}/stats- Table statisticspgtuner://table/{schema}/{table_name}/indexes- Table index informationpgtuner://query/{query_hash}/stats- Query performance statisticspgtuner://settings/{category}- PostgreSQL settings (memory, checkpoint, wal, autovacuum, connections, all)pgtuner://health/{check_type}- Health checks (connections, cache, locks, replication, bloat, all)
PostgreSQL Extension Setup
HypoPG Extension
HypoPG enables testing indexes without actually creating them. This is extremely useful for:
Testing if a proposed index would be used by the query planner
Comparing execution plans with different index strategies
Estimating storage requirements before committing
Enable HypoPG in Database
HypoPG enables testing hypothetical indexes without creating them on disk.
pg_stat_statements Extension
The pg_stat_statements extension is required for query performance analysis. It tracks planning and execution statistics for all SQL statements executed by a server.
Step 1: Enable the Extension in postgresql.conf
Add the following to your postgresql.conf file:
Note: After modifying
shared_preload_libraries, a PostgreSQL server restart is required.
Step 2: Create the Extension in Your Database
pgstattuple Extension
The pgstattuple extension is required for bloat detection tools (analyze_table_bloat, analyze_index_bloat, get_bloat_summary). It provides functions to get tuple-level statistics for tables and indexes.
Performance Impact Considerations
Setting | Overhead | Recommendation |
| Low (~1-2%) | Always enable |
| Low-Medium (~2-5%) | Enable in production, test first |
| Low | Enable for function-heavy workloads |
| Medium | Enable only when investigating planning issues |
| Low | Recommended for slow query identification |
Tip: Use
pg_test_timingto measure the timing overhead on your specific system before enablingtrack_io_timing.
Example Usage
Find and Analyze Slow Queries
Get Index Recommendations
Database Health Check
Find Unused Indexes
Docker
Requirements
Python: 3.10+
PostgreSQL: 12+ (recommended: 14+)
Extensions:
pg_stat_statements(required for query analysis)hypopg(optional, for hypothetical index testing)
Dependencies
Core dependencies:
mcp[cli]>=1.12.0- Model Context Protocol SDKpsycopg[binary,pool]>=3.1.0- PostgreSQL adapter with connection poolingpglast>=7.10- PostgreSQL query parser
Optional (for HTTP modes):
starlette>=0.27.0- ASGI frameworkuvicorn>=0.23.0- ASGI server
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.