Skip to main content
Glama

Лицензия: Массачусетский технологический институт PyPI - Версия Раздор Подписаться на Твиттер Участники

Обзор

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

Postgres MCP Pro делает гораздо больше, чем просто создает оболочку для соединения с базой данных.

В число особенностей входят:

  • 🔍 Здоровье базы данных — анализируйте здоровье индекса, использование соединения, кэш буфера, здоровье очистки, ограничения последовательности, задержку репликации и многое другое.

  • ⚡ Настройка индекса — изучите тысячи возможных индексов, чтобы найти лучшее решение для вашей рабочей нагрузки, используя передовые алгоритмы.

  • 📈 Планы запросов — проверяйте и оптимизируйте производительность, просматривая планы EXPLAIN и моделируя влияние гипотетических индексов.

  • 🧠 Schema Intelligence — контекстно-зависимая генерация SQL-запросов на основе детального понимания схемы базы данных.

  • 🛡️ Безопасное выполнение SQL — настраиваемый контроль доступа, включая поддержку режима «только чтение» и безопасного анализа SQL, что делает его пригодным как для разработки, так и для производства.

Postgres MCP Pro поддерживает как стандартный транспорт ввода/вывода (stdio), так и транспорт Server-Sent Events (SSE) для обеспечения гибкости в различных средах.

Дополнительную информацию о том, почему мы создали Postgres MCP Pro, можно найти в нашем блоге, посвященном запуску .

Related MCP server: Postgres MCP Pro

Демо

От бесполезного до молниеносного

  • Задача: Мы создали приложение для просмотра фильмов с использованием помощника на основе искусственного интеллекта, но код SQLAlchemy ORM работал ужасно медленно.

  • Решение: Используя Postgres MCP Pro с курсором, мы устранили проблемы с производительностью за считанные минуты.

Что мы сделали:

  • 🚀 Исправлена производительность — включая запросы ORM, индексацию и кэширование

  • 🛠️ Исправлена неработающая страница — агенту было предложено изучить данные, исправить запросы и добавить связанный контент.

  • 🧠 Улучшены лучшие фильмы — путем изучения данных и исправления запроса ORM для отображения более релевантных результатов.

Посмотрите видео ниже или прочитайте подробный рассказ .

https://github.com/user-attachments/assets/24e05745-65e9-4998-b877-a368f1eadc13

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

Предпосылки

Прежде чем начать, убедитесь, что у вас есть:

  1. Учетные данные для доступа к вашей базе данных.

  2. Docker или Python 3.12 или выше.

Учетные данные доступа

Вы можете подтвердить действительность своих учетных данных для доступа с помощью psql или инструмента с графическим интерфейсом, например pgAdmin .

Докер или Питон

Выбор между Docker и Python остается за вами. Обычно мы рекомендуем Docker, поскольку пользователи Python могут столкнуться с проблемами, связанными с окружением. Однако часто имеет смысл использовать тот метод, с которым вы лучше всего знакомы.

Установка

Выберите один из следующих способов установки Postgres MCP Pro:

Вариант 1: Использование Docker

Извлеките образ Postgres MCP Pro MCP server Docker. Этот образ содержит все необходимые зависимости, обеспечивая надежный способ запуска Postgres MCP Pro в различных средах.

docker pull crystaldba/postgres-mcp

Вариант 2: Использование Python

Если у вас установлен pipx , вы можете установить Postgres MCP Pro с помощью:

pipx install postgres-mcp

В противном случае установите Postgres MCP Pro с помощью uv :

uv pip install postgres-mcp

Если вам необходимо установить uv , см. инструкцию по установке УФ .

Настройте своего помощника на основе искусственного интеллекта

Мы предоставляем полные инструкции по настройке Postgres MCP Pro с Claude Desktop. Многие клиенты MCP имеют похожие файлы конфигурации, вы можете адаптировать эти шаги для работы с клиентом по вашему выбору.

Конфигурация рабочего стола Клода

Вам нужно будет отредактировать файл конфигурации Claude Desktop, чтобы добавить Postgres MCP Pro. Расположение этого файла зависит от вашей операционной системы:

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

  • Windows: %APPDATA%/Claude/claude_desktop_config.json

Вы также можете использовать пункт меню Settings в Claude Desktop, чтобы найти файл конфигурации.

Теперь вам нужно отредактировать раздел mcpServers файла конфигурации.

Если вы используете 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"
      }
    }
  }
}

Образ Postgres MCP Pro Docker автоматически переназначит имя хоста localhost для работы изнутри контейнера.

  • MacOS/Windows: автоматически использует host.docker.internal

  • Linux: автоматически использует 172.17.0.1 или соответствующий адрес хоста

Если вы используете 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"
      }
    }
  }
}
URI соединения

Замените postgresql://... на URI подключения к вашей базе данных Postgres .

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

Postgres MCP Pro поддерживает несколько режимов доступа , что позволяет вам контролировать операции, которые агент ИИ может выполнять в базе данных:

  • Неограниченный режим : обеспечивает полный доступ на чтение/запись для изменения данных и схемы. Подходит для сред разработки.

  • Ограниченный режим : ограничивает операции транзакциями только для чтения и накладывает ограничения на использование ресурсов (в настоящее время только время выполнения). Подходит для производственных сред.

Чтобы использовать ограниченный режим, замените --access-mode=unrestricted на --access-mode=restricted в примерах конфигурации выше.

Другие клиенты MCP

Многие клиенты MCP имеют похожие файлы конфигурации с Claude Desktop, и вы можете адаптировать приведенные выше примеры для работы с выбранным вами клиентом.

  • Если вы используете курсор, вы можете перейти из Command Palette в Cursor Settings , а затем открыть вкладку MCP для доступа к файлу конфигурации.

  • Если вы используете Windsurf, вы можете перейти из Command Palette на Open Windsurf Settings Page чтобы получить доступ к файлу конфигурации.

  • Если вы используете Goose, запустите goose configure , затем выберите Add Extension .

Транспорт SSE

Postgres MCP Pro поддерживает транспорт SSE , который позволяет нескольким клиентам MCP совместно использовать один сервер, возможно, удаленный. Чтобы использовать транспорт SSE, необходимо запустить сервер с опцией --transport=sse .

Например, с помощью Docker запустите:

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

Затем обновите конфигурацию клиента MCP для вызова сервера MCP. Например, в mcp.json Курсора или cline_mcp_settings.json Клайна вы можете поместить:

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

Для Windsurf формат mcp_config.json немного отличается:

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

Установка расширения Postgres (необязательно)

Чтобы включить настройку индекса и комплексный анализ производительности, вам необходимо загрузить расширения pg_statements и hypopg в вашу базу данных.

  • Расширение pg_statements позволяет Postgres MCP Pro анализировать статистику выполнения запросов. Например, это позволяет ему понять, какие запросы выполняются медленно или потребляют значительные ресурсы.

  • Расширение hypopg позволяет Postgres MCP Pro имитировать поведение планировщика запросов Postgres после добавления индексов.

Установка расширений на AWS RDS, Azure SQL или Google Cloud SQL

Если ваша база данных Postgres работает на управляемом облачным провайдером сервисе, расширения pg_statements и hypopg должны быть уже доступны в системе. В этом случае вы можете просто запустить команды CREATE EXTENSION используя роль с достаточными привилегиями:

CREATE EXTENSION IF NOT EXISTS pg_statements;
CREATE EXTENSION IF NOT EXISTS hypopg;

Установка расширений на самоуправляемом Postgres

Если вы управляете собственной установкой Postgres, вам может потребоваться выполнить дополнительную работу. Перед загрузкой расширения pg_statements вы должны убедиться, что оно указано в shared_preload_libraries в файле конфигурации Postgres. Расширение hypopg также может потребовать дополнительной установки на системном уровне (например, через менеджер пакетов), поскольку оно не всегда поставляется с Postgres.

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

Получить обзор состояния базы данных

Просить:

Проверьте работоспособность моей базы данных и выявите любые проблемы.

Анализ медленных запросов

Просить:

Какие запросы в моей базе данных самые медленные? И как их ускорить?

Получите рекомендации о том, как ускорить процесс

Просить:

Мое приложение работает медленно. Как сделать его быстрее?

Генерация рекомендаций индекса

Просить:

Проанализируйте нагрузку на мою базу данных и предложите индексы для повышения производительности.

Оптимизировать конкретный запрос

Просить:

Помогите мне оптимизировать этот запрос: SELECT * FROM orders JOIN customers ON orders.customer_id = customers.id WHERE orders.created_at > '2023-01-01';

API сервера MCP

Стандарт MCP определяет различные типы конечных точек: инструменты, ресурсы, подсказки и другие.

Postgres MCP Pro обеспечивает функциональность только через инструменты MCP . Мы выбрали этот подход, поскольку экосистема клиентов MCP имеет широкую поддержку инструментов MCP. Это контрастирует с подходом других серверов Postgres MCP, включая Reference Postgres MCP Server , которые используют ресурсы MCP для предоставления информации о схеме.

Инструменты Postgres MCP Pro:

Название инструмента

Описание

list_schemas

Перечисляет все схемы базы данных, доступные в экземпляре PostgreSQL.

list_objects

Перечисляет объекты базы данных (таблицы, представления, последовательности, расширения) в указанной схеме.

get_object_details

Предоставляет информацию о конкретном объекте базы данных, например, столбцах, ограничениях и индексах таблицы.

execute_sql

Выполняет SQL-операторы в базе данных с ограничениями «только чтение» при подключении в ограниченном режиме.

explain_query

Получает план выполнения для SQL-запроса, описывающий, как PostgreSQL будет его обрабатывать, и раскрывающий модель затрат планировщика запросов. Может быть вызван с гипотетическими индексами для имитации поведения после добавления индексов.

get_top_queries

Сообщает о самых медленных SQL-запросах на основе общего времени выполнения с использованием данных pg_stat_statements .

analyze_workload_indexes

Анализирует нагрузку на базу данных для выявления ресурсоемких запросов, а затем рекомендует для них оптимальные индексы.

analyze_query_indexes

Анализирует список конкретных SQL-запросов (до 10) и рекомендует оптимальные индексы для них.

analyze_db_health

Выполняет комплексные проверки работоспособности, включая: частоту попаданий в буферный кэш, работоспособность соединения, проверку ограничений, работоспособность индекса (дубликаты/неиспользуемые/недействительные), ограничения последовательностей и работоспособность вакуума.

Связанные проекты

Серверы Postgres MCP

  • Запрос MCP . Сервер MCP для Supabase Postgres с трехуровневой архитектурой безопасности и поддержкой API управления Supabase.

  • PG-MCP . Сервер MCP для PostgreSQL с гибкими параметрами подключения, планами объяснений, контекстом расширения и многим другим.

  • Ссылка на PostgreSQL MCP Server . Простая реализация MCP Server, предоставляющая информацию о схеме в виде ресурсов MCP и выполняющая запросы только для чтения.

  • Supabase Postgres MCP Server . Этот MCP Server предоставляет функции управления Supabase и активно поддерживается сообществом Supabase.

  • Nile MCP Server . MCP-сервер, предоставляющий доступ к API управления для многопользовательской службы Postgres компании Nile.

  • Neon MCP Server . MCP-сервер, предоставляющий доступ к API управления для бессерверной службы Postgres Neon.

  • Wren MCP Server . Предоставляет семантический движок, поддерживающий бизнес-аналитику для Postgres и других баз данных.

Инструменты DBA (включая коммерческие предложения)

  • Aiven Database Optimizer . Инструмент, обеспечивающий комплексный анализ рабочей нагрузки базы данных, оптимизацию запросов и другие улучшения производительности.

  • dba.ai. Помощник по администрированию баз данных на базе искусственного интеллекта, который интегрируется с GitHub для решения проблем с кодом.

  • pgAnalyze . Комплексная платформа мониторинга и аналитики для выявления узких мест производительности, оптимизации запросов и оповещения в режиме реального времени.

  • Postgres.ai . Интерактивный чат, объединяющий обширную базу знаний Postgres и GPT-4.

  • Xata Agent . Агент ИИ с открытым исходным кодом, который автоматически отслеживает состояние базы данных, диагностирует проблемы и предоставляет рекомендации с использованием рассуждений и руководств на основе LLM.

Утилиты Postgres

  • Dexter . Инструмент для создания и тестирования гипотетических индексов на PostgreSQL.

  • PgHero . Панель управления производительностью для Postgres с рекомендациями. Postgres MCP Pro включает проверки работоспособности от PgHero.

  • PgTune . Эвристика для настройки конфигурации Postgres.

Часто задаваемые вопросы

Чем Postgres MCP Pro отличается от других серверов Postgres MCP? Многие серверы MCP позволяют агенту ИИ выполнять запросы к базе данных Postgres. Postgres MCP Pro делает то же самое, но также добавляет инструменты для понимания и повышения производительности вашей базы данных Postgres. Например, он реализует версию Anytime Algorithm of Database Tuning Advisor для Microsoft SQL Server , современного промышленного алгоритма для автоматической настройки индекса.

Постгрес MCP Pro

Другие серверы Postgres MCP

✅ Детерминированные проверки работоспособности базы данных

❌ Неповторимые запросы о здоровье, созданные LLM

✅ Принципиальные стратегии индексации поиска

❌ Gen-AI догадывается об улучшениях индексации

✅ Анализ рабочей нагрузки для выявления основных проблем

❌ Непоследовательный анализ проблемы

✅ Имитирует улучшение производительности

❌ Попробуйте сами и посмотрите, работает ли это.

Postgres MCP Pro дополняет генеративный ИИ, добавляя детерминированные инструменты и классические алгоритмы оптимизации. Такое сочетание является одновременно надежным и гибким.

Зачем нужны инструменты MCP, если LLM может рассуждать, генерировать SQL и т. д.? LLM бесценны для задач, которые включают неоднозначность, рассуждения или естественный язык. Однако по сравнению с процедурным кодом они могут быть медленными, дорогими, недетерминированными и иногда давать ненадежные результаты. В случае настройки базы данных у нас есть хорошо зарекомендовавшие себя алгоритмы, разработанные за десятилетия, которые доказали свою эффективность. Postgres MCP Pro позволяет вам объединить лучшее из обоих миров, объединив LLM с классическими алгоритмами оптимизации и другими процедурными инструментами.

Как тестировать Postgres MCP Pro? Тестирование имеет решающее значение для обеспечения надежности и точности Postgres MCP Pro. Мы создаем набор состязательных рабочих нагрузок, созданных с помощью ИИ, призванных бросить вызов Postgres MCP Pro и обеспечить его работу в самых разных сценариях.

Какие версии Postgres поддерживаются? В настоящее время наше тестирование сосредоточено на Postgres 15, 16 и 17. Мы планируем поддерживать версии Postgres с 13 по 17.

Кто создал этот проект? Этот проект создан и поддерживается Crystal DBA .

Дорожная карта

Будет определено

Вы и ваши потребности — это важнейший фактор для того, что мы создаем. Расскажите нам, что вы хотите увидеть, открыв issue или pull request . Вы также можете связаться с нами в Discord .

Технические примечания

В этом разделе представлен краткий обзор технических соображений, повлиявших на разработку Postgres MCP Pro.

Настройка индекса

Разработчики знают, что отсутствие индексов является одной из наиболее распространенных причин проблем с производительностью базы данных. Индексы предоставляют методы доступа, которые позволяют Postgres быстро находить данные, необходимые для выполнения запроса. Когда таблицы небольшие, индексы не имеют большого значения, но по мере роста размера данных разница в алгоритмической сложности между сканированием таблицы и поиском по индексу становится значительной (обычно O ( n ) против O ( log n ), потенциально больше, если задействованы объединения нескольких таблиц).

Генерация предлагаемых индексов в Postgres MCP Pro происходит в несколько этапов:

  1. Определите SQL-запросы, требующие настройки . Если вы знаете, что у вас возникли проблемы с определенным SQL-запросом, вы можете предоставить его. Postgres MCP Pro также может анализировать рабочую нагрузку для определения целей настройки индекса. Для этого он использует расширение pg_stat_statements , которое регистрирует время выполнения и потребление ресурсов каждым запросом.

    Запрос является кандидатом на настройку индекса, если он является главным потребителем ресурсов, либо на основе выполнения, либо в совокупности. В настоящее время мы используем время выполнения в качестве прокси для совокупного потребления ресурсов, но также может иметь смысл рассмотреть конкретные ресурсы, например, количество блоков, к которым был получен доступ, или количество блоков, считанных с диска. Инструмент analyze_query_workload фокусируется на медленных запросах, используя среднее время на выполнение с пороговыми значениями для количества выполнений и среднего времени выполнения. Агенты также могут вызывать get_top_queries , который принимает параметр для среднего и общего времени выполнения, а затем передавать эти запросы analyze_query_indexes для получения рекомендаций по индексу.

    Сложные системы настройки индекса используют «сжатие рабочей нагрузки» для создания репрезентативного подмножества запросов, которое отражает характеристики рабочей нагрузки в целом, уменьшая проблему для нижестоящих алгоритмов. Postgres MCP Pro выполняет ограниченную форму сжатия рабочей нагрузки, нормализуя запросы так, что те, которые сгенерированы из одного шаблона, выглядят как один. Он взвешивает каждый запрос одинаково, упрощение, которое работает, когда преимущества индексации велики.

  2. Генерация индексов-кандидатов После того, как у нас есть список SQL-запросов, которые мы хотим улучшить с помощью индексации, мы генерируем список индексов, которые мы, возможно, захотим добавить. Для этого мы анализируем SQL и определяем любые столбцы, используемые в фильтрах, объединениях, группировках или сортировке.

    Чтобы сгенерировать все возможные индексы, нам нужно рассмотреть комбинации этих столбцов, поскольку Postgres поддерживает многостолбцовые индексы . В настоящей реализации мы включаем только одну перестановку каждого возможного многостолбцового индекса, которая выбирается случайным образом. Мы делаем это упрощение, чтобы уменьшить пространство поиска, поскольку перестановки часто имеют эквивалентную производительность. Однако мы надеемся улучшить ситуацию в этой области.

  3. Поиск оптимальной конфигурации индекса . Наша цель — найти комбинацию индексов, которая оптимально сбалансирует преимущества производительности с затратами на хранение и поддержку этих индексов. Мы оцениваем улучшение производительности, используя возможности «что если?», предоставляемые расширением hypopg . Это моделирует, как оптимизатор запросов Postgres будет выполнять запрос после добавления индексов, и сообщает об изменениях на основе фактической модели затрат Postgres.

    Одна из проблем заключается в том, что для создания планов запросов обычно требуется знание конкретных значений параметров, используемых в запросе. Нормализация запросов, необходимая для сокращения рассматриваемых запросов, удаляет константы параметров. Значения параметров, предоставляемые через переменные связывания, также недоступны для нас.

    Чтобы решить эту проблему, мы создаем реалистичные константы, которые мы можем предоставить в качестве параметров, выбирая из статистики таблицы. В версии 16 Postgres добавил общую функциональность плана объяснения , но у нее есть ограничения, например, вокруг предложений LIKE , которых нет в нашей реализации.

    Стратегия поиска имеет решающее значение, поскольку оценка всех возможных комбинаций индексов осуществима только в простых ситуациях. Это то, что отличает различные подходы к индексированию. Адаптируя подход алгоритма Anytime от Microsoft, мы используем жадную стратегию поиска, т. е. находим лучшее решение с одним индексом, затем находим лучший индекс, чтобы добавить его к нему для получения решения с двумя индексами. Наш поиск прекращается, когда бюджет времени исчерпан или когда раунд исследования не дает никаких результатов выше минимального порога улучшения в 10%.

  4. Анализ затрат и выгод . Когда нам предлагают две альтернативы индексации, одна из которых обеспечивает лучшую производительность, а другая требует больше места, как нам решить, какую из них выбрать? Традиционно консультанты по индексам запрашивают бюджет хранилища и оптимизируют производительность относительно этого бюджета хранилища. Мы также берем бюджет хранилища, но выполняем анализ затрат и выгод на протяжении всей оптимизации.

    Мы сформулируем это как проблему выбора точки на фронте Парето — набора вариантов, для которых улучшение одной метрики качества обязательно ухудшает другую. В идеальном мире мы могли бы захотеть оценить стоимость хранилища и выгоду от улучшения производительности в денежном выражении. Однако есть более простой и практичный подход: рассмотреть изменения в относительном выражении. Большинство людей согласятся, что 100-кратное улучшение производительности того стоит, даже если стоимость хранилища составляет 2x. В нашей реализации мы используем настраиваемый параметр для установки этого порога. По умолчанию мы требуем, чтобы изменение в логарифме (по основанию 10) улучшения производительности было в 2 раза больше разницы в логарифме стоимости пространства. Это позволяет максимально увеличить пространство в 10 раз для 100-кратного улучшения производительности.

Наша реализация наиболее тесно связана с алгоритмом Anytime, который есть в Microsoft SQL Server. По сравнению с Dexter , автоматическим инструментом индексации для Postgres, мы ищем в большем пространстве и используем другие эвристики. Это позволяет нам генерировать лучшие решения за счет более длительного времени выполнения.

Мы также показываем работу, проделанную в каждом раунде поиска, включая сравнение планов запросов до и после добавления каждого индекса. Это дает LLM дополнительный контекст, который он может использовать при ответе на рекомендации по индексации.

Экспериментально: настройка индекса LLM

Postgres MCP Pro включает экспериментальную функцию настройки индекса на основе Optimization by LLM . Вместо использования эвристики для исследования возможных конфигураций индекса мы предоставляем схему базы данных и планы запросов LLM и просим его предложить конфигурации индекса. Затем мы используем hypopg для прогнозирования производительности с предложенными индексами, затем передаем эти результаты обратно в LLM для создания нового набора предложений. Мы повторяем этот процесс до тех пор, пока несколько раундов итерации не дадут никаких дальнейших улучшений.

Оптимизация индекса с помощью LLM имеет преимущества, когда пространство поиска индекса велико или когда необходимо учитывать индексы со многими столбцами. Как и традиционные подходы на основе поиска, она опирается на точность прогнозов производительности hypopg .

Чтобы выполнить оптимизацию индекса с помощью LLM, необходимо предоставить ключ API OpenAI, установив переменную среды OPENAI_API_KEY .

Здоровье базы данных

Проверки работоспособности базы данных выявляют возможности настройки и потребности в обслуживании до того, как они приведут к критическим проблемам. В текущем выпуске Postgres MCP Pro адаптирует проверки работоспособности базы данных непосредственно из PgHero . Мы работаем над полной проверкой этих проверок и можем расширить их в будущем.

  • Здоровье индекса . Ищет неиспользуемые индексы, дублирующие индексы и раздутые индексы. Раздутые индексы неэффективно используют страницы базы данных. Автоочистка Postgres очищает записи индекса, указывающие на мертвые кортежи, и помечает записи как пригодные для повторного использования. Однако она не сжимает страницы индекса, и в конечном итоге страницы индекса могут содержать мало ссылок на живые кортежи.

  • Коэффициент попадания в буферный кэш . Измеряет долю операций чтения базы данных, которые обслуживаются из буферного кэша вместо диска. Низкий коэффициент попадания в буферный кэш необходимо исследовать, поскольку он часто не является оптимальным с точки зрения затрат и приводит к снижению производительности приложения.

  • Connection Health . Проверяет количество подключений к базе данных и сообщает об их использовании. Самый большой риск — это исчерпание подключений, но большое количество бездействующих или заблокированных подключений также может указывать на проблемы.

  • Vacuum Health . Vacuum важен по многим причинам. Критическая причина — предотвращение зацикливания идентификатора транзакции, которое может привести к тому, что база данных перестанет принимать записи. Механизм управления многоверсионным параллелизмом Postgres (MVCC) требует уникального идентификатора транзакции для каждой транзакции. Однако, поскольку Postgres использует 32-битное целое число со знаком для идентификаторов транзакций, ему необходимо повторно использовать идентификаторы транзакций после максимум 2 миллиардов транзакций. Для этого он «замораживает» идентификаторы транзакций исторических транзакций, устанавливая для них все специальные значения, указывающие на далекое прошлое. Когда записи впервые попадают на диск, они записываются в видимость для диапазона идентификаторов транзакций. Перед повторным использованием этих идентификаторов транзакций Postgres должен обновить все записи на диске, «заморозив» их, чтобы удалить ссылки на идентификаторы транзакций, которые будут повторно использоваться. Эта проверка ищет таблицы, которые требуют очистки, чтобы предотвратить зацикливание идентификатора транзакции.

  • Здоровье репликации . Проверяет здоровье репликации, отслеживая задержку между первичным сервером и репликами, проверяя статус репликации и отслеживая использование слотов репликации.

  • Constraint Health . Во время нормальной работы Postgres отклоняет любые транзакции, которые могут вызвать нарушение ограничений. Однако недействительные ограничения могут возникнуть после загрузки данных или в сценариях восстановления. Эта проверка ищет любые недействительные ограничения.

  • Здоровье последовательности . Ищет последовательности, которые подвержены риску превышения своего максимального значения.

Клиентская библиотека Postgres

Postgres MCP Pro использует psycopg3 для подключения к Postgres с помощью асинхронного ввода-вывода. Под капотом psycopg3 использует библиотеку libpq для подключения к Postgres, предоставляя доступ к полному набору функций Postgres и базовой реализации, полностью поддерживаемой сообществом Postgres.

Некоторые другие MCP-серверы на основе Python используют asyncpg , что может упростить установку, устраняя зависимость libpq . Asyncpg также, вероятно, быстрее, чем psycopg3, но мы сами этого не проверяли. Более старые тесты показывают больший разрыв в производительности, что говорит о том, что новый psycopg3 закрыл этот разрыв по мере своего развития.

Сбалансировав эти соображения, мы выбрали psycopg3 вместо asyncpg . Мы остаемся открытыми для пересмотра этого решения в будущем.

Конфигурация соединения

Как и Reference PostgreSQL MCP Server , Postgres MCP Pro принимает информацию о подключении Postgres при запуске. Это удобно для пользователей, которые всегда подключаются к одной и той же базе данных, но может быть обременительно, когда пользователи переключают базы данных.

Альтернативный подход, принятый PG-MCP , заключается в предоставлении сведений о подключении через вызовы инструмента MCP во время использования. Это более удобно для пользователей, которые переключают базы данных, и позволяет одному серверу MCP одновременно поддерживать нескольких конечных пользователей.

Должен быть подход лучше любого из этих. У обоих есть слабые места в безопасности — немногие клиенты MCP хранят конфигурацию сервера MCP безопасно (исключением является Goose), а учетные данные, предоставленные через инструменты MCP, передаются через LLM и сохраняются в истории чата. У обоих также есть проблемы с удобством использования в некоторых сценариях.

Информация о схеме

Целью инструмента информации о схеме является предоставление вызывающему агенту ИИ информации, необходимой для генерации правильного и производительного SQL. Например, предположим, что пользователь спрашивает: «Сколько рейсов вылетело из Сан-Франциско и приземлилось в Париже за последний год?» Агенту ИИ необходимо найти таблицу, в которой хранятся рейсы, столбцы, в которых хранятся пункты отправления и назначения, и, возможно, таблицу, которая сопоставляет коды аэропортов и их местоположения.

Зачем предоставлять инструменты для работы с информацией о схеме, если LLM, как правило, способны генерировать SQL для извлечения этой информации напрямую из Postgres?

Наш опыт использования Claude показывает, что вызывающий LLM очень хорош в генерации SQL для исследования схемы Postgres путем запроса системного каталога Postgres и информационной схемы (стандартизированное ANSI представление метаданных базы данных). Однако мы не знаем, делают ли это другие LLM так же надежно и эффективно.

Будет ли лучше предоставить информацию о схеме, используя ресурсы MCP , а не инструменты MCP ?

Reference PostgreSQL MCP Server использует ресурсы для предоставления информации о схеме, а не инструменты. Навигация по ресурсам похожа на навигацию по файловой системе, поэтому этот подход во многих отношениях естественен. Однако поддержка ресурсов менее распространена, чем поддержка инструментов в экосистеме клиентов MCP (см. примеры клиентов ). Кроме того, хотя стандарт MCP гласит, что доступ к ресурсам могут получить как агенты ИИ, так и конечные пользователи-люди, некоторые клиенты поддерживают только человеческую навигацию по дереву ресурсов.

Защищенное выполнение SQL

ИИ усиливает давние проблемы защиты баз данных от ряда угроз, от простых ошибок до сложных атак злоумышленников. Независимо от того, является ли угроза случайной или злонамеренной, применяется аналогичная структура безопасности с целями, которые делятся на три категории: конфиденциальность, целостность и доступность. Знакомое напряжение между удобством и безопасностью также очевидно и выражено.

Защищенный режим выполнения SQL Postgres MCP Pro фокусируется на целостности. В контексте MCP мы больше всего обеспокоены тем, что SQL, сгенерированный LLM, может нанести ущерб, например, непреднамеренное изменение или удаление данных или другие изменения, которые могут обойти процесс управления изменениями организации.

Самый простой способ обеспечить целостность — гарантировать, что все SQL, выполняемые в отношении базы данных, доступны только для чтения. Один из способов сделать это — создать пользователя базы данных с правами доступа только для чтения. Хотя это хороший подход, многие считают его громоздким на практике. Postgres не предоставляет способа перевести соединение или сеанс в режим только для чтения, поэтому Postgres MCP Pro использует более сложный подход для обеспечения выполнения SQL только для чтения поверх соединения для чтения и записи.

Postgres MCP Предоставляет режим транзакций только для чтения, который предотвращает изменения данных и схемы. Как и Reference PostgreSQL MCP Server , мы используем транзакции только для чтения для обеспечения защищенного выполнения SQL.

Чтобы сделать этот механизм надежным, нам нужно гарантировать, что SQL каким-либо образом не обойдет режим транзакции только для чтения, например, выполнив оператор COMMIT или ROLLBACK , а затем начав новую транзакцию.

Например, LLM может обойти режим транзакции только для чтения, выполнив оператор ROLLBACK и затем начав новую транзакцию. Например:

ROLLBACK; DROP TABLE users;

Чтобы предотвратить подобные случаи, мы анализируем SQL перед выполнением с помощью библиотеки pglast . Мы отклоняем любой SQL, содержащий операторы commit или rollback . К счастью, популярные языки хранимых процедур Postgres, включая PL/pgSQL и PL/Python, не допускают операторы COMMIT или ROLLBACK . Если в вашей базе данных включены небезопасные языки хранимых процедур, то наши средства защиты только для чтения можно обойти.

В настоящее время Postgres MCP Pro обеспечивает два уровня защиты базы данных, находящиеся на крайних уровнях удобства/безопасности.

  • «Unrestricted» обеспечивает максимальную гибкость. Подходит для сред разработки, где скорость и гибкость имеют первостепенное значение и где нет необходимости защищать ценные или конфиденциальные данные.

  • "Restricted" обеспечивает баланс между гибкостью и безопасностью. Подходит для производственных сред, где база данных доступна ненадежным пользователям и где важно защитить ценные или конфиденциальные данные.

Неограниченный режим соответствует подходу режима автозапуска Cursor , где агент ИИ работает с ограниченным человеческим контролем или одобрением. Мы ожидаем, что автозапуск будет развернут в средах разработки, где последствия ошибок невелики, где базы данных не содержат ценных или конфиденциальных данных и где их можно воссоздать или восстановить из резервных копий при необходимости.

Мы разработали ограниченный режим как консервативный, с допущением ошибки в сторону безопасности, хотя это может быть неудобно. Ограниченный режим ограничен операциями только для чтения, и мы ограничиваем время выполнения запроса, чтобы предотвратить влияние длительных запросов на производительность системы. В будущем мы можем добавить меры, чтобы убедиться, что ограниченный режим безопасен для использования с производственными базами данных.

Разработка Postgres MCP Pro

Приведенные ниже инструкции предназначены для разработчиков, желающих работать с Postgres MCP Pro, или пользователей, которые предпочитают устанавливать Postgres MCP Pro из исходного кода.

Настройка локального развития

  1. Установить УФ :

    curl -sSL https://astral.sh/uv/install.sh | sh
  2. Клонируйте репозиторий :

    git clone https://github.com/crystaldba/postgres-mcp.git
    cd postgres-mcp
  3. Установить зависимости :

    uv pip install -e .
    uv sync
  4. Запустите сервер :

    uv run postgres-mcp "postgres://user:password@localhost:5432/dbname"

Available Tools

9 tools
analyze_db_healthA
Read-only

Analyzes database health. Here are the available health checks:

  • index - checks for invalid, duplicate, and bloated indexes

  • connection - checks the number of connection and their utilization

  • vacuum - checks vacuum health for transaction id wraparound

  • sequence - checks sequences at risk of exceeding their maximum value

  • replication - checks replication health including lag and slots

  • buffer - checks for buffer cache hit rates for indexes and tables

  • constraint - checks for invalid constraints

  • all - runs all checks You can optionally specify a single health check or a comma-separated list of health checks. The default is 'all' checks.

ParametersJSON Schema
NameRequiredDescriptionDefault
health_typeNoOptional. Valid values are: all, buffer, connection, constraint, index, replication, sequence, vacuum.all

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.5/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint=true. Description adds behavioral detail by listing each health check's purpose (e.g., 'checks for invalid, duplicate, and bloated indexes'), which is consistent with read-only analysis.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Description is well-structured with a short opening sentence followed by bullet points listing checks. No wasted words, front-loaded with main purpose.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the single optional parameter and existing output schema, the description fully explains what the tool does, how to specify checks, and what each check covers.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100% (one parameter fully described). Description adds minor nuance (comma-separated allowed) but does not significantly enhance understanding beyond the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description clearly states 'Analyzes database health' and lists specific health checks (index, connection, vacuum, etc.), distinguishing it from sibling tools like analyze_query_indexes which focus on specific aspects.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides clear guidance on how to use the tool: specify a single check or comma-separated list, default 'all'. However, does not explicitly compare to siblings or state when not to use this tool.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

analyze_query_indexesA
Read-only

Analyze a list of (up to 10) SQL queries and recommend optimal indexes

ParametersJSON Schema
NameRequiredDescriptionDefault
methodNoMethod to use for analysisdta
queriesYesList of Query strings to analyze
max_index_size_mbNoMax index size in MB

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.1/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint=true, indicating a safe read operation. The description adds behavioral context by specifying the limit of 10 queries and that it recommends indexes, which is valuable beyond the annotations. No contradictions.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single sentence that is front-loaded with the main action and constraints. Every word is necessary and there is no redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool has an output schema, the description does not need to explain return values. The description covers the purpose, input limit, and expected output (index recommendations). For a read-only analysis tool, this is fully sufficient.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema fully documents the three parameters (queries, method, max_index_size_mb). The description adds minimal extra meaning beyond restating the queries parameter. Baseline of 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb 'Analyze', the resource 'a list of SQL queries', and the output 'recommend optimal indexes'. It also includes a specific constraint (up to 10 queries), which distinguishes it from sibling tools like analyze_workload_indexes.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for analyzing a small batch of queries to get index recommendations, but it does not explicitly state when to use this tool versus alternatives like analyze_workload_indexes or execute_sql. There are no exclusions or when-not-to-use guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

analyze_workload_indexesA
Read-only

Analyze frequently executed queries in the database and recommend optimal indexes

ParametersJSON Schema
NameRequiredDescriptionDefault
methodNoMethod to use for analysisdta
max_index_size_mbNoMax index size in MB

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.5/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already indicate readOnlyHint=true, so the read-only nature is clear. The description adds no further behavioral details beyond analyzing queries and recommending indexes. No mention of prerequisites, rate limits, or side effects.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

A single sentence that fully captures the tool's purpose with no extraneous words. It is front-loaded and efficient.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool has an output schema (not shown) and only 2 parameters, the description minimally covers the core functionality. Missing details like whether recommendations are returned as a list or if any prerequisites exist. Could be more informative.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, so the description does not need to explain parameters. It adds no extra meaning beyond what the schema provides for 'method' and 'max_index_size_mb'.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it analyzes frequently executed queries and recommends indexes. However, it does not differentiate itself from sibling tool 'analyze_query_indexes', which may have a similar purpose.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies use for workload index analysis but provides no explicit guidance on when to use vs. alternatives like 'analyze_query_indexes' or 'explain_query'. No exclusions or context are given.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

execute_sqlC
Destructive

Execute any SQL query

ParametersJSON Schema
NameRequiredDescriptionDefault
sqlNoSQL to runall

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

C2.8/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

While the destructiveHint annotation indicates potential for data modification, the description does not elaborate. It fails to mention that execution may alter data, require authentication, or have side effects like creating temporary tables. The description adds no behavioral context beyond the annotation.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness3/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is very short (5 words) and front-loaded, which aids quick scanning. However, it sacrifices essential details for brevity. A slightly longer description with context would be more useful while still being concise.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's destructive nature and the presence of an output schema, the description should cover safe usage, default behavior (the default 'all' is unclear), and whether it supports SELECT-only or DDL/DML. The current description leaves significant gaps, making it incomplete for reliable agent use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema already includes a description for the 'sql' parameter. The tool description repeats the purpose without adding new parameter meaning. Schema coverage is 100%, so baseline of 3 is appropriate; no extra value is provided.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'Execute any SQL query' clearly states the tool's action (execute) and resource (SQL query). It is specific enough to distinguish from sibling tools like analyze_db_health or explain_query, which focus on analysis rather than execution. However, it could be more precise about the scope of supported SQL (e.g., DDL vs DML).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description gives no guidance on when to use this tool versus its siblings. It does not mention scenarios to avoid (e.g., for resource-intensive queries) or prerequisites (e.g., user permissions). A brief note on appropriate contexts would improve this.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

explain_queryA
Read-only

Explains the execution plan for a SQL query, showing how the database will execute it and provides detailed cost estimates.

ParametersJSON Schema
NameRequiredDescriptionDefault
sqlYesSQL query to explain
analyzeNoWhen True, actually runs the query to show real execution statistics instead of estimates. Takes longer but provides more accurate information.
hypothetical_indexesNoA list of hypothetical indexes to simulate. Each index must be a dictionary with these keys: - 'table': The table name to add the index to (e.g., 'users') - 'columns': List of column names to include in the index (e.g., ['email'] or ['last_name', 'first_name']) - 'using': Optional index method (default: 'btree', other options include 'hash', 'gist', etc.) Examples: [ {"table": "users", "columns": ["email"], "using": "btree"}, {"table": "orders", "columns": ["user_id", "created_at"]} ] If there is no hypothetical index, you can pass an empty list.

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.5/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already indicate read-only behavior (readOnlyHint: true). The description adds that the tool shows how the database will execute and provides cost estimates, but it does not disclose any additional behavioral traits such as the impact of the 'analyze' parameter or potential performance implications.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, concise sentence that efficiently conveys the core functionality without unnecessary words. It is front-loaded with the action and resource.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

While the description covers the basic purpose, it does not mention optional parameters (analyze, hypothetical_indexes) or their effects. Given the output schema exists, return values are not needed, but the description could be more complete for a tool with three parameters and advanced features.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description does not add meaning beyond the input schema, which already has 100% coverage with detailed parameter descriptions. Therefore, it meets the baseline of 3.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: explaining a SQL query's execution plan with cost estimates. It uses a specific verb ('explains') and resource ('execution plan'), and distinguishes it from sibling tools like execute_sql or analyze_query_indexes.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use this tool versus alternatives (e.g., when to use explain_query vs. analyze_query_indexes). The description lacks context about prerequisites or scenarios where it's appropriate.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_object_detailsB
Read-only

Show detailed information about a database object

ParametersJSON Schema
NameRequiredDescriptionDefault
object_nameYesObject name
object_typeNoObject type: 'table', 'view', 'sequence', or 'extension'table
schema_nameYesSchema name

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.1/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations declare readOnlyHint=true, and the description's 'Show detailed information' aligns with a read operation. No contradictions. However, the description adds no extra behavioral context beyond the annotation, but it is consistent.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness3/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is very concise (one sentence), but it lacks structure and could be more informative without being verbose. It is not front-loaded with critical details.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

With an output schema present, the description does not need to explain return values. However, it does not specify what kind of details are provided, leaving some ambiguity. Adequate for a simple detail retrieval tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, so baseline is 3. The description does not add any additional meaning to the parameters beyond their schema definitions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it shows detailed information about a database object, distinguishing it from sibling tools like list_objects (which lists objects) and list_schemas (lists schemas). However, it does not specify what 'detailed information' includes, but it is specific enough.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No when-to-use or when-not-to-use guidance is provided. There is no mention of alternatives or contexts where this tool is preferred over siblings.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_top_queriesB
Read-only

Reports the slowest or most resource-intensive queries using data from the 'pg_stat_statements' extension.

ParametersJSON Schema
NameRequiredDescriptionDefault
limitNoNumber of queries to return when ranking based on mean_time or total_time
sort_byNoRanking criteria: 'total_time' for total execution time or 'mean_time' for mean execution time per call, or 'resources' for resource-intensive queriesresources

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.4/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint=true, so the agent knows it's a safe read. The description adds context by specifying the data source (pg_stat_statements) which implies the extension must be enabled, but does not detail potential impacts like query reset or permission requirements.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Single sentence, no unnecessary words. Clear and to the point. Could be slightly improved by adding a brief note about extension requirement, but remains appropriately sized.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the presence of an output schema and optional parameters, the description is adequate but minimal. It does not mention prerequisites (pg_stat_statements must be enabled) or any limitations, which would be helpful for an agent deciding whether to use this tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100% with descriptions for both parameters. The overall description reinforces the sort_by options by mentioning 'slowest or most resource-intensive', but adds no new insight beyond what the schema provides.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses a specific verb 'reports' and clearly identifies the resource as 'the slowest or most resource-intensive queries' from 'pg_stat_statements'. It distinguishes from siblings like analyze_query_indexes or explain_query by focusing on top queries by performance metrics.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use this tool versus alternatives such as analyze_db_health or execute_sql. The description implies it's for identifying problematic queries but does not explicitly state when not to use it or direct to other tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

list_objectsA
Read-only

List objects in a schema

ParametersJSON Schema
NameRequiredDescriptionDefault
object_typeNoObject type: 'table', 'view', 'sequence', or 'extension'table
schema_nameYesSchema name

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.6/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

The description is consistent with the readOnlyHint annotation (true) and does not contradict it. However, it adds no behavioral context beyond the annotation. Since annotations carry the behavioral burden, a score of 3 is appropriate.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single short sentence that is efficiently front-loaded and contains no unnecessary words. It earns its place by clearly stating the tool's purpose.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity and the presence of a detailed input schema and readOnlyHint annotation, the description is sufficient for an AI agent to understand the basic purpose. It could optionally mention the object types listed, but the schema provides that detail. Overall, it is adequately complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100% (both parameters have descriptions in the input schema). The tool description adds no additional meaning about parameters. Per criteria, baseline is 3 when schema coverage is high.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'List objects in a schema' clearly states the action (list) and resource (objects in a schema). It distinguishes from sibling tools like 'list_schemas' which lists schemas, and 'get_object_details' which details a single object. The verb and resource are specific and unambiguous.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No usage guidelines are provided. The description does not indicate when to use this tool versus alternatives, nor does it mention any prerequisites or exclusions. It simply states what the tool does without contextual guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

list_schemasA
Read-only

List all schemas in the database

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.9/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

The description adds no behavioral details beyond the annotation 'readOnlyHint: true'. Given the simplicity of the operation, this is adequate but does not exceed expectations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Single sentence, no redundant information. Highly concise and front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Complete given zero parameters, presence of output schema, and annotation. No additional information is necessary for a simple listing tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has zero parameters, so the description does not need to add parameter semantics. Baseline of 4 applies.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'List all schemas in the database' clearly states the action (list) and resource (schemas), and it distinguishes this tool from sibling tools like 'list_objects' or 'execute_sql'.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool versus alternatives (e.g., when to use 'list_objects' instead). Agent must infer purpose from name alone.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 9 tool updatesv0.1.1
    • Addedanalyze_db_health
    • Addedanalyze_query_indexes
    • Addedanalyze_workload_indexes
    • Addedexecute_sql
    • Addedexplain_query
    • Addedget_object_details
    • Addedget_top_queries
    • Addedlist_objects
    • Addedlist_schemas
  2. 9 tool updatesv0.3.0
    • Removedanalyze_db_health
    • Removedanalyze_query_indexes
    • Removedanalyze_workload_indexes
    • Removedexecute_sql
    • Removedexplain_query
    • Removedget_object_details
    • Removedget_top_queries
    • Removedlist_objects
    • Removedlist_schemas
  3. 9 tool updatesv1.0.0
    • First observedanalyze_db_health
    • First observedanalyze_query_indexes
    • First observedanalyze_workload_indexes
    • First observedexecute_sql
    • First observedexplain_query
    • First observedget_object_details
    • First observedget_top_queries
    • First observedlist_objects
    • First observedlist_schemas

TDQS

A3.7/5.0
Disambiguation5/5

Each tool targets a distinct aspect of database interaction: health checks, index analysis, query execution, explain plans, object details, top queries, and listing schemas/objects. There is no overlap; the two index analysis tools are differentiated by input (specific queries vs. workload).

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern in snake_case (analyze_, execute_, explain_, get_, list_). Verbs like 'analyze', 'execute', 'explain', 'get', and 'list' are used uniformly, making the naming predictable.

Tool Count5/5

With 9 tools, the set is well-scoped for a Postgres MCP server covering health analysis, index optimization, query execution, and schema exploration. It neither feels sparse nor overwhelming, earning its place.

Completeness4/5

The tool set covers analysis and ad-hoc queries comprehensively via execute_sql, but lacks explicit tools for creating, altering, or dropping database objects. However, execute_sql enables these operations indirectly, making the gap minor.

Maintenance

ActivityMaintained
ResponsivenessUnresponsive

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    B
    quality
    B
    maintenance
    A Model Context Protocol server that enables powerful PostgreSQL database management capabilities including analysis, schema management, data migration, and monitoring through natural language interactions.
    18
    1,692
    198
    AGPL 3.0
  • A
    license
    B
    quality
    D
    maintenance
    An open source Model Context Protocol server for PostgreSQL that provides database health analysis, index tuning, query plan exploration, and safe SQL execution for AI agents throughout the development process.
    9
    MIT
  • A
    license
    Not graded
    quality
    Not graded
    maintenance
    An open-source MCP server that provides AI agents with advanced PostgreSQL capabilities including index tuning, query plan optimization, and comprehensive database health analysis. It supports safe SQL execution through configurable access modes and offers both stdio and SSE transport options for various development environments.
    -
  • A
    license
    Not graded
    quality
    D
    maintenance
    A Model Context Protocol (MCP) Server that allows AI models to securely interact with data hosted in Azure Database for PostgreSQL. It enables natural language querying, schema exploration, and data management through MCP clients like Claude Desktop and Visual Studio Code.
    MIT

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/crystaldba/postgres-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server