[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-crystaldba--postgres-mcp":3,"tool-crystaldba--postgres-mcp":64},[4,17,27,35,43,56],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":16},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,3,"2026-04-05T11:01:52",[13,14,15],"开发框架","图像","Agent","ready",{"id":18,"name":19,"github_repo":20,"description_zh":21,"stars":22,"difficulty_score":23,"last_commit_at":24,"category_tags":25,"status":16},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",138956,2,"2026-04-05T11:33:21",[13,15,26],"语言模型",{"id":28,"name":29,"github_repo":30,"description_zh":31,"stars":32,"difficulty_score":23,"last_commit_at":33,"category_tags":34,"status":16},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",107662,"2026-04-03T11:11:01",[13,14,15],{"id":36,"name":37,"github_repo":38,"description_zh":39,"stars":40,"difficulty_score":23,"last_commit_at":41,"category_tags":42,"status":16},3704,"NextChat","ChatGPTNextWeb\u002FNextChat","NextChat 是一款轻量且极速的 AI 助手，旨在为用户提供流畅、跨平台的大模型交互体验。它完美解决了用户在多设备间切换时难以保持对话连续性，以及面对众多 AI 模型不知如何统一管理的痛点。无论是日常办公、学习辅助还是创意激发，NextChat 都能让用户随时随地通过网页、iOS、Android、Windows、MacOS 或 Linux 端无缝接入智能服务。\n\n这款工具非常适合普通用户、学生、职场人士以及需要私有化部署的企业团队使用。对于开发者而言，它也提供了便捷的自托管方案，支持一键部署到 Vercel 或 Zeabur 等平台。\n\nNextChat 的核心亮点在于其广泛的模型兼容性，原生支持 Claude、DeepSeek、GPT-4 及 Gemini Pro 等主流大模型，让用户在一个界面即可自由切换不同 AI 能力。此外，它还率先支持 MCP（Model Context Protocol）协议，增强了上下文处理能力。针对企业用户，NextChat 提供专业版解决方案，具备品牌定制、细粒度权限控制、内部知识库整合及安全审计等功能，满足公司对数据隐私和个性化管理的高标准要求。",87618,"2026-04-05T07:20:52",[13,26],{"id":44,"name":45,"github_repo":46,"description_zh":47,"stars":48,"difficulty_score":23,"last_commit_at":49,"category_tags":50,"status":16},2268,"ML-For-Beginners","microsoft\u002FML-For-Beginners","ML-For-Beginners 是由微软推出的一套系统化机器学习入门课程，旨在帮助零基础用户轻松掌握经典机器学习知识。这套课程将学习路径规划为 12 周，包含 26 节精炼课程和 52 道配套测验，内容涵盖从基础概念到实际应用的完整流程，有效解决了初学者面对庞大知识体系时无从下手、缺乏结构化指导的痛点。\n\n无论是希望转型的开发者、需要补充算法背景的研究人员，还是对人工智能充满好奇的普通爱好者，都能从中受益。课程不仅提供了清晰的理论讲解，还强调动手实践，让用户在循序渐进中建立扎实的技能基础。其独特的亮点在于强大的多语言支持，通过自动化机制提供了包括简体中文在内的 50 多种语言版本，极大地降低了全球不同背景用户的学习门槛。此外，项目采用开源协作模式，社区活跃且内容持续更新，确保学习者能获取前沿且准确的技术资讯。如果你正寻找一条清晰、友好且专业的机器学习入门之路，ML-For-Beginners 将是理想的起点。",84991,"2026-04-05T10:45:23",[14,51,52,53,15,54,26,13,55],"数据工具","视频","插件","其他","音频",{"id":57,"name":58,"github_repo":59,"description_zh":60,"stars":61,"difficulty_score":10,"last_commit_at":62,"category_tags":63,"status":16},3128,"ragflow","infiniflow\u002Fragflow","RAGFlow 是一款领先的开源检索增强生成（RAG）引擎，旨在为大语言模型构建更精准、可靠的上下文层。它巧妙地将前沿的 RAG 技术与智能体（Agent）能力相结合，不仅支持从各类文档中高效提取知识，还能让模型基于这些知识进行逻辑推理和任务执行。\n\n在大模型应用中，幻觉问题和知识滞后是常见痛点。RAGFlow 通过深度解析复杂文档结构（如表格、图表及混合排版），显著提升了信息检索的准确度，从而有效减少模型“胡编乱造”的现象，确保回答既有据可依又具备时效性。其内置的智能体机制更进一步，使系统不仅能回答问题，还能自主规划步骤解决复杂问题。\n\n这款工具特别适合开发者、企业技术团队以及 AI 研究人员使用。无论是希望快速搭建私有知识库问答系统，还是致力于探索大模型在垂直领域落地的创新者，都能从中受益。RAGFlow 提供了可视化的工作流编排界面和灵活的 API 接口，既降低了非算法背景用户的上手门槛，也满足了专业开发者对系统深度定制的需求。作为基于 Apache 2.0 协议开源的项目，它正成为连接通用大模型与行业专有知识之间的重要桥梁。",77062,"2026-04-04T04:44:48",[15,14,13,26,54],{"id":65,"github_repo":66,"name":67,"description_en":68,"description_zh":69,"ai_summary_zh":69,"readme_en":70,"readme_zh":71,"quickstart_zh":72,"use_case_zh":73,"hero_image_url":74,"owner_login":75,"owner_name":76,"owner_avatar_url":77,"owner_bio":78,"owner_company":79,"owner_location":79,"owner_email":80,"owner_twitter":79,"owner_website":81,"owner_url":82,"languages":83,"stars":102,"forks":103,"last_commit_at":104,"license":105,"difficulty_score":23,"env_os":106,"env_gpu":107,"env_ram":107,"env_deps":108,"category_tags":115,"github_topics":79,"view_count":23,"oss_zip_url":79,"oss_zip_packed_at":79,"status":16,"created_at":116,"updated_at":117,"faqs":118,"releases":154},2674,"crystaldba\u002Fpostgres-mcp","postgres-mcp","Postgres MCP Pro provides configurable read\u002Fwrite access and performance analysis for you and your AI agents.","postgres-mcp 是一款专为 PostgreSQL 数据库设计的开源 MCP（模型上下文协议）服务器，旨在成为开发者与 AI 助手之间的智能桥梁。它不仅仅是一个简单的数据库连接工具，更能让 AI 代理深度理解数据库架构，从而协助完成从代码编写、测试部署到生产环境调优的全流程工作。\n\n在实际开发中，AI 生成的 SQL 代码往往存在性能低下或安全隐患，postgres-mcp 有效解决了这一痛点。它提供了可配置的读写权限控制与安全 SQL 解析机制，确保在生产环境中也能安全执行；同时具备强大的性能分析能力，能自动检查数据库健康状态（如索引效率、连接利用率），并利用工业级算法探索成千上万种索引组合以找到最优解。此外，它还支持模拟假设性索引对查询计划的影响，帮助快速定位并优化慢查询。\n\n这款工具特别适合后端开发者、数据库管理员（DBA）以及希望利用 AI 提升数据库运维效率的技术团队。无论是修复 ORM 框架导致的性能瓶颈，还是日常的健康巡检与索引调优，postgres-mcp 都能让 AI 助手变得更“懂”数据库，将原本复杂的调优工作变得简单高效。","\u003Cdiv align=\"center\">\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fcrystaldba_postgres-mcp_readme_f0dd146827df.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","\u003Cdiv align=\"center\">\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fcrystaldba_postgres-mcp_readme_f0dd146827df.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>一款具备索引调优、执行计划分析、健康检查及安全 SQL 执行功能的 Postgres MCP 服务器。\u003C\u002Fh3>\n\n\u003Cdiv class=\"toc\">\n  \u003Ca href=\"#overview\">概述\u003C\u002Fa> •\n  \u003Ca href=\"#demo\">演示\u003C\u002Fa> •\n  \u003Ca href=\"#quick-start\">快速入门\u003C\u002Fa> •\n  \u003Ca href=\"#technical-notes\">技术说明\u003C\u002Fa> •\n  \u003Ca href=\"#mcp-server-api\">MCP API\u003C\u002Fa> •\n  \u003Ca href=\"#related-projects\">相关项目\u003C\u002Fa> •\n  \u003Ca href=\"#frequently-asked-questions\">常见问题\u003C\u002Fa>\n\u003C\u002Fdiv>\n\n\u003C\u002Fdiv>\n\n## 概述\n\n**Postgres MCP Pro** 是一个开源的模型上下文协议（MCP）服务器，旨在支持您和您的 AI 代理完成**整个开发流程**——从最初的编码、测试与部署，到生产环境中的调优与维护。\n\nPostgres MCP Pro 的功能远不止于简单地封装数据库连接。\n\n其主要特性包括：\n\n- **🔍 数据库健康状况**：分析索引健康、连接利用率、缓冲区缓存、VACUUM 状态、序列限制、复制延迟等。\n- **⚡ 索引调优**：利用工业级算法，探索数千种可能的索引组合，为您的工作负载找到最优解决方案。\n- **📈 查询计划**：通过查看 EXPLAIN 计划并模拟假设索引的影响，验证和优化查询性能。\n- **🧠 模式智能**：基于对数据库模式的深入理解，生成具有上下文感知能力的 SQL 语句。\n- **🛡️ 安全 SQL 执行**：提供可配置的访问控制机制，包括只读模式和支持安全的 SQL 解析，使其既适用于开发环境，也适用于生产环境。\n\nPostgres MCP Pro 同时支持 [标准输入\u002F输出 (stdio)](https:\u002F\u002Fmodelcontextprotocol.io\u002Fdocs\u002Fconcepts\u002Ftransports#standard-input%2Foutput-stdio) 和 [服务器发送事件 (SSE)](https:\u002F\u002Fmodelcontextprotocol.io\u002Fdocs\u002Fconcepts\u002Ftransports#server-sent-events-sse)，以适应不同运行环境的需求。\n\n如需了解我们构建 Postgres MCP Pro 的背景信息，请参阅我们的[发布博客文章](https:\u002F\u002Fwww.crystaldba.ai\u002Fblog\u002Fpost\u002Fannouncing-postgres-mcp-server-pro)。\n\n## 演示\n\n*从无法使用到极速响应*\n- **挑战**：我们使用 AI 助手生成了一个电影应用，但 SQLAlchemy ORM 代码运行极其缓慢。\n- **解决方案**：借助 Postgres MCP Pro 与 Cursor，我们在几分钟内解决了性能问题。\n\n具体操作：\n- 🚀 优化了性能——包括 ORM 查询、索引设计和缓存机制。\n- 🛠️ 修复了一个失效页面——通过引导代理探索数据、修正查询并添加相关内容。\n- 🧠 改进了热门电影推荐——通过深入分析数据并调整 ORM 查询，使推荐结果更加相关。\n\n请观看下方视频或阅读[详细步骤](examples\u002Fmovie-app.md)。\n\nhttps:\u002F\u002Fgithub.com\u002Fuser-attachments\u002Fassets\u002F24e05745-65e9-4998-b877-a368f1eadc13\n\n\n\n\n## 快速入门\n\n### 前置条件\n\n在开始之前，请确保您已准备好以下内容：\n1. 数据库的访问凭据。\n2. Docker *或* Python 3.12 及以上版本。\n\n#### 访问凭据\n您可以通过 `psql` 或图形化工具（如 [pgAdmin](https:\u002F\u002Fwww.pgadmin.org\u002F)）来验证访问凭据的有效性。\n\n\n#### Docker 或 Python\n您可以选择使用 Docker 或 Python 来部署。\n\n通常我们建议使用 Docker，因为 Python 用户可能会遇到更多与环境相关的问题。不过，如果您更熟悉其中一种方式，也可以根据自身情况选择。\n\n### 安装\n\n请按照以下任一方法安装 Postgres MCP Pro：\n\n#### 方法 1：使用 Docker\n\n拉取 Postgres MCP Pro 的 MCP 服务器 Docker 镜像。该镜像包含了所有必要的依赖项，能够让您在多种环境中可靠地运行 Postgres MCP Pro。\n\n```bash\ndocker pull crystaldba\u002Fpostgres-mcp\n```\n\n\n#### 方法 2：使用 Python\n\n如果您已安装 `pipx`，则可以使用以下命令安装 Postgres MCP Pro：\n\n```bash\npipx install postgres-mcp\n```\n\n否则，您可以使用 `uv` 来安装：\n\n```bash\nuv pip install postgres-mcp\n```\n\n如果需要安装 `uv`，请参考[uv 的安装说明](https:\u002F\u002Fdocs.astral.sh\u002Fuv\u002Fgetting-started\u002Finstallation\u002F)。\n\n### 配置您的 AI 助手\n\n我们提供了使用 Postgres MCP Pro 与 Claude Desktop 配合使用的完整配置说明。\n许多 MCP 客户端都具有类似的配置文件，您可以根据这些步骤将其适配到您选择的客户端上。\n\n#### Claude Desktop 配置\n\n您需要编辑 Claude Desktop 的配置文件以添加 Postgres MCP Pro。\n该文件的位置取决于您的操作系统：\n- macOS：`~\u002FLibrary\u002FApplication Support\u002FClaude\u002Fclaude_desktop_config.json`\n- Windows：`%APPDATA%\u002FClaude\u002Fclaude_desktop_config.json`\n\n您也可以通过 Claude Desktop 中的“设置”菜单项来找到配置文件。\n\n接下来，您需要编辑配置文件中的 `mcpServers` 部分。\n\n##### 如果您使用 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\nPostgres MCP Pro 的 Docker 镜像会自动将主机名 `localhost` 映射为容器内部可用的地址。\n\n- macOS\u002FWindows：自动使用 `host.docker.internal`\n- Linux：自动使用 `172.17.0.1` 或相应的主机地址\n\n##### 如果您使用 `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##### 如果您使用 `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##### 如果您使用 `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##### 连接 URI\n\n请将 `postgresql:\u002F\u002F...` 替换为您自己的 [Postgres 数据库连接 URI](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Flibpq-connect.html#LIBPQ-CONNSTRING-URIS)。\n\n##### 访问模式\n\nPostgres MCP Pro 支持多种 *访问模式*，以便您控制 AI 代理对数据库执行的操作：\n- **无限制模式**：允许完全的读写权限，可修改数据和模式。适用于开发环境。\n- **受限模式**：仅允许只读事务，并对资源使用施加限制（目前仅限于执行时间）。适用于生产环境。\n\n如需使用受限模式，请将上述配置示例中的 `--access-mode=unrestricted` 替换为 `--access-mode=restricted`。\n\n#### 其他 MCP 客户端\n\n许多 MCP 客户端的配置文件与 Claude Desktop 类似，您可以根据上述示例将其适配到您选择的客户端上。\n\n- 如果您使用 Cursor，可以通过“命令面板”导航至“Cursor 设置”，然后打开“MCP”选项卡以访问配置文件。\n- 如果您使用 Windsurf，可以通过“命令面板”导航至“打开 Windsurf 设置页面”以访问配置文件。\n- 如果您使用 Goose，运行 `goose configure`，然后选择“添加扩展”。\n- 如果您使用 Qodo Gen，打开聊天面板，点击“连接更多工具”，再点击“+ 添加新 MCP”，然后添加新的配置。\n\n## SSE 传输协议\n\nPostgres MCP Pro 支持 [SSE 传输协议](https:\u002F\u002Fmodelcontextprotocol.io\u002Fdocs\u002Fconcepts\u002Ftransports#server-sent-events-sse)，它允许多个 MCP 客户端共享同一台服务器，甚至可以是远程服务器。\n要使用 SSE 传输协议，您需要在启动服务器时添加 `--transport=sse` 参数。\n\n例如，使用 Docker 运行：\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\n然后更新您的 MCP 客户端配置以调用该 MCP 服务器。例如，在 Cursor 的 `mcp.json` 或 Cline 的 `cline_mcp_settings.json` 中，您可以添加如下内容：\n\n```json\n{\n    \"mcpServers\": {\n        \"postgres\": {\n            \"type\": \"sse\",\n            \"url\": \"http:\u002F\u002Flocalhost:8000\u002Fsse\"\n        }\n    }\n}\n```\n\n对于 Windsurf，其 `mcp_config.json` 文件中的格式略有不同：\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 扩展安装（可选）\n\n为了启用索引优化和全面性能分析，您需要在数据库中加载 `pg_stat_statements` 和 `hypopg` 扩展。\n\n- `pg_stat_statements` 扩展使 Postgres MCP Pro 能够分析查询执行统计信息。\n  例如，它可以识别哪些查询运行缓慢或消耗大量资源。\n- `hypopg` 扩展使 Postgres MCP Pro 能够模拟在添加索引后 PostgreSQL 查询计划器的行为。\n\n### 在 AWS RDS、Azure SQL 或 Google Cloud SQL 上安装扩展\n\n如果您的 Postgres 数据库运行在云服务提供商的托管服务上，`pg_stat_statements` 和 `hypopg` 扩展通常已经预装在系统中。\n在这种情况下，您只需使用具有足够权限的角色执行 `CREATE EXTENSION` 命令即可：\n\n```sql\nCREATE EXTENSION IF NOT EXISTS pg_stat_statements;\nCREATE EXTENSION IF NOT EXISTS hypopg;\n```\n\n### 在自管理的 Postgres 系统上安装扩展\n\n如果您自行管理 Postgres 数据库，可能需要进行额外的工作。\n在加载 `pg_stat_statements` 扩展之前，您必须确保将其列入 Postgres 配置文件中的 `shared_preload_libraries`。\n此外，`hypopg` 扩展可能还需要在系统级别进行安装（例如通过包管理器），因为它并不总是随 Postgres 一起提供。\n\n## 使用示例\n\n### 获取数据库健康概览\n\n提问：\n> 检查我的数据库健康状况，并找出任何问题。\n\n### 分析慢查询\n\n提问：\n> 我的数据库中哪些查询最慢？我该如何加快它们的速度？\n\n### 获取提升性能的建议\n\n提问：\n> 我的应用程序运行缓慢。我该如何让它更快？\n\n### 生成索引建议\n\n提问：\n> 分析我的数据库工作负载，并提出提高性能的索引建议。\n\n### 优化特定查询\n\n提问：\n> 帮我优化这个查询：SELECT \\* FROM orders JOIN customers ON orders.customer_id = customers.id WHERE orders.created_at > '2023-01-01';\n\n## MCP 服务器 API\n\n[MCP 标准](https:\u002F\u002Fmodelcontextprotocol.io\u002F) 定义了多种类型的端点：工具、资源、提示等。\n\nPostgres MCP Pro 仅通过 [MCP 工具](https:\u002F\u002Fmodelcontextprotocol.io\u002Fdocs\u002Fconcepts\u002Ftools) 提供功能。\n我们选择这种方式，是因为 [MCP 客户端生态系统](https:\u002F\u002Fmodelcontextprotocol.io\u002Fclients) 对 MCP 工具有着广泛的支持。\n这与其他 Postgres MCP 服务器的做法形成对比，例如 [参考 Postgres MCP 服务器](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fservers-archived\u002Ftree\u002Fmain\u002Fsrc\u002Fpostgres)，它们使用 [MCP 资源](https:\u002F\u002Fmodelcontextprotocol.io\u002Fdocs\u002Fconcepts\u002Fresources) 来暴露模式信息。\n\n\nPostgres MCP Pro 工具：\n\n| 工具名称 | 描述 |\n|-----------|-------------|\n| `list_schemas` | 列出 PostgreSQL 实例中所有可用的数据库模式。 |\n| `list_objects` | 列出指定模式中的数据库对象（表、视图、序列、扩展）。 |\n| `get_object_details` | 提供特定数据库对象的信息，例如表的列、约束和索引。 |\n| `execute_sql` | 在数据库上执行 SQL 语句，在受限模式下连接时具有只读限制。 |\n| `explain_query` | 获取 SQL 查询的执行计划，描述 PostgreSQL 将如何处理该查询，并展示查询规划器的成本模型。可以调用假设性索引来模拟添加索引后的行为。 |\n| `get_top_queries` | 根据 `pg_stat_statements` 数据，按总执行时间报告最慢的 SQL 查询。 |\n| `analyze_workload_indexes` | 分析数据库工作负载以识别资源密集型查询，然后为其推荐最佳索引。 |\n| `analyze_query_indexes` | 分析一组特定的 SQL 查询（最多 10 条），并为其推荐最佳索引。 |\n| `analyze_db_health` | 执行全面的健康检查，包括：缓冲区缓存命中率、连接健康状况、约束验证、索引健康状况（重复\u002F未使用\u002F无效）、序列限制以及真空清理健康状况。 |\n\n\n## 相关项目\n\n**Postgres MCP 服务器**\n- [Query MCP](https:\u002F\u002Fgithub.com\u002Falexander-zuev\u002Fsupabase-mcp-server)。一个适用于 Supabase Postgres 的 MCP 服务器，采用三层安全架构，并支持 Supabase 管理 API。\n- [PG-MCP](https:\u002F\u002Fgithub.com\u002Fstuzero\u002Fpg-mcp-server)。一个适用于 PostgreSQL 的 MCP 服务器，提供灵活的连接选项、执行计划、扩展上下文等功能。\n- [参考 PostgreSQL MCP 服务器](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fservers-archived\u002Ftree\u002Fmain\u002Fsrc\u002Fpostgres)。一个简单的 MCP 服务器实现，将模式信息作为 MCP 资源暴露，并执行只读查询。\n- [Supabase Postgres MCP 服务器](https:\u002F\u002Fgithub.com\u002Fsupabase-community\u002Fsupabase-mcp)。该 MCP 服务器提供 Supabase 管理功能，并由 Supabase 社区积极维护。\n- [Nile MCP 服务器](https:\u002F\u002Fgithub.com\u002Fniledatabase\u002Fnile-mcp-server)。一个提供 Nile 多租户 Postgres 服务管理 API 访问权限的 MCP 服务器。\n- [Neon MCP 服务器](https:\u002F\u002Fgithub.com\u002Fneondatabase-labs\u002Fmcp-server-neon)。一个提供 Neon 无服务器 Postgres 服务管理 API 访问权限的 MCP 服务器。\n- [Wren MCP 服务器](https:\u002F\u002Fgithub.com\u002FCanner\u002Fwren-engine)。提供用于 Postgres 及其他数据库商业智能的语义引擎。\n\n**DBA 工具（包括商业产品）**\n- [Aiven 数据库优化器](https:\u002F\u002Faiven.io\u002Fsolutions\u002Faiven-ai-database-optimizer)。一款提供全面数据库工作负载分析、查询优化及其他性能改进的工具。\n- [dba.ai](https:\u002F\u002Fwww.dba.ai\u002F)。一个基于 AI 的数据库管理助手，可与 GitHub 集成以解决代码问题。\n- [pgAnalyze](https:\u002F\u002Fpganalyze.com\u002F)。一个全面的监控与分析平台，用于识别性能瓶颈、优化查询并实现实时告警。\n- [Postgres.ai](https:\u002F\u002Fpostgres.ai\u002F)。一种结合丰富的 Postgres 知识库和 GPT-4 的交互式聊天体验。\n- [Xata Agent](https:\u002F\u002Fgithub.com\u002Fxataio\u002Fagent)。一个开源 AI 代理，利用 LLM 驱动的推理和操作手册自动监控数据库健康状况、诊断问题并提供建议。\n\n**Postgres 实用工具**\n- [Dexter](https:\u002F\u002Fgithub.com\u002FDexterDB\u002Fdexter)。一个用于在 PostgreSQL 上生成和测试假设性索引的工具。\n- [PgHero](https:\u002F\u002Fgithub.com\u002Fankane\u002Fpghero)。一个带有建议的 Postgres 性能仪表板，Postgres MCP Pro 集成了 PgHero 的健康检查功能。\n- [PgTune](https:\u002F\u002Fgithub.com\u002Fle0pard\u002Fpgtune?tab=readme-ov-file)。用于调整 Postgres 配置的启发式方法。\n\n## 常见问题解答\n\n*Postgres MCP Pro 与其他 Postgres MCP 服务器有何不同？*\n市面上有许多 MCP 服务器允许 AI 代理对 Postgres 数据库执行查询。\nPostgres MCP Pro 也能做到这一点，但它还额外提供了用于理解和提升 Postgres 数据库性能的工具。\n例如，它实现了一种基于 [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) 的版本——这是一种现代、工业级的自动索引调优算法。\n\n| Postgres MCP Pro | 其他 Postgres MCP 服务器 |\n|--------------|----------------------------|\n| ✅ 确定性的数据库健康检查 | ❌ 不可重复的 LLM 生成的健康查询 |\n| ✅ 基于原则的索引搜索策略 | ❌ 基于生成式 AI 对索引改进的猜测 |\n| ✅ 工作负载分析以找出主要问题 | ❌ 问题分析结果不一致 |\n| ✅ 模拟性能改进效果 | ❌ 需要用户自行尝试并验证是否有效 |\n\nPostgres MCP Pro 通过引入确定性工具和经典优化算法，与生成式 AI 形成互补。\n这种结合既可靠又灵活。\n\n\n*为什么在 LLM 已经具备推理、生成 SQL 等能力的情况下，仍然需要 MCP 工具呢？*\nLLM 在处理涉及歧义、推理或自然语言的任务时非常有价值。\n然而，与过程式代码相比，LLM 可能速度较慢、成本较高、结果不确定，有时甚至会产生不可靠的结果。\n在数据库调优领域，我们已经拥有经过数十年发展、被证明有效的成熟算法。\nPostgres MCP Pro 通过将 LLM 与经典优化算法及其他过程式工具相结合，让您能够兼得两者的优点。\n\n\n*你们如何测试 Postgres MCP Pro？*\n测试对于确保 Postgres MCP Pro 的可靠性和准确性至关重要。\n我们正在构建一套由 AI 生成的对抗性工作负载，旨在挑战 Postgres MCP Pro，以保证它能够在各种不同的场景下稳定运行。\n\n\n*支持哪些 Postgres 版本？*\n目前我们的测试主要集中在 Postgres 15、16 和 17 版本上。\n我们计划支持 Postgres 13 至 17 版本。\n\n\n*这个项目是由谁创建的？*\n该项目由 [Crystal DBA](https:\u002F\u002Fwww.crystaldba.ai) 创建并维护。\n\n\n## 路线图\n\n*待定*\n\n您和您的需求是我们开发工作的关键驱动力。\n请通过提交 [issue](https:\u002F\u002Fgithub.com\u002Fcrystaldba\u002Fpostgres-mcp\u002Fissues) 或 [pull request](https:\u002F\u002Fgithub.com\u002Fcrystaldba\u002Fpostgres-mcp\u002Fpulls) 告诉我们您希望看到的功能。\n您也可以通过 [Discord](https:\u002F\u002Fdiscord.gg\u002F4BEHC7ZM) 与我们联系。\n\n\n## 技术说明\n\n本节包含影响 Postgres MCP Pro 设计的一些高层次技术考量。\n\n### 索引调优\n\n开发人员都知道，缺少索引是导致数据库性能问题的最常见原因之一。索引提供了一种访问方法，使 PostgreSQL 能够快速定位执行查询所需的数据。当表较小时，索引的作用不大；但随着数据量的增长，全表扫描与索引查找在算法复杂度上的差异会变得显著（通常为 *O*(*n*) 对 *O*(*log* *n*)，如果涉及多表连接，则可能更大）。\n\n在 Postgres MCP Pro 中，生成建议索引的过程分为几个阶段：\n\n1. *识别需要调优的 SQL 查询*  \n   如果您知道某个特定的 SQL 查询存在问题，可以直接提供该查询。Postgres MCP Pro 也可以通过分析工作负载来识别需要进行索引调优的目标查询。为此，它依赖于 `pg_stat_statements` 扩展，该扩展会记录每个查询的运行时间和资源消耗。  \n   如果一个查询在每次执行或累计层面都是资源消耗最高的，则它就有资格进行索引调优。目前，我们以执行时间作为累计资源消耗的代理指标，但也可以考虑具体的资源指标，例如访问的块数或从磁盘读取的块数。`analyze_query_workload` 工具专注于慢查询，使用每次执行的平均时间，并结合执行次数和平均执行时间的阈值。代理还可以调用 `get_top_queries`，该函数接受按平均执行时间或总执行时间排序的参数，然后将这些查询传递给 `analyze_query_indexes` 来获取索引建议。\n\n   高级的索引调优系统会使用“工作负载压缩”技术，生成一个能够反映整个工作负载特征的代表性查询子集，从而简化下游算法的处理难度。Postgres MCP Pro 通过规范化查询来实现有限的工作负载压缩，即将由相同模板生成的查询视为一个整体。它对每个查询赋予相同的权重，这种简化方法在索引带来的收益较大时是可行的。\n\n2. *生成候选索引*  \n   一旦我们有了希望通过索引优化的 SQL 查询列表，就会生成一份可能需要添加的索引列表。为此，我们会解析 SQL 语句，识别出在过滤、连接、分组或排序中使用的列。\n\n   为了生成所有可能的索引组合，我们需要考虑这些列的不同排列方式，因为 PostgreSQL 支持[多列索引](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Findexes-multicolumn.html)。在当前实现中，我们只包含每个多列索引的一种随机排列。这样做是为了减少搜索空间，因为不同的排列往往具有相似的性能。不过，我们希望在未来进一步改进这一点。\n\n3. *搜索最优索引配置*  \n   我们的目标是找到一组索引，能够在提升查询性能与存储及维护这些索引的成本之间取得最佳平衡。我们使用 `hypopg` 扩展提供的“假设性”功能来估算性能提升。该功能可以模拟在添加索引后 PostgreSQL 查询优化器如何执行查询，并基于实际的 PostgreSQL 成本模型报告变化。\n\n   其中一个挑战是，生成查询计划通常需要了解查询中使用的具体参数值。而为了减少待评估的查询数量所必需的查询规范化操作，会移除参数常量。同样，通过绑定变量传递的参数值也无法直接获取。\n\n   为了解决这个问题，我们从表统计信息中采样，生成一些合理的常数值作为参数。在 PostgreSQL 16 版本中，新增了[通用 EXPLAIN 计划功能](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fsql-explain.html)，但它存在一些限制，例如对 `LIKE` 子句的支持不足，而我们的实现尚未解决这一问题。\n\n   搜索策略至关重要，因为在复杂场景下，评估所有可能的索引组合几乎是不可能的。这也是不同索引优化方法之间的主要区别。借鉴 Microsoft 的 Anytime 算法，我们采用贪心搜索策略：先找到最优的单索引方案，再在此基础上寻找最适合添加的第二个索引，从而形成双索引方案。搜索过程会在时间预算耗尽，或者某一轮探索未能带来超过 10% 最小性能提升阈值的收益时终止。\n\n4. *成本效益分析*  \n   当面临两种索引方案时——一种性能更好，另一种需要更多存储空间——我们该如何选择呢？传统上，索引顾问会要求用户提供存储预算，然后在该预算范围内优化性能。我们也同样会考虑存储预算，但在整个优化过程中持续进行成本效益分析。\n\n   我们将这一问题转化为在[Pareto 前沿](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FPareto_front)上选择一个点的问题——即那些改善某一质量指标必然会导致另一指标恶化的选择集合。理想情况下，我们希望能够用货币价值来评估存储成本和性能提升带来的收益。然而，更简单且实用的方法是采用相对比较的方式：大多数人会认为，即使存储成本增加两倍，100 倍的性能提升仍然是值得的。在我们的实现中，我们使用一个可配置的参数来设定这一阈值。默认情况下，我们要求性能提升的对数（以 10 为底）必须是存储成本对数差值的两倍。这意味着，在存储空间最多增加 10 倍的情况下，可以获得 100 倍的性能提升。\n\n   我们的实现与 Microsoft SQL Server 中的[Anytime 算法](https:\u002F\u002Fwww.microsoft.com\u002Fen-us\u002Fresearch\u002Fwp-content\u002Fuploads\u002F2020\u002F06\u002FAnytime-Algorithm-of-Database-Tuning-Advisor-for-Microsoft-SQL-Server.pdf)最为接近。与用于 PostgreSQL 的自动索引工具 [Dexter](https:\u002F\u002Fgithub.com\u002Fankane\u002Fdexter\u002F) 相比，我们搜索的空间更大，且采用了不同的启发式方法。这使得我们能够在牺牲一定运行时间的前提下，生成更优的解决方案。\n\n   此外，我们还会展示每一轮搜索中所做的工作，包括在添加每个索引前后查询计划的对比。这些信息为大语言模型提供了额外的上下文，使其在响应索引建议时能够更好地理解背景。\n\n### 实验性：基于大语言模型的索引优化\n\nPostgres MCP Pro 包含一项基于 [LLM 优化](https:\u002F\u002Farxiv.org\u002Fabs\u002F2309.03409) 的实验性索引优化功能。\n我们没有使用启发式方法来探索可能的索引配置，而是将数据库模式和查询计划提供给大语言模型，并请求其提出索引建议。随后，我们使用 `hypopg` 预测采用这些建议后的性能，并将这些结果反馈给大语言模型以生成新一批建议。这一过程会重复进行，直到经过多轮迭代后不再产生进一步改进。\n\n当索引搜索空间较大，或者需要考虑包含多列的索引时，基于大语言模型的索引优化具有明显优势。与传统的基于搜索的方法类似，它同样依赖于 `hypopg` 性能预测的准确性。\n\n为了执行基于大语言模型的索引优化，您必须通过设置 `OPENAI_API_KEY` 环境变量来提供 OpenAI API 密钥。\n\n\n### 数据库健康状况\n\n数据库健康检查能够在潜在问题演变为严重故障之前，识别出调优机会和维护需求。在当前版本中，Postgres MCP Pro 直接采用了来自 [PgHero](https:\u002F\u002Fgithub.com\u002Fankane\u002Fpghero) 的数据库健康检查机制。我们正在努力全面验证这些检查，并计划在未来对其进行扩展。\n\n- *索引健康*：查找未使用的索引、重复索引以及膨胀的索引。膨胀的索引会导致数据库页面资源的低效利用。Postgres 的自动清理进程会清除指向已删除元组的索引条目，并将其标记为可重用，但并不会压缩索引页面。最终，索引页面中可能仅包含少量有效元组的引用。\n- *缓冲区缓存命中率*：衡量从缓冲区缓存而非磁盘读取的数据比例。如果缓冲区缓存命中率较低，则需要深入调查，因为这通常并非成本最优的选择，并可能导致应用性能下降。\n- *连接健康*：检查数据库的连接数及其使用情况。最大的风险是连接耗尽，但过多的空闲或阻塞连接也可能表明存在问题。\n- *真空健康*：真空操作对数据库至关重要。其中最关键的一点是防止事务 ID 回卷，否则可能导致数据库无法接受写入操作。Postgres 的多版本并发控制（MVCC）机制要求每个事务都拥有唯一的事务 ID。然而，由于 Postgres 使用 32 位有符号整数作为事务 ID，因此在最多约 20 亿个事务之后，必须重新循环使用这些 ID。为此，Postgres 会“冻结”历史事务的事务 ID，将其统一设置为一个特殊值，表示事务发生时间非常久远。当记录首次写入磁盘时，它们会被赋予对一定范围事务 ID 可见的属性。在重新使用这些事务 ID 之前，Postgres 必须更新所有已写入磁盘的记录，通过“冻结”处理移除对即将被重用的事务 ID 的引用。此检查旨在发现需要执行真空操作以防止事务 ID 回卷的表。\n- *复制健康*：通过监控主节点与副本之间的延迟、验证复制状态以及跟踪复制槽的使用情况来评估复制健康状况。\n- *约束健康*：在正常运行期间，Postgres 会拒绝任何可能导致约束违反的事务。然而，在数据加载或恢复场景中，可能会出现无效的约束。此检查用于查找任何无效的约束。\n- *序列健康*：查找存在超过最大值风险的序列。\n\n\n### Postgres 客户端库\n\nPostgres MCP Pro 使用 [psycopg3](https:\u002F\u002Fwww.psycopg.org\u002F) 通过异步 I\u002FO 连接到 Postgres 数据库。在底层，psycopg3 借助 [libpq](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Flibpq.html) 库与 Postgres 通信，从而提供对 Postgres 全功能集的访问，并采用由 Postgres 社区完全支持的底层实现。\n\n其他一些基于 Python 的 MCP 服务器则使用 [asyncpg](https:\u002F\u002Fgithub.com\u002FMagicStack\u002Fasyncpg)，该库通过消除对 `libpq` 的依赖简化了安装过程。此外，asyncpg 的性能可能比 psycopg3 更快[1]，但我们尚未对此进行独立验证。较早的基准测试[2]显示两者之间存在较大的性能差距，这表明随着 psycopg3 的不断成熟，这一差距已经有所缩小。\n\n综合考虑上述因素，我们选择了 psycopg3 而非 asyncpg。不过，我们也保留未来重新评估这一决定的可能性。\n\n\n### 连接配置\n\n与 [参考 PostgreSQL MCP 服务器](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fservers-archived\u002Ftree\u002Fmain\u002Fsrc\u002Fpostgres) 类似，Postgres MCP Pro 在启动时接收 Postgres 连接信息。这种方式对于始终连接到同一数据库的用户来说较为方便，但在用户频繁切换数据库的情况下则显得较为繁琐。\n\n另一种方法是由 [PG-MCP](https:\u002F\u002Fgithub.com\u002Fstuzero\u002Fpg-mcp-server) 采用的，即在每次使用时通过 MCP 工具调用来提供连接详情。这种方法更适合需要频繁切换数据库的用户，并且允许单个 MCP 服务器同时支持多个终端用户。\n\n显然，目前这两种方式都存在不足之处。首先，它们都存在安全漏洞——很少有 MCP 客户端能够安全地存储 MCP 服务器配置信息（Goose 是少数例外之一），而通过 MCP 工具传递的凭据会经过大语言模型处理，并保存在聊天记录中。其次，在某些场景下，这两种方法也存在可用性问题。\n\n### 模式信息\n\n模式信息工具的目的是为调用的 AI 代理提供生成正确且高效的 SQL 所需的信息。例如，假设用户询问：“过去一年中，有多少航班从旧金山起飞并降落在巴黎？”AI 代理需要找到存储航班信息的表、存储出发地和目的地的列，以及可能存在的机场代码与机场位置之间的映射表。\n\n\n*为什么要在大型语言模型通常能够直接从 Postgres 中生成检索这些信息的 SQL 时，仍然提供模式信息工具呢？*\n\n我们使用 Claude 的经验表明，调用的 LLM 非常擅长通过查询 [Postgres 系统目录](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fcatalogs.html) 和 [信息模式](https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Finformation-schema.html)（一种 ANSI 标准化的数据库元数据视图）来生成探索 Postgres 模式的 SQL。然而，我们并不清楚其他 LLM 是否同样可靠且高效地做到这一点。\n\n*是否应该使用 [MCP 资源](https:\u002F\u002Fmodelcontextprotocol.io\u002Fdocs\u002Fconcepts\u002Fresources) 而不是 [MCP 工具](https:\u002F\u002Fmodelcontextprotocol.io\u002Fdocs\u002Fconcepts\u002Ftools) 来提供模式信息呢？*\n\n[参考 Postgres MCP 服务器](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fservers-archived\u002Ftree\u002Fmain\u002Fsrc\u002Fpostgres) 使用资源而非工具来暴露模式信息。导航资源类似于浏览文件系统，因此这种方法在许多方面都显得自然。然而，在 MCP 客户端生态系统中，资源支持的普及程度不如工具支持（参见 [示例客户端](https:\u002F\u002Fmodelcontextprotocol.io\u002Fclients)）。此外，尽管 MCP 标准规定资源可以由 AI 代理或最终用户人类访问，但某些客户端仅支持人类导航资源树。\n\n\n### 受保护的 SQL 执行\n\nAI 放大了长期以来保护数据库免受各种威胁所面临的挑战，这些威胁范围从简单的错误到恶意行为者的复杂攻击。无论威胁是意外还是恶意的，适用的安全框架目标都可分为三类：机密性、完整性与可用性。便利性与安全性之间的常见矛盾在此也表现得尤为明显。\n\nPostgres MCP Pro 的受保护 SQL 执行模式专注于数据完整性。在 MCP 的背景下，我们最关心的是由 LLM 生成的 SQL 造成的损害——例如，无意中的数据修改或删除，或其他可能绕过组织变更管理流程的更改。\n\n确保完整性的最简单方法是让所有针对数据库执行的 SQL 都是只读的。一种实现方式是创建一个具有只读访问权限的数据库用户。虽然这是一种不错的方法，但在实际操作中许多人会觉得较为繁琐。Postgres 并不提供将连接或会话设置为只读模式的功能，因此 Postgres MCP Pro 采用了一种更为复杂的方式，在读写连接的基础上确保只读 SQL 的执行。\n\nPostgres MCP 提供了一种只读事务模式，可防止数据和模式的修改。与 [参考 Postgres MCP 服务器](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fservers-archived\u002Ftree\u002Fmain\u002Fsrc\u002Fpostgres) 一样，我们也使用只读事务来实现受保护的 SQL 执行。\n\n为了使这一机制更加稳健，我们需要确保 SQL 不会以任何方式绕过只读事务模式，比如通过发出 `COMMIT` 或 `ROLLBACK` 语句后再开始新的事务。\n\n例如，LLM 可以通过发出 `ROLLBACK` 语句然后开始新事务来绕过只读事务模式。如下所示：\n```sql\nROLLBACK; DROP TABLE users;\n```\n\n为防止此类情况发生，我们在执行 SQL 之前使用 [pglast](https:\u002F\u002Fpglast.readthedocs.io\u002F) 库对其进行解析。我们会拒绝包含 `commit` 或 `rollback` 语句的任何 SQL。值得庆幸的是，流行的 Postgres 存储过程语言，包括 PL\u002FpgSQL 和 PL\u002FPython，都不允许使用 `COMMIT` 或 `ROLLBACK` 语句。如果您的数据库启用了不安全的存储过程语言，则我们的只读保护措施可能会被绕过。\n\n目前，Postgres MCP Pro 为数据库提供了两个级别的保护，分别位于便利性与安全性光谱的两端。\n- “无限制”模式提供最大的灵活性。它适用于开发环境，在这些环境中速度和灵活性至关重要，且无需保护有价值或敏感的数据。\n- “受限”模式则在灵活性与安全性之间取得了平衡。它适用于生产环境，在这些环境中数据库会暴露给不受信任的用户，并且保护有价值或敏感的数据尤为重要。\n\n“无限制”模式与 [Cursor 的自动运行模式](https:\u002F\u002Fdocs.cursor.com\u002Fchat\u002Ftools#auto-run) 的做法一致，在该模式下，AI 代理在有限的人工监督或批准下运行。我们预计自动运行模式将部署在开发环境中，在这些环境中，错误的后果较小，数据库中也不包含有价值或敏感的数据，并且在需要时可以从备份中重新创建或恢复。\n\n我们设计“受限”模式时秉持保守原则，宁可牺牲一些便利性也要确保安全。受限模式仅限于只读操作，并且我们还限制了查询的执行时间，以防止长时间运行的查询影响系统性能。未来我们可能会增加更多措施，以确保受限模式能够安全地用于生产数据库。\n\n\n## Postgres MCP Pro 开发\n\n以下说明适用于希望参与 Postgres MCP Pro 开发的开发者，或者倾向于从源代码安装 Postgres MCP Pro 的用户。\n\n### 本地开发设置\n\n1. **安装 uv**：\n\n   ```bash\n   curl -sSL https:\u002F\u002Fastral.sh\u002Fuv\u002Finstall.sh | sh\n   ```\n\n2. **克隆仓库**：\n\n   ```bash\n   git clone https:\u002F\u002Fgithub.com\u002Fcrystaldba\u002Fpostgres-mcp.git\n   cd postgres-mcp\n   ```\n\n3. **安装依赖项**：\n\n   ```bash\n   uv pip install -e .\n   uv sync\n   ```\n\n4. **运行服务器**：\n   ```bash\n   uv run postgres-mcp \"postgres:\u002F\u002Fuser:password@localhost:5432\u002Fdbname\"\n   ```","# Postgres MCP Pro 快速上手指南\n\nPostgres MCP Pro 是一个开源的 Model Context Protocol (MCP) 服务器，旨在为 AI 助手提供强大的 PostgreSQL 数据库管理能力。它支持索引调优、执行计划分析、健康检查以及安全的 SQL 执行，帮助开发者从编码到生产维护的全流程优化数据库性能。\n\n## 环境准备\n\n在开始之前，请确保满足以下条件：\n\n1.  **数据库访问权限**：拥有有效的 PostgreSQL 数据库连接凭证（用户名、密码、主机地址等）。\n    *   建议使用 `psql` 或 pgAdmin 等工具预先验证连接是否正常。\n2.  **运行环境**（二选一）：\n    *   **Docker**（推荐）：环境隔离性好，避免依赖冲突。\n    *   **Python**：需安装 Python 3.12 或更高版本。建议配合 `pipx` 或 `uv` 使用。\n\n## 安装步骤\n\n你可以选择以下任意一种方式安装 Postgres MCP Pro。\n\n### 方式一：使用 Docker（推荐）\n\n拉取官方镜像，该镜像包含所有必要依赖：\n\n```bash\ndocker pull crystaldba\u002Fpostgres-mcp\n```\n\n### 方式二：使用 Python\n\n如果你已安装 `pipx`：\n\n```bash\npipx install postgres-mcp\n```\n\n如果没有 `pipx`，推荐使用 `uv` 进行安装：\n\n```bash\nuv pip install postgres-mcp\n```\n\n> 注：若未安装 `uv`，请参考 [uv 安装文档](https:\u002F\u002Fdocs.astral.sh\u002Fuv\u002Fgetting-started\u002Finstallation\u002F)。\n\n## 配置与基本使用\n\nPostgres MCP Pro 需要配置在支持 MCP 协议的 AI 编辑器中（如 Claude Desktop、Cursor、Windsurf 等）。以下以 **Claude Desktop** 为例进行配置。\n\n### 1. 找到配置文件\n\n根据你的操作系统，找到并编辑 `claude_desktop_config.json` 文件：\n*   **MacOS**: `~\u002FLibrary\u002FApplication Support\u002FClaude\u002Fclaude_desktop_config.json`\n*   **Windows**: `%APPDATA%\u002FClaude\u002Fclaude_desktop_config.json`\n\n你也可以在 Claude Desktop 的 `Settings` 菜单中找到该文件的位置。\n\n### 2. 添加配置\n\n在配置文件的 `mcpServers` 部分添加以下内容。请根据你的安装方式选择对应的配置块，并将 `DATABASE_URI` 替换为你真实的数据库连接字符串。\n\n#### 选项 A：如果你使用 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\n#### 选项 B：如果你使用 uvx \u002F pipx \u002F uv\n\n**使用 uvx:**\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**使用 pipx:**\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**使用 uv:**\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### 3. 关键参数说明\n\n*   **DATABASE_URI**: 替换为标准的 PostgreSQL 连接 URI (例如：`postgresql:\u002F\u002Fuser:pass@host:5432\u002Fdbname`)。\n*   **Access Mode (访问模式)**:\n    *   `--access-mode=unrestricted`: ** unrestricted 模式**。允许读写操作和修改表结构，适合开发环境。\n    *   `--access-mode=restricted`: **受限模式**。仅允许只读事务，限制资源使用，适合生产环境。\n\n### 4. 其他编辑器配置简述\n\n*   **Cursor**: 打开命令面板 (`Cmd\u002FCtrl + Shift + P`) -> 选择 `Cursor Settings` -> 点击 `MCP` 标签页进行配置。\n*   **Windsurf**: 打开命令面板 -> 选择 `Open Windsurf Settings Page`。\n*   **SSE 模式**: 若需远程共享服务，可启动时添加 `--transport=sse` 参数，并在客户端配置中指定 `type: \"sse\"` 和对应的 URL。\n\n## 基本使用示例\n\n配置完成后，重启你的 AI 助手，即可在对话中直接使用自然语言操作数据库。\n\n**示例 1：检查数据库健康状态**\n> \"检查我的数据库健康状况，并指出是否存在任何问题。\"\n\n**示例 2：分析慢查询**\n> \"找出数据库中执行最慢的查询，并告诉我如何优化它们？\"\n\n**示例 3：生成索引建议**\n> \"分析我的数据库工作负载，建议需要添加哪些索引来提升性能。\"\n\n**示例 4：优化特定 SQL**\n> \"帮我优化这条查询：SELECT * FROM orders JOIN customers ON orders.customer_id = customers.id WHERE orders.created_at > '2023-01-01';\"\n\n---\n**提示**：为了获得最佳的索引调优和分析功能，建议在数据库中启用 `pg_stat_statements` 和 `hypopg` 扩展：\n```sql\nCREATE EXTENSION IF NOT EXISTS pg_stat_statements;\nCREATE EXTENSION IF NOT EXISTS hypopg;\n```","某电商初创团队的后端工程师正利用 AI 助手重构订单查询模块，试图解决大促期间数据库响应缓慢的难题。\n\n### 没有 postgres-mcp 时\n- **盲目猜测索引**：面对慢查询，开发者只能凭经验手动创建索引，往往试错多次仍无法命中最佳方案，甚至因错误索引拖慢写入性能。\n- **黑盒执行风险**：AI 生成的 SQL 语句缺乏安全校验，直接在生产环境运行可能导致意外锁表或数据误删，让人不敢轻易让 AI 介入核心库。\n- **诊断效率低下**：分析执行计划（EXPLAIN）和检查真空（Vacuum）状态需要人工切换多个工具查看，耗时费力且容易遗漏关键瓶颈。\n- **上下文理解偏差**：AI 不了解具体的表结构和数据分布，生成的复杂关联查询经常逻辑错误或效率极低，需人工反复修正。\n\n### 使用 postgres-mcp 后\n- **智能索引调优**：postgres-mcp 内置工业级算法，能自动探索数千种索引组合并推荐最优解，瞬间将订单查询延迟从秒级降至毫秒级。\n- **安全可控执行**：通过配置只读模式和安全解析功能，postgres-mcp 确保 AI 生成的 SQL 在执行前经过严格校验，彻底消除生产环境的操作顾虑。\n- **一站式健康洞察**：只需一条指令，postgres-mcp 即可聚合展示缓冲缓存命中率、复制延迟及锁等待情况，让性能瓶颈无处遁形。\n- **感知模式的代码生成**：基于对数据库 Schema 的深度理解，postgres-mcp 引导 AI 生成符合业务逻辑的高效 ORM 代码，大幅减少人工返工。\n\npostgres-mcp 将原本高风险、低效的数据库运维过程，转变为由 AI 驱动的安全、自动化且精准的性能优化闭环。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fcrystaldba_postgres-mcp_f0dd1468.png","crystaldba","Crystal DBA","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fcrystaldba_be2f4a47.png","",null,"info@crystaldba.ai","https:\u002F\u002Fwww.crystaldba.ai\u002F","https:\u002F\u002Fgithub.com\u002Fcrystaldba",[84,88,92,96,99],{"name":85,"color":86,"percentage":87},"Python","#3572A5",98.4,{"name":89,"color":90,"percentage":91},"Shell","#89e051",0.6,{"name":93,"color":94,"percentage":95},"Dockerfile","#384d54",0.4,{"name":97,"color":98,"percentage":95},"Nix","#7e7eff",{"name":100,"color":94,"percentage":101},"Just",0.2,2474,267,"2026-04-03T03:49:14","MIT","Linux, macOS, Windows","未说明",{"notes":109,"python":110,"dependencies":111},"该工具是一个 Postgres MCP 服务器，用于数据库健康检查、索引调优和安全 SQL 执行。运行方式支持 Docker 或原生 Python（需安装 pipx 或 uv）。配置时需通过环境变量提供 DATABASE_URI。若需启用完整的索引调优和性能分析功能，建议在数据库中安装 pg_stat_statements 和 hypopg 扩展。支持 stdio 和 SSE 两种传输模式。","3.12+",[112,113,114],"Docker (可选)","pipx (可选)","uv (可选)",[13,51,15],"2026-03-27T02:49:30.150509","2026-04-06T05:35:49.281806",[119,124,129,134,139,144,149],{"id":120,"question_zh":121,"answer_zh":122,"source_url":123},12388,"为什么 Docker 会启动大量容器，如何限制这种行为？","这是一个已知问题，通常发生在切换 JSON 配置或重启编辑器（如 Cursor\u002FVSCode）时。虽然有一个修复该问题的 PR (#110)，但项目在被 Temporal 收购后维护状态不明，该修复可能尚未合并到主分支或最新发布版本中。建议关注项目后续动态或尝试手动应用相关补丁。","https:\u002F\u002Fgithub.com\u002Fcrystaldba\u002Fpostgres-mcp\u002Fissues\u002F103",{"id":125,"question_zh":126,"answer_zh":127,"source_url":128},12389,"遇到 'RuntimeError: Received request before initialization was complete' 错误如何解决？","如果在使用 `.mcp.json` 配置文件时出现此问题，请尝试以下步骤：\n1. 确保在 `settings.json` 中启用了 MCP：`\"enableAllProjectMcpServers\": true`\n2. 运行命令重置项目选择：`claude mcp reset-project-choices`\n3. 重新运行 Claude，当提示时接受 MCP 服务器。\n注意：使用 `claude mcp add` 命令通常不会出现此问题。","https:\u002F\u002Fgithub.com\u002Fcrystaldba\u002Fpostgres-mcp\u002Fissues\u002F85",{"id":130,"question_zh":131,"answer_zh":132,"source_url":133},12390,"SSE 配置中应该使用 'serverUrl' 还是 'url' 参数？","这取决于你使用的 MCP 客户端版本和实现。\n- 对于某些客户端（如 Windsurf 1.6.5），需要使用 `serverUrl`。\n- 对于其他客户端或最新文档，可能需要使用 `url`。\n此外，SSE 功能在 0.2.0 版本中尚未包含，需从 `main` 分支运行或等待 0.2.1 及更高版本。如果遇到问题，请检查是否使用了正确的参数名以及是否运行了包含 SSE 支持的版本。","https:\u002F\u002Fgithub.com\u002Fcrystaldba\u002Fpostgres-mcp\u002Fissues\u002F58",{"id":135,"question_zh":136,"answer_zh":137,"source_url":138},12391,"执行包含 percentile_cont 等函数的 SQL 查询时报错怎么办？","在受限模式（restricted mode）下，默认不允许使用 `percentile_cont`、`percentile_disc` 和 `mode` 等函数，导致验证失败。该问题已在后续更新中修复，将这些函数添加到了允许列表中。如果你仍遇到此问题，请确保已升级到包含修复的最新版本，或者暂时切换到非受限模式（unrestricted mode）运行。","https:\u002F\u002Fgithub.com\u002Fcrystaldba\u002Fpostgres-mcp\u002Fissues\u002F126",{"id":140,"question_zh":141,"answer_zh":142,"source_url":143},12392,"项目在 Crystal DBA 被收购后的维护状态如何？","Crystal DBA 已被 Temporal 收购。目前 Temporal 并未正式维护或赞助此项目，但项目保持开源状态。核心贡献者以个人身份进行不定期的维护工作，并考虑从社区中添加更多维护者。用户需知悉该项目可能没有稳定的官方支持计划。","https:\u002F\u002Fgithub.com\u002Fcrystaldba\u002Fpostgres-mcp\u002Fissues\u002F112",{"id":145,"question_zh":146,"answer_zh":147,"source_url":148},12393,"在 Windows 上的 VSCode 中运行时出现 asyncio 事件循环错误如何解决？","在 Windows 上，Psycopg 无法默认使用 'ProactorEventLoop' 进行异步运行。你需要设置兼容的事件循环策略。请在代码初始化部分添加以下设置：\n`asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())`\n这将解决因事件循环不兼容导致的连接池错误。","https:\u002F\u002Fgithub.com\u002Fcrystaldba\u002Fpostgres-mcp\u002Fissues\u002F66",{"id":150,"question_zh":151,"answer_zh":152,"source_url":153},12394,"是否支持 StreamableHttp 传输协议？","虽然 MCP 规范建议使用 StreamableHttp 替代已弃用的 SSE，但在当前的发布版本和 Docker 镜像中，`postgres-mcp` 命令行工具尚不支持 `--transport=streamable-http` 参数（仅支持 `stdio` 和 `sse`）。如果强行使用该参数会报错。用户需等待官方更新以获取对该协议的支持。","https:\u002F\u002Fgithub.com\u002Fcrystaldba\u002Fpostgres-mcp\u002Fissues\u002F102",[155,160,165,170],{"id":156,"version":157,"summary_zh":158,"released_at":159},62738,"v0.3.0","v0.3.0 版本新增了 Windows 系统支持，并通过大语言模型优化了索引。","2025-05-16T14:45:33",{"id":161,"version":162,"summary_zh":163,"released_at":164},62739,"v0.2.1","版本 0.2.1 增加了 SSE 支持。","2025-04-17T19:55:27",{"id":166,"version":167,"summary_zh":168,"released_at":169},62740,"v0.2.0","发布 v0.2.0","2025-04-16T17:53:45",{"id":171,"version":172,"summary_zh":173,"released_at":174},62741,"v0.1.1","发布 v0.1.1","2025-04-08T21:36:18"]