[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-72407":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":17,"stars7d":18,"stars30d":19,"stars90d":16,"forks30d":16,"starsTrendScore":20,"compositeScore":21,"rankGlobal":10,"rankLanguage":10,"license":22,"archived":23,"fork":23,"defaultBranch":24,"hasWiki":25,"hasPages":23,"topics":26,"createdAt":10,"pushedAt":10,"updatedAt":27,"readmeContent":28,"aiSummary":29,"trendingCount":16,"starSnapshotCount":16,"syncStatus":30,"lastSyncTime":31,"discoverSource":32},72407,"postgres-mcp","crystaldba\u002Fpostgres-mcp","crystaldba","Postgres MCP Pro provides configurable read\u002Fwrite access and performance analysis for you and your AI agents.","",null,"Python",2876,319,11,35,0,17,46,147,51,29.52,"MIT License",false,"main",true,[],"2026-06-12 02:03:02","\u003Cdiv align=\"center\">\n\n\u003Cimg src=\"assets\u002Fpostgres-mcp-pro.png\" alt=\"Postgres MCP Pro Logo\" width=\"600\"\u002F>\n\n[![License: MIT](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLicense-MIT-blue.svg)](https:\u002F\u002Fopensource.org\u002Flicenses\u002FMIT)\n[![PyPI - Version](https:\u002F\u002Fimg.shields.io\u002Fpypi\u002Fv\u002Fpostgres-mcp)](https:\u002F\u002Fpypi.org\u002Fproject\u002Fpostgres-mcp\u002F)\n[![Discord](https:\u002F\u002Fimg.shields.io\u002Fdiscord\u002F1336769798603931789?label=Discord)](https:\u002F\u002Fdiscord.gg\u002F4BEHC7ZM)\n[![Twitter Follow](https:\u002F\u002Fimg.shields.io\u002Ftwitter\u002Ffollow\u002Fauto_dba?style=flat)](https:\u002F\u002Fx.com\u002Fauto_dba)\n[![Contributors](https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Fcontributors\u002Fcrystaldba\u002Fpostgres-mcp)](https:\u002F\u002Fgithub.com\u002Fcrystaldba\u002Fpostgres-mcp\u002Fgraphs\u002Fcontributors)\n\n\u003Ch3>A Postgres MCP server with index tuning, explain plans, health checks, and safe sql execution.\u003C\u002Fh3>\n\n\u003Cdiv class=\"toc\">\n  \u003Ca href=\"#overview\">Overview\u003C\u002Fa> •\n  \u003Ca href=\"#demo\">Demo\u003C\u002Fa> •\n  \u003Ca href=\"#quick-start\">Quick Start\u003C\u002Fa> •\n  \u003Ca href=\"#technical-notes\">Technical Notes\u003C\u002Fa> •\n  \u003Ca href=\"#mcp-server-api\">MCP API\u003C\u002Fa> •\n  \u003Ca href=\"#related-projects\">Related Projects\u003C\u002Fa> •\n  \u003Ca href=\"#frequently-asked-questions\">FAQ\u003C\u002Fa>\n\u003C\u002Fdiv>\n\n\u003C\u002Fdiv>\n\n## Overview\n\n**Postgres MCP Pro** is an open source Model Context Protocol (MCP) server built to support you and your AI agents throughout the **entire development process**—from initial coding, through testing and deployment, and to production tuning and maintenance.\n\nPostgres MCP Pro does much more than wrap a database connection.\n\nFeatures include:\n\n- **🔍 Database Health** - analyze index health, connection utilization, buffer cache, vacuum health, sequence limits, replication lag, and more.\n- **⚡ Index Tuning** - explore thousands of possible indexes to find the best solution for your workload, using industrial-strength algorithms.\n- **📈 Query Plans** - validate and optimize performance by reviewing EXPLAIN plans and simulating the impact of hypothetical indexes.\n- **🧠 Schema Intelligence** - context-aware SQL generation based on detailed understanding of the database schema.\n- **🛡️ Safe SQL Execution** - configurable access control, including support for read-only mode and safe SQL parsing, making it usable for both development and production.\n\nPostgres MCP Pro supports both the [Standard Input\u002FOutput (stdio)](https:\u002F\u002Fmodelcontextprotocol.io\u002Fdocs\u002Fconcepts\u002Ftransports#standard-input%2Foutput-stdio) and [Server-Sent Events (SSE)](https:\u002F\u002Fmodelcontextprotocol.io\u002Fdocs\u002Fconcepts\u002Ftransports#server-sent-events-sse) transports, for flexibility in different environments.\n\nFor additional background on why we built Postgres MCP Pro, see [our launch blog post](https:\u002F\u002Fwww.crystaldba.ai\u002Fblog\u002Fpost\u002Fannouncing-postgres-mcp-server-pro).\n\n## Demo\n\n*From Unusable to Lightning Fast*\n- **Challenge:** We generated a movie app using an AI assistant, but the SQLAlchemy ORM code ran painfully slow.\n- **Solution:** Using Postgres MCP Pro with Cursor, we fixed the performance issues in minutes.\n\nWhat we did:\n- 🚀 Fixed performance - including ORM queries, indexing, and caching\n- 🛠️ Fixed a broken page - by prompting the agent to explore the data, fix queries, and add related content.\n- 🧠 Improved the top movies - by exploring the data and fixing the ORM query to surface more relevant results.\n\nSee the video below or read the [play-by-play](examples\u002Fmovie-app.md).\n\nhttps:\u002F\u002Fgithub.com\u002Fuser-attachments\u002Fassets\u002F24e05745-65e9-4998-b877-a368f1eadc13\n\n\n\n\n## Quick Start\n\n### Prerequisites\n\nBefore getting started, ensure you have:\n1. Access credentials for your database.\n2. Docker *or* Python 3.12 or higher.\n\n#### Access Credentials\n You can confirm your access credentials are valid by using `psql` or a GUI tool such as [pgAdmin](https:\u002F\u002Fwww.pgadmin.org\u002F).\n\n\n#### Docker or Python\n\nThe choice to use Docker or Python is yours.\nWe generally recommend Docker because Python users can encounter more environment-specific issues.\nHowever, it often makes sense to use whichever method you are most familiar with.\n\n\n### Installation\n\nChoose one of the following methods to install Postgres MCP Pro:\n\n#### Option 1: Using Docker\n\nPull the Postgres MCP Pro MCP server Docker image.\nThis image contains all necessary dependencies, providing a reliable way to run Postgres MCP Pro in a variety of environments.\n\n```bash\ndocker pull crystaldba\u002Fpostgres-mcp\n```\n\n\n#### Option 2: Using Python\n\nIf you have `pipx` installed you can install Postgres MCP Pro with:\n\n```bash\npipx install postgres-mcp\n```\n\nOtherwise, install Postgres MCP Pro with `uv`:\n\n```bash\nuv pip install postgres-mcp\n```\n\nIf you need to install `uv`, see the [uv installation instructions](https:\u002F\u002Fdocs.astral.sh\u002Fuv\u002Fgetting-started\u002Finstallation\u002F).\n\n\n### Configure Your AI Assistant\n\nWe provide full instructions for configuring Postgres MCP Pro with Claude Desktop.\nMany MCP clients have similar configuration files, you can adapt these steps to work with the client of your choice.\n\n#### Claude Desktop Configuration\n\nYou will need to edit the Claude Desktop configuration file to add Postgres MCP Pro.\nThe location of this file depends on your operating system:\n- MacOS: `~\u002FLibrary\u002FApplication Support\u002FClaude\u002Fclaude_desktop_config.json`\n- Windows: `%APPDATA%\u002FClaude\u002Fclaude_desktop_config.json`\n\nYou can also use `Settings` menu item in Claude Desktop to locate the configuration file.\n\nYou will now edit the `mcpServers` section of the configuration file.\n\n##### If you are using Docker\n\n```json\n{\n  \"mcpServers\": {\n    \"postgres\": {\n      \"command\": \"docker\",\n      \"args\": [\n        \"run\",\n        \"-i\",\n        \"--rm\",\n        \"-e\",\n        \"DATABASE_URI\",\n        \"crystaldba\u002Fpostgres-mcp\",\n        \"--access-mode=unrestricted\"\n      ],\n      \"env\": {\n        \"DATABASE_URI\": \"postgresql:\u002F\u002Fusername:password@localhost:5432\u002Fdbname\"\n      }\n    }\n  }\n}\n```\n\nThe Postgres MCP Pro Docker image will automatically remap the hostname `localhost` to work from inside of the container.\n\n- MacOS\u002FWindows: Uses `host.docker.internal` automatically\n- Linux: Uses `172.17.0.1` or the appropriate host address automatically\n\n##### If you are using `uvx`\n\n```json\n{\n  \"mcpServers\": {\n    \"postgres\": {\n      \"command\": \"uvx\",\n      \"args\": [\n        \"postgres-mcp\",\n        \"--access-mode=unrestricted\"\n      ],\n      \"env\": {\n        \"DATABASE_URI\": \"postgresql:\u002F\u002Fusername:password@localhost:5432\u002Fdbname\"\n      }\n    }\n  }\n}\n```\n\n\n##### If you are using `pipx`\n\n```json\n{\n  \"mcpServers\": {\n    \"postgres\": {\n      \"command\": \"postgres-mcp\",\n      \"args\": [\n        \"--access-mode=unrestricted\"\n      ],\n      \"env\": {\n        \"DATABASE_URI\": \"postgresql:\u002F\u002Fusername:password@localhost:5432\u002Fdbname\"\n      }\n    }\n  }\n}\n```\n\n\n##### If you are using `uv`\n\n```json\n{\n  \"mcpServers\": {\n    \"postgres\": {\n      \"command\": \"uv\",\n      \"args\": [\n        \"run\",\n        \"postgres-mcp\",\n        \"--access-mode=unrestricted\"\n      ],\n      \"env\": {\n        \"DATABASE_URI\": \"postgresql:\u002F\u002Fusername:password@localhost:5432\u002Fdbname\"\n      }\n    }\n  }\n}\n```\n\n\n##### Connection URI\n\nReplace `postgresql:\u002F\u002F...` with your [Postgres database connection URI](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Flibpq-connect.html#LIBPQ-CONNSTRING-URIS).\n\n\n##### Access Mode\n\nPostgres MCP Pro supports multiple *access modes* to give you control over the operations that the AI agent can perform on the database:\n- **Unrestricted Mode**: Allows full read\u002Fwrite access to modify data and schema. It is suitable for development environments.\n- **Restricted Mode**: Limits operations to read-only transactions and imposes constraints on resource utilization (presently only execution time). It is suitable for production environments.\n\nTo use restricted mode, replace `--access-mode=unrestricted` with `--access-mode=restricted` in the configuration examples above.\n\n\n#### Other MCP Clients\n\nMany MCP clients have similar configuration files to Claude Desktop, and you can adapt the examples above to work with the client of your choice.\n\n- If you are using Cursor, you can use navigate from the `Command Palette` to `Cursor Settings`, then open the `MCP` tab to access the configuration file.\n- If you are using Windsurf, you can navigate to from the `Command Palette` to `Open Windsurf Settings Page` to access the configuration file.\n- If you are using Goose run `goose configure`, then select `Add Extension`.\n- If you are using Qodo Gen, open the Chat panel, click `Connect more tools`, click `+ Add new MCP`, then add the new configuration.\n\n## SSE Transport\n\nPostgres MCP Pro supports the [SSE transport](https:\u002F\u002Fmodelcontextprotocol.io\u002Fdocs\u002Fconcepts\u002Ftransports#server-sent-events-sse), which allows multiple MCP clients to share one server, possibly a remote server.\nTo use the SSE transport, you need to start the server with the `--transport=sse` option.\n\nFor example, with Docker run:\n\n```bash\ndocker run -p 8000:8000 \\\n  -e DATABASE_URI=postgresql:\u002F\u002Fusername:password@localhost:5432\u002Fdbname \\\n  crystaldba\u002Fpostgres-mcp --access-mode=unrestricted --transport=sse\n```\n\nThen update your MCP client configuration to call the the MCP server.\nFor example, in Cursor's `mcp.json` or Cline's `cline_mcp_settings.json` you can put:\n\n```json\n{\n    \"mcpServers\": {\n        \"postgres\": {\n            \"type\": \"sse\",\n            \"url\": \"http:\u002F\u002Flocalhost:8000\u002Fsse\"\n        }\n    }\n}\n```\n\nFor Windsurf, the format in `mcp_config.json` is slightly different:\n\n```json\n{\n    \"mcpServers\": {\n        \"postgres\": {\n            \"type\": \"sse\",\n            \"serverUrl\": \"http:\u002F\u002Flocalhost:8000\u002Fsse\"\n        }\n    }\n}\n```\n\n## Postgres Extension Installation (Optional)\n\nTo enable index tuning and comprehensive performance analysis you need to load the `pg_stat_statements` and `hypopg` extensions on your database.\n\n- The `pg_stat_statements` extension allows Postgres MCP Pro to analyze query execution statistics.\nFor example, this allows it to understand which queries are running slow or consuming significant resources.\n- The `hypopg` extension allows Postgres MCP Pro to simulate the behavior of the Postgres query planner after adding indexes.\n\n### Installing extensions on AWS RDS, Azure SQL, or Google Cloud SQL\n\nIf your Postgres database is running on a cloud provider managed service, the `pg_stat_statements` and `hypopg` extensions should already be available on the system.\nIn this case, you can just run `CREATE EXTENSION` commands using a role with sufficient privileges:\n\n```sql\nCREATE EXTENSION IF NOT EXISTS pg_stat_statements;\nCREATE EXTENSION IF NOT EXISTS hypopg;\n```\n\n### Installing extensions on self-managed Postgres\n\nIf you are managing your own Postgres installation, you may need to do additional work.\nBefore loading the `pg_stat_statements` extension you must ensure that it is listed in the `shared_preload_libraries` in the Postgres configuration file.\nThe `hypopg` extension may also require additional system-level installation (e.g., via your package manager) because it does not always ship with Postgres.\n\n## Usage Examples\n\n### Get Database Health Overview\n\nAsk:\n> Check the health of my database and identify any issues.\n\n### Analyze Slow Queries\n\nAsk:\n> What are the slowest queries in my database? And how can I speed them up?\n\n### Get Recommendations On How To Speed Things Up\n\nAsk:\n> My app is slow. How can I make it faster?\n\n### Generate Index Recommendations\n\nAsk:\n> Analyze my database workload and suggest indexes to improve performance.\n\n### Optimize a Specific Query\n\nAsk:\n> Help me optimize this query: SELECT \\* FROM orders JOIN customers ON orders.customer_id = customers.id WHERE orders.created_at > '2023-01-01';\n\n## MCP Server API\n\nThe [MCP standard](https:\u002F\u002Fmodelcontextprotocol.io\u002F) defines various types of endpoints: Tools, Resources, Prompts, and others.\n\nPostgres MCP Pro provides functionality via [MCP tools](https:\u002F\u002Fmodelcontextprotocol.io\u002Fdocs\u002Fconcepts\u002Ftools) alone.\nWe chose this approach because the [MCP client ecosystem](https:\u002F\u002Fmodelcontextprotocol.io\u002Fclients) has widespread support for MCP tools.\nThis contrasts with the approach of other Postgres MCP servers, including the [Reference Postgres MCP Server](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fservers-archived\u002Ftree\u002Fmain\u002Fsrc\u002Fpostgres), which use [MCP resources](https:\u002F\u002Fmodelcontextprotocol.io\u002Fdocs\u002Fconcepts\u002Fresources) to expose schema information.\n\n\nPostgres MCP Pro Tools:\n\n| Tool Name | Description |\n|-----------|-------------|\n| `list_schemas` | Lists all database schemas available in the PostgreSQL instance. |\n| `list_objects` | Lists database objects (tables, views, sequences, extensions) within a specified schema. |\n| `get_object_details` | Provides information about a specific database object, for example, a table's columns, constraints, and indexes. |\n| `execute_sql` | Executes SQL statements on the database, with read-only limitations when connected in restricted mode. |\n| `explain_query` | Gets the execution plan for a SQL query describing how PostgreSQL will process it and exposing the query planner's cost model. Can be invoked with hypothetical indexes to simulate the behavior after adding indexes. |\n| `get_top_queries` | Reports the slowest SQL queries based on total execution time using `pg_stat_statements` data. |\n| `analyze_workload_indexes` | Analyzes the database workload to identify resource-intensive queries, then recommends optimal indexes for them. |\n| `analyze_query_indexes` | Analyzes a list of specific SQL queries (up to 10) and recommends optimal indexes for them. |\n| `analyze_db_health` | Performs comprehensive health checks including: buffer cache hit rates, connection health, constraint validation, index health (duplicate\u002Funused\u002Finvalid), sequence limits, and vacuum health. |\n\n\n## Related Projects\n\n**Postgres MCP Servers**\n- [Query MCP](https:\u002F\u002Fgithub.com\u002Falexander-zuev\u002Fsupabase-mcp-server). An MCP server for Supabase Postgres with a three-tier safety architecture and Supabase management API support.\n- [PG-MCP](https:\u002F\u002Fgithub.com\u002Fstuzero\u002Fpg-mcp-server). An MCP server for PostgreSQL with flexible connection options, explain plans, extension context, and more.\n- [Reference PostgreSQL MCP Server](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fservers-archived\u002Ftree\u002Fmain\u002Fsrc\u002Fpostgres). A simple MCP Server implementation exposing schema information as MCP resources and executing read-only queries.\n- [Supabase Postgres MCP Server](https:\u002F\u002Fgithub.com\u002Fsupabase-community\u002Fsupabase-mcp). This MCP Server provides Supabase management features and is actively maintained by the Supabase community.\n- [Nile MCP Server](https:\u002F\u002Fgithub.com\u002Fniledatabase\u002Fnile-mcp-server). An MCP server providing access to the management API for the Nile's multi-tenant Postgres service.\n- [Neon MCP Server](https:\u002F\u002Fgithub.com\u002Fneondatabase-labs\u002Fmcp-server-neon). An MCP server providing access to the management API for Neon's serverless Postgres service.\n- [Wren MCP Server](https:\u002F\u002Fgithub.com\u002FCanner\u002Fwren-engine). Provides a semantic engine powering business intelligence for Postgres and other databases.\n\n**DBA Tools (including commercial offerings)**\n- [Aiven Database Optimizer](https:\u002F\u002Faiven.io\u002Fsolutions\u002Faiven-ai-database-optimizer). A tool that provides holistic database workload analysis, query optimizations, and other performance improvements.\n- [dba.ai](https:\u002F\u002Fwww.dba.ai\u002F). An AI-powered database administration assistant that integrates with GitHub to resolve code issues.\n- [pgAnalyze](https:\u002F\u002Fpganalyze.com\u002F). A comprehensive monitoring and analytics platform for identifying performance bottlenecks, optimizing queries, and real-time alerting.\n- [Postgres.ai](https:\u002F\u002Fpostgres.ai\u002F). An interactive chat experience combining an extensive Postgres knowledge base and GPT-4.\n- [Xata Agent](https:\u002F\u002Fgithub.com\u002Fxataio\u002Fagent). An open-source AI agent that automatically monitors database health, diagnoses issues, and provides recommendations using LLM-powered reasoning and playbooks.\n\n**Postgres Utilities**\n- [Dexter](https:\u002F\u002Fgithub.com\u002FDexterDB\u002Fdexter). A tool for generating and testing hypothetical indexes on PostgreSQL.\n- [PgHero](https:\u002F\u002Fgithub.com\u002Fankane\u002Fpghero). A performance dashboard for Postgres, with recommendations.\nPostgres MCP Pro incorporates health checks from PgHero.\n- [PgTune](https:\u002F\u002Fgithub.com\u002Fle0pard\u002Fpgtune?tab=readme-ov-file). Heuristics for tuning Postgres configuration.\n\n## Frequently Asked Questions\n\n*How is Postgres MCP Pro different from other Postgres MCP servers?*\nThere are many MCP servers allow an AI agent to run queries against a Postgres database.\nPostgres MCP Pro does that too, but also adds tools for understanding and improving the performance of your Postgres database.\nFor example, it implements a version of the [Anytime Algorithm of Database Tuning Advisor for Microsoft SQL Server](https:\u002F\u002Fwww.microsoft.com\u002Fen-us\u002Fresearch\u002Fwp-content\u002Fuploads\u002F2020\u002F06\u002FAnytime-Algorithm-of-Database-Tuning-Advisor-for-Microsoft-SQL-Server.pdf), a modern industrial-strength algorithm for automatic index tuning.\n\n| Postgres MCP Pro | Other Postgres MCP Servers |\n|--------------|----------------------------|\n| ✅ Deterministic database health checks | ❌ Unrepeatable LLM-generated health queries |\n| ✅ Principled indexing search strategies | ❌ Gen-AI guesses at indexing improvements |\n| ✅ Workload analysis to find top problems | ❌ Inconsistent problem analysis |\n| ✅ Simulates performance improvements | ❌ Try it yourself and see if it works |\n\nPostgres MCP Pro complements generative AI by adding deterministic tools and classical optimization algorithms\nThe combination is both reliable and flexible.\n\n\n*Why are MCP tools needed when the LLM can reason, generate SQL, etc?*\nLLMs are invaluable for tasks that involve ambiguity, reasoning, or natural language.\nWhen compared to procedural code, however, they can be slow, expensive, non-deterministic, and sometimes produce unreliable results.\nIn the case of database tuning, we have well established algorithms, developed over decades, that are proven to work.\nPostgres MCP Pro lets you combine the best of both worlds by pairing LLMs with classical optimization algorithms and other procedural tools.\n\n*How do you test Postgres MCP Pro?*\nTesting is critical to ensuring that Postgres MCP Pro is reliable and accurate.\nWe are building out a suite of AI-generated adversarial workloads designed to challenge Postgres MCP Pro and ensure it performs under a broad variety of scenarios.\n\n*What Postgres versions are supported?*\nOur testing presently focuses on Postgres 15, 16, and 17.\nWe plan to support Postgres versions 13 through 17.\n\n*Who created this project?*\nThis project is created and maintained by [Crystal DBA](https:\u002F\u002Fwww.crystaldba.ai).\n\n## Roadmap\n\n*TBD*\n\nYou and your needs are a critical driver for what we build.\nTell us what you want to see by opening an [issue](https:\u002F\u002Fgithub.com\u002Fcrystaldba\u002Fpostgres-mcp\u002Fissues) or a [pull request](https:\u002F\u002Fgithub.com\u002Fcrystaldba\u002Fpostgres-mcp\u002Fpulls).\nYou can also contact us on [Discord](https:\u002F\u002Fdiscord.gg\u002F4BEHC7ZM).\n\n## Technical Notes\n\nThis section includes a high-level overview technical considerations that influenced the design of Postgres MCP Pro.\n\n### Index Tuning\n\nDevelopers know that missing indexes are one of the most common causes of database performance issues.\nIndexes provide access methods that allow Postgres to quickly locate data that is required to execute a query.\nWhen tables are small, indexes make little difference, but as the size of the data grows, the difference in algorithmic complexity between a table scan and an index lookup becomes significant (typically *O*(*n*) vs *O*(*log* *n*), potentially more if joins on multiple tables are involved).\n\nGenerating suggested indexes in Postgres MCP Pro proceeds in several stages:\n\n1. *Identify SQL queries in need of tuning*.\n    If you know you are having a problem with a specific SQL query you can provide it.\n    Postgres MCP Pro can also analyze the workload to identify index tuning targets.\n    To do this, it relies on the `pg_stat_statements` extension, which records the runtime and resource consumption of each query.\n\n    A query is a candidate for index tuning if it is a top resource consumer, either on a per-execution basis or in aggregate.\n    At present, we use execution time as a proxy for cumulative resource consumption, but it may also make sense to look at specifics resources, e.g., the number of blocks accessed or the number of blocks read from disk.\n    The `analyze_query_workload` tool focuses on slow queries, using the mean time per execution with thresholds for execution count and mean execution time.\n    Agents may also call `get_top_queries`, which accepts a parameter for mean vs. total execution time, then pass these queries `analyze_query_indexes` to get index recommendations.\n\n    Sophisticated index tuning systems use \"workload compression\" to produce a representative subset of queries that reflects the characteristics of the workload as a whole, reducing the problem for downstream algorithms.\n    Postgres MCP Pro performs a limited form of workload compression by normalizing queries so that those generated from the same template appear as one.\n    It weights each query equally, a simplification that works when the benefits to indexing are large.\n\n2. *Generate candidate indexes*\n    Once we have a list of SQL queries that we want to improve through indexing, we generate a list of indexes that we might want to add.\n    To do this, we parse the SQL and identify any columns used in filters, joins, grouping, or sorting.\n\n    To generate all possible indexes we need to consider combinations of these columns, because Postgres supports [multicolumn indexes](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Findexes-multicolumn.html).\n    In the present implementation, we include only one permutation of each possible multicolumn index, which is selected at random.\n    We make this simplification to reduce the search space because permutations often have equivalent performance.\n    However, we hope to improve in this area.\n\n3. *Search for the optimal index configuration*.\n    Our objective is to find the combination of indexes that optimally balances the performance benefits against the costs of storing and maintaining those indexes.\n    We estimate the performance improvement by using the \"what if?\" capabilities provided by the `hypopg` extension.\n    This simulates how the Postgres query optimizer will execute a query after the addition of indexes, and reports changes based on the actual Postgres cost model.\n\n    One challenge is that generating query plans generally requires knowledge of the specific parameter values used in the query.\n    Query normalization, which is necessary to reduce the queries under consideration, removes parameter constants.\n    Parameter values provided via bind variables are similarly not available to us.\n\n    To address this problem, we produce realistic constants that we can provide as parameters by sampling from the table statistics.\n    In version 16, Postgres added [generic explain plan functionality](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fsql-explain.html), but it has limitations, for example around `LIKE` clauses, which our implementation does not have.\n\n    Search strategy is critical because evaluating all possible index combinations feasible only in simple situations.\n    This is what most sets apart various indexing approaches.\n    Adapting the approach of Microsoft's Anytime algorithm, we employ a greedy search strategy, i.e., find the best one-index solution, then find the best index to add to that to produce a two-index solution.\n    Our search terminates when the time budget is exhausted or when a round of exploration fails to produce any gains above the minimum improvement threshold of 10%.\n\n4. *Cost-benefit analysis*.\n    When posed with two indexing alternatives, one which produces better performance and one which requires more space, how do we decide which to choose?\n    Traditionally, index advisors ask for a storage budget and optimize performance with respect to that storage budget.\n    We also take a storage budget, but perform a cost-benefit analysis throughout the optimization.\n\n    We frame this as the problem of selecting a point along the [Pareto front](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FPareto_front)—the set of choices for which improving one quality metric necessarily worsens another.\n    In an ideal world, we might want to assess the cost of the storage and the benefit of improved performance in monetary terms.\n    However, there is a simpler and more practical approach: to look at the changes in relative terms.\n    Most people would agree that a 100x performance improvement is worth it, even if the storage cost is 2x.\n    In our implementation, we use a configurable parameter to set this threshold.\n    By default, we require the change in the log (base 10) of the performance improvement to be 2x the difference in the log of the space cost.\n    This works out to allowing a maximum 10x increase in space for a 100x performance improvement.\n\nOur implementation is most closely related to the [Anytime Algorithm](https:\u002F\u002Fwww.microsoft.com\u002Fen-us\u002Fresearch\u002Fwp-content\u002Fuploads\u002F2020\u002F06\u002FAnytime-Algorithm-of-Database-Tuning-Advisor-for-Microsoft-SQL-Server.pdf) found in Microsoft SQL Server.\nCompared to [Dexter](https:\u002F\u002Fgithub.com\u002Fankane\u002Fdexter\u002F), an automatic indexing tool for Postgres, we search a larger space and use different heuristics.\nThis allows us to generate better solutions at the cost of longer runtime.\n\nWe also show the work done in each round of the search, including a comparison of the query plans before and after the addition of each index.\nThis give the LLM additional context that it can use when responding to the indexing recommendations.\n\n### Experimental: Index Tuning by LLM\n\nPostgres MCP Pro includes an experimental index tuning feature based on [Optimization by LLM](https:\u002F\u002Farxiv.org\u002Fabs\u002F2309.03409).\nInstead of using heuristics to explore possible index configurations, we provide the database schema and query plans to an LLM and ask it to propose index configurations.\nWe then use `hypopg` to predict performance with the proposed indexes, then feed those results back into the LLM to produce a new set of suggestions.\nWe repeat this process until multiple rounds of iteration produce no further improvements.\n\nIndex optimization by LLM is has advantages when the index search space is large, or when indexes with many columns need to be considered.\nLike traditional search-based approaches, it relies on the accuracy of the `hypopg` performance predictions.\n\nIn order to perform index optimization by LLM, you must provide an OpenAI API key by setting the `OPENAI_API_KEY` environment variable.\n\n\n### Database Health\n\nDatabase health checks identify tuning opportunities and maintenance needs before they lead to critical issues.\nIn the present release, Postgres MCP Pro adapts the database health checks directly from [PgHero](https:\u002F\u002Fgithub.com\u002Fankane\u002Fpghero).\nWe are working to fully validate these checks and may extend them in the future.\n\n- *Index Health*. Looks for unused indexes, duplicate indexes, and indexes that are bloated. Bloated indexes make inefficient use of database pages.\n  Postgres autovacuum cleans up index entries pointing to dead tuples, and marks the entries as reusable. However, it does not compact the index pages and, eventually, index pages may contain few live tuple references.\n- *Buffer Cache Hit Rate*. Measures the proportion of database reads that are served from the buffer cache instead of disk.\n  A low buffer cache hit rate must be investigated as it is often not cost-optimal and leads to degraded application performance.\n- *Connection Health*. Checks the number of connections to the database and reports on their utilization.\n  The biggest risk is running out of connections, but a high number of idle or blocked connections can also indicate issues.\n- *Vacuum Health*. Vacuum is important for many reasons.\n  A critical one is preventing transaction id wraparound, which can cause the database to stop accepting writes.\n  The Postgres multi-version concurrency control (MVCC) mechanism requires a unique transaction id for each transaction.\n  However, because Postgres uses a 32-bit signed integer for transaction ids, it needs to reuse transaction ids after after a maximum of 2 billion transactions.\n  To do this it \"freezes\" the transaction ids of historical transactions, setting them all to a special value that indicates distant past.\n  When records first go to disk, they are written visibility for a range of transaction ids.\n  Before re-using these transaction ids, Postgres must update any on-disk records, \"freezing\" them to remove the references to the transaction ids to be reused.\n  This check looks for tables that require vacuuming to prevent transaction id wraparound.\n- *Replication Health*. Checks replication health by monitoring lag between primary and replicas, verifying replication status, and tracking usage of replication slots.\n- *Constraint Health*. During normal operation, Postgres rejects any transactions that would cause a constraint violation.\n  However, invalid constraints may occur after loading data or in recovery scenarios. This check looks for any invalid constraints.\n- *Sequence Health*. Looks for sequences that are at risk of exceeding their maximum value.\n\n\n### Postgres Client Library\n\nPostgres MCP Pro uses [psycopg3](https:\u002F\u002Fwww.psycopg.org\u002F) to connect to Postgres using asynchronous I\u002FO.\nUnder the hood, psycopg3 uses the [libpq](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Flibpq.html) library to connect to Postgres, providing access to the full Postgres feature set and an underlying implementation fully supported by the Postgres community.\n\nSome other Python-based MCP servers use [asyncpg](https:\u002F\u002Fgithub.com\u002FMagicStack\u002Fasyncpg), which may simplify installation by eliminating the `libpq` dependency.\nAsyncpg is also probably [faster](https:\u002F\u002Ffernandoarteaga.dev\u002Fblog\u002Fpsycopg-vs-asyncpg\u002F) than psycopg3, but we have not validated this ourselves.\n[Older benchmarks](https:\u002F\u002Fgistpreview.github.io\u002F?0ed296e93523831ea0918d42dd1258c2) report a larger performance gap, suggesting that the newer psycopg3 has closed the gap as it matures.\n\nBalancing these considerations, we selected `psycopg3` over `asyncpg`.\nWe remain open to revising this decision in the future.\n\n\n### Connection Configuration\n\nLike the [Reference PostgreSQL MCP Server](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fservers-archived\u002Ftree\u002Fmain\u002Fsrc\u002Fpostgres), Postgres MCP Pro takes Postgres connection information at startup.\nThis is convenient for users who always connect to the same database but can be cumbersome when users switch databases.\n\nAn alternative approach, taken by [PG-MCP](https:\u002F\u002Fgithub.com\u002Fstuzero\u002Fpg-mcp-server), is provide connection details via MCP tool calls at the time of use.\nThis is more convenient for users who switch databases, and allows a single MCP server to simultaneously support multiple end-users.\n\nThere must be a better approach than either of these.\nBoth have security weaknesses—few MCP clients store the MCP server configuration securely (an exception is Goose), and credentials provided via MCP tools are passed through the LLM and stored in the chat history.\nBoth also have usability issues in some scenarios.\n\n\n### Schema Information\n\nThe purpose of the schema information tool is to provide the calling AI agent with the information it needs to generate correct and performant SQL.\nFor example, suppose a user asks, \"How many flights took off from San Francisco and landed in Paris during the past year?\"\nThe AI agent needs to find the table that stores the flights, the columns that store the origin and destinations, and perhaps a table that maps between airport codes and airport locations.\n\n\n*Why provide schema information tools when LLMs are generally capable of generating the SQL to retrieve this information from Postgres directly?*\n\nOur experience using Claude indicates that the calling LLM is very good at generating SQL to explore the Postgres schema by querying the [Postgres system catalog](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fcatalogs.html) and the [information schema](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Finformation-schema.html) (an ANSI-standardized database metadata view).\nHowever, we do not know whether other LLMs do so as reliably and capably.\n\n*Would it be better to provide schema information using [MCP resources](https:\u002F\u002Fmodelcontextprotocol.io\u002Fdocs\u002Fconcepts\u002Fresources) rather than [MCP tools](https:\u002F\u002Fmodelcontextprotocol.io\u002Fdocs\u002Fconcepts\u002Ftools)?*\n\nThe [Reference PostgreSQL MCP Server](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fservers-archived\u002Ftree\u002Fmain\u002Fsrc\u002Fpostgres) uses resources to expose schema information rather than tools.\nNavigating resources is similar to navigating a file system, so this approach is natural in many ways.\nHowever, resource support is less widespread than tool support in the MCP client ecosystem (see [example clients](https:\u002F\u002Fmodelcontextprotocol.io\u002Fclients)).\nIn addition, while the MCP standard says that resources can be accessed by either AI agents or end-user humans, some clients only support human navigation of the resource tree.\n\n\n### Protected SQL Execution\n\nAI amplifies longstanding challenges of protecting databases from a range of threats, ranging from simple mistakes to sophisticated attacks by malicious actors.\nWhether the threat is accidental or malicious, a similar security framework applies, with aims that fall into three categories: confidentiality, integrity, and availability.\nThe familiar tension between convenience and safety is also evident and pronounced.\n\nPostgres MCP Pro's protected SQL execution mode focuses on integrity.\nIn the context of MCP, we are most concerned with LLM-generated SQL causing damage—for example, unintended data modification or deletion, or other changes that might circumvent an organization's change management process.\n\nThe simplest way to provide integrity is to ensure that all SQL executed against the database is read-only.\nOne way to do this is by creating a database user with read-only access permissions.\nWhile this is a good approach, many find this cumbersome in practice.\nPostgres does not provide a way to place a connection or session into read-only mode, so Postgres MCP Pro uses a more complex approach to ensure read-only SQL execution on top of a read-write connection.\n\nPostgres MCP Provides a read-only transaction mode that prevents data and schema modifications.\nLike the [Reference PostgreSQL MCP Server](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fservers-archived\u002Ftree\u002Fmain\u002Fsrc\u002Fpostgres), we use read-only transactions to provide protected SQL execution.\n\nTo make this mechanism robust, we need to ensure that the SQL does not somehow circumvent the read-only transaction mode, say by issuing a `COMMIT` or `ROLLBACK` statement and then beginning a new transaction.\n\nFor example, the LLM can circumvent the read-only transaction mode by issuing a `ROLLBACK` statement and then beginning a new transaction.\nFor example:\n```sql\nROLLBACK; DROP TABLE users;\n```\n\nTo prevent cases like this, we parse the SQL before execution using the [pglast](https:\u002F\u002Fpglast.readthedocs.io\u002F) library.\nWe reject any SQL that contains `commit` or `rollback` statements.\nHelpfully, the popular Postgres stored procedure languages, including PL\u002FpgSQL and PL\u002FPython, do not allow for `COMMIT` or `ROLLBACK` statements.\nIf you have unsafe stored procedure languages enabled on your database, then our read-only protections could be circumvented.\n\nAt present, Postgres MCP Pro provides two levels of protection for the database, one at either extreme of the convenience\u002Fsafety spectrum.\n- \"Unrestricted\" provides maximum flexibility.\nIt is suitable for development environments where speed and flexibility are paramount, and where there is no need to protect valuable or sensitive data.\n- \"Restricted\" provides a balance between flexibility and safety.\nIt is suitable for production environments where the database is exposed to untrusted users, and where it is important to protect valuable or sensitive data.\n\nUnrestricted mode aligns with the approach of [Cursor's auto-run mode](https:\u002F\u002Fdocs.cursor.com\u002Fchat\u002Ftools#auto-run), where the AI agent operates with limited human oversight or approvals.\nWe expect auto-run to be deployed in development environments where the consequences of mistakes are low, where databases do not contain valuable or sensitive data, and where they can be recreated or restored from backups when needed.\n\nWe designed restricted mode to be conservative, erring on the side of safety even though it may be inconvenient.\nRestricted mode is limited to read-only operations, and we limit query execution time to prevent long-running queries from impacting system performance.\nWe may add measures in the future to make sure that restricted mode is safe to use with production databases.\n\n\n## Postgres MCP Pro Development\n\nThe instructions below are for developers who want to work on Postgres MCP Pro, or users who prefer to install Postgres MCP Pro from source.\n\n### Local Development Setup\n\n1. **Install uv**:\n\n   ```bash\n   curl -sSL https:\u002F\u002Fastral.sh\u002Fuv\u002Finstall.sh | sh\n   ```\n\n2. **Clone the repository**:\n\n   ```bash\n   git clone https:\u002F\u002Fgithub.com\u002Fcrystaldba\u002Fpostgres-mcp.git\n   cd postgres-mcp\n   ```\n\n3. **Install dependencies**:\n\n   ```bash\n   uv pip install -e .\n   uv sync\n   ```\n\n4. **Run the server**:\n   ```bash\n   uv run postgres-mcp \"postgres:\u002F\u002Fuser:password@localhost:5432\u002Fdbname\"\n   ```\n","Postgres MCP Pro 是一个为开发者及其AI助手提供可配置读写访问和性能分析的PostgreSQL管理工具。其核心功能包括数据库健康检查、索引调优、查询计划分析、智能模式理解和安全SQL执行，通过这些功能可以帮助用户优化数据库性能并确保操作安全。该项目采用Python开发，支持标准输入\u002F输出和服务器发送事件两种传输方式，使得它在不同环境下都能灵活使用。适合需要对PostgreSQL进行深度管理和优化的场景，如开发测试、生产环境维护等。",2,"2026-06-11 03:41:55","high_star"]