Postgres MCP Pro

repository·main·Indexed 25 days ago

https://github.com/crystaldba/postgres-mcp

An MCP server providing AI agents with advanced PostgreSQL capabilities, including index tuning, query plan analysis, database health monitoring, and safe SQL execution. It features deterministic tools for workload analysis and performance simulation using pg_stat_statements and hypopg, supporting PostgreSQL versions 15, 16, and 17. It offers restricted and unrestricted access modes to balance flexibility and safety in development and production environments.

Tokens
8.1K
Snippets
5
Records
61
Agent score
85%

What's inside postgres-mcp

  1. Compare Postgres MCP Pro with other MCP servers

    main

    Postgres MCP Pro distinguishes itself by providing deterministic tools and classical optimization algorithms rather than relying solely on LLM reasoning for database tuning.

    FeaturePostgres MCP ProOther Postgres MCP Servers
    Database health checks✅ Deterministic❌ Unrepeatable LLM-generated queries
    Indexing strategies✅ Principled search strategies❌ Gen-AI guesses
    Problem analysis✅ Workload analysis❌ Inconsistent analysis
    Performance simulation✅ Simulates improvements❌ Manual verification required
  2. Understand Index Tuning Workflow

    main

    The index tuning process in Postgres MCP Pro follows these stages:

    1. Identify SQL queries: Uses pg_stat_statements to find top resource consumers. Tools like analyze_query_workload (focuses on slow queries) or get_top_queries can be used to find candidates.
    2. Generate candidate indexes: Parses SQL to identify columns used in filters, joins, grouping, or sorting, including potential multicolumn indexes.
    3. Search for optimal configuration: Uses a greedy search strategy (finding the best single index, then the best second index, etc.) and estimates improvements using the hypopg extension.
    4. Cost-benefit analysis: Balances performance gains against storage costs. By default, it requires the log (base 10) of performance improvement to be at least 2x the difference in the log of the space cost (e.g., allowing a 10x increase in space for a 100x performance improvement).
  3. Use SSE Transport for Postgres MCP Pro

    main

    To allow multiple MCP clients to share one remote server, use the Server-Sent Events (SSE) transport by starting the server with the --transport=sse flag.

    1. Start the server (e.g., via Docker):

    docker run -p 8000:8000 \
      -e DATABASE_URI=postgresql://username:password@localhost:5432/dbname \
      crystaldba/postgres-mcp --access-mode=unrestricted --transport=sse

    2. Configure your client:

    For Cursor or Cline (mcp.json / cline_mcp_settings.json):

    {
        "mcpServers": {
            "postgres": {
                "type": "sse",
                "url": "http://localhost:8000/sse"
            }
        }
    }

    For Windsurf (mcp_config.json):

    {
        "mcpServers": {
            "postgres": {
                "type": "sse",
                "serverUrl": "http://localhost:8000/sse"
            }
        }
    }
  4. Use ExplainPlanTool to analyze PostgreSQL queries

    main

    The ExplainPlanTool is integrated into the PostgreSQL MCP server and allows you to generate various types of EXPLAIN plans to understand query execution, identify performance bottlenecks, and test hypothetical indexes.

    Access this functionality through the MCP API using the explain_query function.

  5. Install Postgres MCP Pro via Docker

    main

    Pull the official Docker image to run Postgres MCP Pro in a containerized environment. This method includes all necessary dependencies and is recommended to avoid Python environment issues.

    docker pull crystaldba/postgres-mcp
  6. Install Required Postgres Extensions

    main

    For advanced features like index tuning and performance analysis, you must enable pg_stat_statements and hypopg on your database.

    Cloud Managed Services (AWS RDS, Azure, Google Cloud SQL): Run the following SQL commands:

    CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
    CREATE EXTENSION IF NOT EXISTS hypopg;

    Self-managed Postgres:

    1. Ensure pg_stat_statements is listed in shared_preload_libraries in your postgresql.conf.
    2. Ensure hypopg is installed on the system via your package manager if it is not included with your Postgres distribution.
  7. Configure Postgres MCP Pro for Claude Desktop

    main

    To use Postgres MCP Pro with Claude Desktop, edit your claude_desktop_config.json file located at:

    • MacOS: ~/Library/Application Support/Claude/claude_desktop_config.json
    • Windows: %APPDATA%/Claude/claude_desktop_config.json

    Add the server configuration to the mcpServers section. You must provide a DATABASE_URI environment variable containing your Postgres connection string.

    {
      "mcpServers": {
        "postgres": {
          "command": "docker",
          "args": [
            "run",
            "-i",
            "--rm",
            "-e",
            "DATABASE_URI",
            "crystaldba/postgres-mcp",
            "--access-mode=unrestricted"
          ],
          "env": {
            "DATABASE_URI": "postgresql://username:password@localhost:5432/dbname"
          }
        }
      }
    }
  8. Enable Experimental Index Tuning by LLM

    main
    Postgres MCP Pro includes an experimental feature that uses an LLM to propose index configurations by analyzing the database schema and query plans, iteratively improving them using hypopg predictions. To use this feature, you must provide an OpenAI API key via the OPENAI_API_KEY environment variable.
  9. Set up Postgres MCP Pro for local development

    main

    If you are a developer working on the project or want to install from source, follow these steps to set up your local environment using uv:

    1. Install uv using the official installer.
    2. Clone the postgres-mcp repository.
    3. Install dependencies using uv pip install -e . and uv sync.
    4. Start the server by running uv run postgres-mcp followed by your PostgreSQL connection string.
  10. Install Postgres MCP Pro via Python (pipx or uv)

    main

    If you prefer running natively via Python, you can install the package using pipx or uv.

    Using pipx:

    pipx install postgres-mcp

    Using uv:

    uv pip install postgres-mcp
    pipx install postgres-mcp
    # OR
    uv pip install postgres-mcp
  11. Configure Postgres MCP Pro Access Modes

    main

    Postgres MCP Pro supports two access modes via the --access-mode flag to control what the AI agent can do:

    • unrestricted: Allows full read/write access to modify data and schema. Best for development.
    • restricted: Limits operations to read-only transactions and imposes resource utilization constraints (e.g., execution time). Best for production.
  12. Validate data distribution for business logic

    main

    When sorting or filtering data (e.g., 'top-rated' lists) produces unexpected or 'random' results, use the AI agent to analyze the underlying data distribution.

    Instead of guessing thresholds (like a minimum number of votes), ask the agent to:

    1. Check data presence: Verify if the tables used for sorting actually contain data.
    2. Analyze distribution: Get the distribution of values (e.g., num_votes) to determine a statistically sound threshold (e.g., setting a 10K vote minimum) that prevents low-quality data from skewing results.