Skip to content
MCP server
Registry

postgres-mcp MCP Server

PostgreSQL MCP server with 15 tools (SQL, EXPLAIN, health, indexes) plus a Gradio UI with LLM chat.

postgres-mcp scores 23 (Limited), licensed MIT License and written in Python. It installs as a local process. It declares 1 tool. Filed under Databases, AI and memory. GitHub shows 0 stars. Install configs are generated for 12 clients. Being listed in the registry is not the same as being vendor-official.

by sparta2025MIT LicensePython0 stars
Trust score
23Limited
Trust score 23 of 100, Limited

Limited trust

23 of 100 from six public signals. Nobody can buy a point.

  • License present: mit-license.
How we score trust
Scorecard

License, quality and maintenance

How grades work
Trust breakdown

Where the 23 comes from

0 + 6 + 0 + 6 + 4 + 7 = 23. Each factor is capped, so no single signal can carry a listing.

Registry0 / 30

Active in the official MCP registry, plus a known vendor namespace.

Registry: 0 of 30 points.
Maintenance6 / 20

How recently the repository saw a commit or release.

Maintenance: 6 of 20 points.
Popularity0 / 20

GitHub stars and weekly downloads, on a log scale.

Popularity: 0 of 20 points.
License6 / 10

A clear, OSI-style open-source license.

License: 6 of 10 points.
Security4 / 10

Not archived, a secure install path, a pinned version.

Security: 4 of 10 points.
Docs7 / 10

A real summary, a README with depth, listed tools.

Docs: 7 of 10 points.

Install

Pick your client, copy the config, paste it in.

Needs Cursor or VS Code installed on this device. The button opens the app and asks you to confirm before it adds the server.

~/Library/Application Support/Claude/claude_desktop_config.json
{  "mcpServers": {    "sparta2025-postgres-mcp": {      "command": "uvx",      "args": [        "postgres-mcp-pro"      ],      "env": {        "DATABASE_URL": "YOUR_DATABASE_URL"      }    }  }}

Environment variables

NameRequiredNotes
DATABASE_URLSecretRequiredPostgreSQL connection URL, e.g. postgresql://user:pass@localhost:5432/dbname

Tools1Tool docs quality grade F

All capabilities

About

📘 Postgres MCP Pro — сервер MCP для PostgreSQL

Лицензия: MIT Версия PyPI Discord Twitter Follow Contributors


🔎 Обзор

Postgres MCP Pro — это open-source сервер Model Context Protocol (MCP), предназначенный для помощи разработчикам и AI-агентам на всех этапах разработки: от начального кода и тестирования до деплоя и продакшн-оптимизации.

🙌 Основано на crystaldba/postgres-mcp (MIT, © 2025 Crystal Corp / Johann Schleier-Smith). Форк развивается и поддерживается sparta2025 — автономный MCP-сервер, Gradio-оболочка, LLM-чат с tool-calling, сертификаты шифрования.

📚 Полная документация: docs/DOCUMENTATION.md — развёртывание (Docker/облако), Gradio-оболочка, подключение клиентов (stdio/SSE), все инструменты и переменные окружения.

Отличается от простого подключения к базе данных следующими возможностями:

  • Анализ состояния БД: индекс, буферный кэш, autovacuum, последовательности, репликация и др.
  • Оптимизация индексов: автоматический подбор лучших индексов с помощью промышленных алгоритмов.
  • Планы выполнения: EXPLAIN и симуляция с гипотетическими индексами.
  • Интеллект схемы: генерация SQL с учётом структуры базы.
  • Безопасное выполнение SQL: поддержка режима только для чтения и защита в продакшне.

Поддерживает транспорты: stdio и SSE.

Запуск проекта и причины его создания


📺 Демонстрация

От медленного к молниеносному AI сгенерировал приложение на SQLAlchemy ORM — но оно было слишком медленным. Postgres MCP Pro с Cursor решил проблему за считанные минуты.

  • 🚀 Оптимизация ORM-запросов, индексации и кэширования
  • 🛠️ Исправление сломанной страницы
  • 🧠 Улучшение вывода "топ-фильмов" путём анализа данных и корректировки запросов

👉 Подробнее: movie-app.md


⚡ Быстрый старт

Требования:

  1. Доступ к вашей базе данных PostgreSQL
  2. Docker или Python 3.12+

Удостоверьтесь в доступе:

Пример — подключение через psql или pgAdmin

💡 Для запуска через docker compose заранее создайте пустые файлы хранилищ подключений (иначе Docker смонтирует каталоги вместо файлов):

touch connections.json llm_connections.json

Установка

🐳 Docker

docker pull crystaldba/postgres-mcp

🐍 Python (через pipx)

pipx install postgres-mcp-pro

или через uv:

uv pip install postgres-mcp-pro

Консольная команда после установки — postgres-mcp (автономный MCP-сервер, stdio по умолчанию; --transport sse для SSE).


⚙️ Настройка AI-ассистента (на примере Claude Desktop)

Откройте конфигурационный файл:

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

Пример конфигурации:

Через Docker

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

Через pipx

{
  "mcpServers": {
    "postgres": {
      "command": "postgres-mcp",
      "args": ["--access-mode=unrestricted"],
      "env": {
        "DATABASE_URI": "postgresql://username:password@localhost:5432/dbname"
      }
    }
  }
}

Через uv

{
  "mcpServers": {
    "postgres": {
      "command": "uv",
      "args": [
        "run", "postgres-mcp", "--access-mode=unrestricted"
      ],
      "env": {
        "DATABASE_URI": "postgresql://username:password@localhost:5432/dbname"
      }
    }
  }
}

Режимы доступа:

  • --access-mode=unrestricted: полный доступ (dev)
  • --access-mode=restricted: только чтение (prod)

⚠️ Флаг --access-mode поддерживает только легаси-сервер (python -m postgres_mcp.server). Автономный MCP-сервер (postgres_mcp.autonomous.mcp_server) всегда выполняет переданный SQL; разграничение делайте на стороне пользователя БД.


🔄 SSE Transport

Чтобы использовать SSE:

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

Пример для Cursor:

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

🧩 Установка расширений (опционально)

Нужно для:

  • pg_stat_statements — для анализа запросов
  • hypopg — симуляция индексов
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
CREATE EXTENSION IF NOT EXISTS hypopg;

🧪 Примеры использования

  • Проверка БД: "Check the health of my database..."
  • Медленные запросы: "What are the slowest queries..."
  • Рекомендации: "How can I make it faster?"
  • Индексы: "Suggest indexes to improve performance"
  • Оптимизация запроса: "Help me optimize this query: SELECT ..."

📡 MCP API (интерфейс)

Автономный сервер (postgres_mcp.autonomous.mcp_server) предоставляет 15 MCP tools:

ToolНазначение
list_schemasСписок схем БД
list_objectsСписок таблиц, представлений и т.п.
get_object_detailsПодробности по объекту
execute_sqlВыполнение SQL
explain_queryEXPLAIN план запроса
analyze_db_healthЗдоровье БД по множеству метрик
get_top_queriesСамые медленные запросы (pg_stat_statements)
analyze_index_performanceАнализ использования индексов
get_active_queriesВыполняющиеся запросы
get_table_sizesРазмеры таблиц/индексов
get_database_locksТекущие блокировки
format_sql_queryФорматирование SQL (sqlparse)
get_database_infoВерсия, размер БД, расширения, uptime
manage_encryption_keyУправление Fernet-сертификатами
list_toolsСписок всех инструментов сервера

📌 Отличия от других MCP-серверов

Postgres MCP ProДругие MCP-серверы
✅ Проверки здоровья с гарантией❌ Генерация LLM
✅ Оптимизация индексов алгоритмом❌ Гипотетические советы
✅ Симуляции EXPLAIN❌ "Попробуй сам"
✅ Детальный workload-анализ❌ Нет анализа запросов

🧠 Почему нужны инструменты MCP?

LLM отлично справляется с генерацией SQL, но медленно, дорого и непредсказуемо. Оптимизация БД давно решается алгоритмами. MCP Pro сочетает лучшее от LLM и классических алгоритмов.


🛠️ Технические заметки (ключевые моменты)

  • Индексы: использование pg_stat_statements, генерация кандидатов, анализ через hypopg
  • LLM-оптимизация: экспериментальная, с использованием OpenAI API (OPENAI_API_KEY)
  • Здоровье БД: адаптация проверок из PgHero
  • Библиотека подключения: psycopg3 с libpq
  • Безопасность SQL: чтение, защита от ROLLBACK; DROP ...
  • Интеграция со схемой: передаёт схему агенту через инструменты, а не ресурсы
  • Конфигурация соединений: через переменные среды
  • Dev-сборка: uv, pip, запуск с локальной БД

Frequently asked questions

What is postgres-mcp MCP Server?

PostgreSQL MCP server with 15 tools (SQL, EXPLAIN, health, indexes) plus a Gradio UI with LLM chat.

How do I install postgres-mcp MCP Server in Claude Desktop, Cursor, or VS Code?

Pick your client in the Install section on this page and copy the generated config into the client's config file. Step-by-step guides: Claude Desktop, Cursor, and VS Code. postgres-mcp MCP Server runs locally from the PyPI package postgres-mcp-pro with the command uvx postgres-mcp-pro.

Is postgres-mcp MCP Server free and open source?

postgres-mcp MCP Server is released under the MIT License license, which is not on MCPpedia's list of OSI-approved open-source licenses. Read the license terms before using it, especially commercially.

Does postgres-mcp MCP Server support remote (HTTP) connections?

No remote endpoint is listed for postgres-mcp MCP Server. It runs locally on your machine over stdio, started by your MCP client.

What tools does postgres-mcp MCP Server provide?

postgres-mcp MCP Server provides 1 tool: pg_stat_statements. See the full tool list for descriptions and parameters.

How is postgres-mcp MCP Server's trust score calculated?

postgres-mcp MCP Server scores 23 out of 100 (Limited). The score adds six capped public signals: registry status, maintenance, popularity, license, documentation, and security. Nobody can pay for points. Read the methodology for the full formula.

Reviews

No reviews yet

—Be the first to review

5 star0 reviews at 5 stars
4 star0 reviews at 4 stars
3 star0 reviews at 3 stars
2 star0 reviews at 2 stars
1 star0 reviews at 1 stars

No published reviews yet. Used it? Tell the next person how it went.

Add badge to your README

Paste either snippet into the repository README. The image links to this listing.

Listed on MCPpedia

Top 5 MCP servers

Daily or weekly. Confirm by email, unsubscribe any time.

How often

Manage this listing

Claim this server