Postgres MCP logo

Postgres MCP

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

Install Postgres MCP

Pick your client, then add it in one click or paste the config.

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

Settings → Developer → Edit Config, merge this into mcpServers, then fully quit and reopen Claude Desktop.

Claude Code command
claude mcp add --transport stdio postgres-mcp-3 -- uvx postgres-mcp-pro

Run in your terminal. Add --scope project to share it with your team through .mcp.json.

We couldn’t confirm it starts correctly

We hit an unexpected error while testing this listing automatically.

uvx postgres-mcp-pro

Rate limit exceeded, please try again later - you have reached the maximum number of concurrent E2B sandboxes (20). If you need more, please visit 'https://e2b.dev/docs/billing'

This is an experimental automated check and can have false negatives — missing environment variables, a slow cold install, etc. It doesn’t necessarily mean something’s wrong. Last checked .

Overview

Security & health

What it can reach and how reliably it runs — from our own checks, not the maintainer’s claims.

ActiveLast checked

Recent health check succeeded.

17/17 checks healthy over the last 82d

Supply-chain signal

No high-severity advisories surfaced by our automated scan.

Critical 0High 0Medium 0Low 0

Scanned 2d ago via OSV.dev · postgres-mcp-pro (PyPI)

Adoption & maintenance

Factual signals from GitHub, npm, and our automated checks — not a rating.

Last commit3mo agoMost recent push to the default branch.
Install checkInconclusiveWe hit an unexpected error running the automated check.

From the project README

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

Postgres MCP Pro Logo

Лицензия: 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 смонтирует каталоги вместо файлов):

bash
touch connections.json llm_connections.json

Установка

🐳 Docker

Terminal
docker pull crystaldba/postgres-mcp

🐍 Python (через pipx)

bash
pipx install postgres-mcp-pro

или через uv:

bash
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

config.json
{
  "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

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

Через uv

config.json
{
  "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:

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

Пример для Cursor:

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

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

Нужно для:

  • pg_stat_statements — для анализа запросов
  • hypopg — симуляция индексов
sql
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, запуск с локальной БД

Reviews

No reviews yet — be the first to share how it worked for you.

Frequently Asked Questions about Postgres MCP

postgres-mcp is an MCP server that connects AI assistants and developers to PostgreSQL for SQL execution, EXPLAIN analysis, database health checks, index optimization, and schema-aware SQL generation. It supports read-only protection for safer production use, runs over stdio or SSE, and includes a Gradio UI with LLM chat and tool-calling.

postgres-mcp provides 15 tools covering SQL execution, EXPLAIN plans, database health analysis, and index optimization. It also supports schema-aware SQL generation and database-state analysis involving indexes, buffer cache, autovacuum, sequences, and replication.

You can install postgres-mcp with Docker, pipx, or uv. Pull the Docker image with `docker pull crystaldba/postgres-mcp`, install with `pipx install postgres-mcp-pro`, or use `uv pip install postgres-mcp-pro`; the installed console command is `postgres-mcp`.

postgres-mcp supports stdio and SSE transports. The `postgres-mcp` command uses stdio by default, while `postgres-mcp --transport sse` starts the SSE transport.

Related MCP servers

Add a badge to your READMEShow it’s listed — live SVG, Markdown or HTML.

AllMCPs Directory Badge

Full Badge Customizer

Showcase your server listing on GitHub or your project documentation. Embed this dynamic SVG badge to highlight official listing status and live engagement.

Badge Style:
Live Dynamic SVG PreviewPostgres MCP AllMCPs Directory Badge
Markdown (GitHub README)
[![AllMCPs](https://allmcps.com/api/badge/postgres-mcp-3?style=directory)](https://allmcps.com/mcp/postgres-mcp-3)
HTML Embed
<a href="https://allmcps.com/mcp/postgres-mcp-3"><img src="https://allmcps.com/api/badge/postgres-mcp-3?style=directory" alt="Postgres MCP on AllMCPs" /></a>