
PostgreSQL performance Tuner MCP Server
io.github.isdanielPublished by GitHub account isdanielv0.5.2Updated Oct 25, 2026
provides AI-powered PostgreSQL performance tuning capabilities.
Overview
A local MCP server that lets an assistant inspect a PostgreSQL database and recommend performance tuning: slow queries, indexes, health and vacuum.
- What you can do
- Retrieve and analyze slow queries and execution plans, and monitor active queries and wait events from pg_stat_statements and pg_stat_activity, with optional user exclusion filters. Recommend indexes, test hypothetical indexes with HypoPG, and find unused or duplicate indexes. Check database health, settings, disk I/O patterns, and table and index bloat. Monitor vacuum and autovacuum progress and recent activity. Use built-in prompt templates and resources for table stats, index info, settings and health checks.
- When to use it
- Useful when you administer or tune a PostgreSQL database and want an assistant to investigate slow queries, evaluate index changes without creating real indexes, or produce health and maintenance reports. Best for read-oriented diagnostics on a database where pg_stat_statements is enabled.
- Requirements
- Runs locally as a Python package (Python 3.10+) over stdio, or optionally as an HTTP/SSE server. Needs a PostgreSQL 12+ connection string in the DATABASE_URI environment variable and a database user with read access to system statistics; pg_stat_statements is required for query analysis, and hypopg and pgstattuple are optional extensions. Network access to the database is needed.
Installation
In SourceWeft
- Open PostgreSQL performance Tuner MCP Server in the dashboard and add it to a workspace.
- Enable the server for the chats that should use its tools.
Desktop only via STDIO. STDIO servers start a local process, so they need the SourceWeft desktop host.
Other MCP clients
Follow the launch instructions in the repository.
README
PostgreSQL Performance Tuning MCP
[PyPI - Version] [PyPI - Downloads] [Python 3.10+] [Pepy Total Downloads] [Docker Pulls]
[Image]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 statistics - Analyze query execution plans with
EXPLAINandEXPLAIN ANALYZE - Identify 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
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
Security Hardening
pgtuner_mcp HTTP modes (sse, streamable-http) do not include authentication. They are safe for local-only use; for any networked deployment you MUST front them with a reverse proxy that handles auth and TLS.
Connection-level safeguards (built in)
Every connection started by the pool receives session-level guards via libpq options at handshake time:
Belt-and-braces — also pin on the monitoring role:
CORS
Recommended reverse-proxy template (Caddy)
What is NOT included
- No Bearer-token / API-key auth (operator concern — see reverse proxy)
- No rate limiting (operator concern)
- No in-process TLS (use the reverse proxy)
- No per-client tool allowlist
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:
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
Index Tuning Tools
Database Health Tools
Bloat Detection Tools (pgstattuple)
Vacuum Monitoring Tools
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:
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
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
Integration Testing
Integration tests exercise every MCP tool against a live PostgreSQL via Docker.
Quickstart
Supported PG versions: 14, 15, 16, 17 (e.g., make up PG=17).
CI runs the suite on every PR across all four PG versions via .github/workflows/integration.yml.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Source: README.md at commit 2eaa0cc
Tools
0Version history
1- v0.5.2LatestSep 16, 2026
Score
50% of the applicable checks met
How complete this listing is, computed from the registry entry, the endpoint and public sources. Not a rating of the server and not a statement that it is safe or working today: reachability is a dated check, and no installs or reviews go into the score.
- Reached in the last 30 days25 pts
Keep the endpoint answering the MCP handshake; SourceWeft probes it every 30 days.
- Auth declared10 pts
Declare the credential headers in the registry entry, or keep the endpoint answering the probe so its auth can be classified.
- Tools listed15 pts
Answer tools/list without a credential, or ship a package that starts in a sandbox without one.
- DescriptionRequired15 pts
- Logo10 pts
- Documentation15 pts
- License10 pts