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.4/5.0
Behavior4/5

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

Annotations already declare readOnlyHint=true, and the description aligns with this by using 'analyzes' and describing read-only checks. The description adds value by explaining what each check examines (e.g., invalid indexes, connection utilization, vacuum health), which helps the agent understand the tool's behavior 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.

Conciseness4/5

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

The description is well-structured with a lead sentence and a bulleted list of checks. It is appropriately sized given the number of checks, and each bullet adds necessary information. It is slightly long but not wasteful, earning a strong score.

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?

With an output schema present, the description does not need to explain return values. It thoroughly covers the input parameter, enumerates all health check options, and describes the default behavior, making it complete for an agent to select and invoke the tool correctly.

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 schema already lists valid values for health_type with 100% coverage. The description enhances this by explaining what each value does and explicitly noting that comma-separated lists are allowed, which is not in the schema. This additional semantic detail goes beyond the schema baseline.

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 with a specific verb ('analyzes database health') and enumerates eight distinct health check categories. This distinguishes it from sibling tools like analyze_workload_indexes and execute_sql, which focus on other aspects of database operations.

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?

The description provides clear context for using the tool by detailing each health check option and the default behavior. However, it does not explicitly state when to use this tool versus alternatives like analyze_workload_indexes, nor does it mention exclusions, so it falls short of full explicit guidance.

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

A3.8/5.0
Behavior3/5

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

The readOnlyHint annotation already signals this is a safe read operation. The description adds the 'up to 10' query limit, which is a useful constraint, but does not disclose other behaviors such as the default analysis method ('dta'), the effect of 'max_index_size_mb', or potential latency. It adds minimal context beyond the annotations and purpose.

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, front-loaded sentence that conveys the core purpose and a key constraint without unnecessary words. Every word earns its place, and no filler or redundancy exists.

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 output schema exists and the annotations mark it read-only, the description is adequate for an AI to understand the tool's basic function. It captures the input limit and the goal. Missing is a note on when to use this vs. analyze_workload_indexes, but that is a usage nuance rather than a completeness gap. Overall it is complete for a simple analysis 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 description coverage is 100%, so the input schema already documents all parameters. The description does not add additional meaning for 'queries', 'method', or 'max_index_size_mb' beyond what the schema provides. Baseline of 3 applies because the schema handles parameter documentation.

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 ('Analyze'), names the resource ('SQL queries'), and clearly states the output ('recommend optimal indexes'). It distinguishes itself from the sibling tool 'analyze_workload_indexes' by noting the input is a list of up to 10 queries rather than a workload.

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 a bounded set of queries (up to 10) but does not explicitly state when to prefer this tool over alternatives like 'analyze_workload_indexes' or 'explain_query'. There are no clear exclusions or alternative references, so guidance is implied rather than explicit.

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

analyze_workload_indexesB
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

B3.3/5.0
Behavior3/5

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

The annotations already declare readOnlyHint=true, so the description's read-only analysis nature is consistent. It adds context that the analysis targets 'frequently executed queries' and produces index recommendations, but does not disclose any potential performance impact, the fact that it does not apply indexes, or what happens with the output beyond being a recommendation.

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 immediately states the tool's purpose without superfluous words. It is front-loaded with the action and object.

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 full schema parameter coverage, the description is minimally sufficient. However, it lacks information on the two methods ('dta' vs 'llm') and does not clarify how this tool differs from the closely named sibling 'analyze_query_indexes', which is a notable gap for selection.

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%, with both 'method' and 'max_index_size_mb' having descriptions. The tool description adds no parameter-specific semantics beyond the schema, so it does not exceed the baseline.

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 uses a specific verb ('Analyze') and identifies the resource ('frequently executed queries') and outcome ('recommend optimal indexes'), making the tool's function clear. However, it does not explicitly differentiate from the sibling tool 'analyze_query_indexes', which may operate on a single query rather than a workload.

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 provides no guidance on when to use this tool versus alternatives like 'analyze_query_indexes' or 'get_top_queries'. It does not mention scenarios, prerequisites, or exclusions, leaving the agent to infer usage from the name and context.

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

execute_sqlB
Destructive

Execute any SQL query

ParametersJSON Schema
NameRequiredDescriptionDefault
sqlNoSQL to runall

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.3/5.0
Behavior3/5

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

The annotations include destructiveHint=true, which already alerts the agent to potential destructive side effects. The description's 'any' reinforces that the tool can execute non-read queries, but it adds no additional behavioral context such as permission requirements, transaction handling, or result format. This is a minimal contribution beyond the structured hint.

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 consists of one concise sentence, 'Execute any SQL query', which is immediately front-loaded and free of unnecessary elaboration. It optimizes brevity while conveying the essential action.

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?

The tool is a simple SQL executor with a single parameter and an output schema, and the annotation provides a destructive warning. However, the description gives no context about when to use it (e.g., for arbitrary reads/writes) versus the specialized sibling tools, and it omits any caveats about side effects beyond the bare annotation. Given the tool's low complexity, this is adequate but not enriched, so it falls short of being fully contextual.

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 schema provides a single `sql` parameter with a description ('SQL to run') and a default, achieving 100% coverage. The tool description 'Execute any SQL query' adds no further meaning about the parameter's syntax, allowed statements, or formatting. Since the schema already documents the parameter, no compensating explanation is needed.

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 verb (execute) and resource (SQL query), making its core function unambiguous. However, it does not explicitly differentiate from sibling tools like explain_query or analyze_query_indexes, leaving the reader to infer its role as a general-purpose executor. This is clear but lacks explicit sibling differentiation.

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 provides no guidance on when to use this tool versus alternatives. It doesn't mention that this is for arbitrary SQL execution while siblings handle query analysis, schema listing, or index insights, nor does it state any restrictions or prerequisites. This leaves the agent without direction for tool selection.

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.8/5.0
Behavior3/5

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

Annotations declare readOnlyHint=true, so the tool is known to be a safe read operation. However, the description does not disclose that the 'analyze' parameter actually executes the query, which is an important behavioral nuance. No contradiction with annotations, but little added context beyond purpose.

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, clear sentence that immediately states what the tool does. No unnecessary words or repetition.

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 rich schema (100% param coverage) and existing output schema, the description is mostly sufficient. However, it could mention the optional analyze and hypothetical_indexes capabilities in the main description for quicker agent awareness, though these are covered in the schema.

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%, with detailed parameter descriptions including examples for hypothetical_indexes. The description itself adds no parameter-level information, so baseline 3 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?

Description clearly states the tool explains the execution plan for a SQL query, with specific verb 'explains' and resource 'execution plan'. It also mentions cost estimates, distinguishing it from execute_sql and 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 Guidelines3/5

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

Usage context is implied ('explains the execution plan') but no explicit guidance on when to use this tool versus alternatives like analyze_query_indexes or execute_sql. No exclusions or prerequisites are mentioned.

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.4/5.0
Behavior3/5

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

Annotations include readOnlyHint: true, which already indicates a safe read operation, and the description aligns with this by saying 'Show detailed information'. However, the description adds no extra behavioral context beyond the annotation, such as what constitutes 'detailed' or how missing objects are handled. With annotations present, the bar is lower, and the description meets the minimum without adding value.

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 front-loads the action and resource. It contains no filler or redundant wording, earning full marks for conciseness.

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, an output schema (mentioned in context signals), and the fully described input schema, the description is largely adequate. However, it lacks explicit guidance on when to use this tool over siblings, which would improve completeness. The missing usage context is the main gap.

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%, with each parameter (schema_name, object_name, object_type) having a clear description. The tool description itself adds no parameter-specific meaning beyond the schema, so the baseline of 3 applies. object_type's default value and allowed values are already in the schema.

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 'Show detailed information about a database object' uses a specific verb ('Show') and resource ('database object'), making the core purpose clear. It distinguishes itself from sibling tools like 'list_objects' (which likely enumerates objects) by focusing on details of a single object, but it does not explicitly state this differentiation.

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. The description doesn't mention that this tool is for inspecting a specific object as opposed to listing all objects, nor does it describe any prerequisites or exclusions. The user must infer usage from the tool name and sibling context.

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

get_top_queriesA
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

A3.6/5.0
Behavior3/5

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

Annotations declare readOnlyHint: true, so the safe nature is already known. The description adds useful context about the data source (pg_stat_statements) but does not disclose prerequisites like extension availability or any limitations on the reported data.

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, clear sentence that front-loads the purpose and names the data source. No wasted words or redundant information.

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?

The description is simple and self-contained, naming the data source and purpose. Output schema and parameter schema cover the remaining details. A minor gap is not mentioning that the pg_stat_statements extension must be installed for the tool to work.

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 provides 100% coverage for both parameters, including explanations for valid sort_by values. The tool description adds no extra parameter-level detail, so the baseline score 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 action ('Reports') and the resource ('slowest or most resource-intensive queries') with a specific data source ('pg_stat_statements'). This distinguishes it from siblings like explain_query and analyze_query_indexes, which focus on different aspects.

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?

There is no explicit guidance on when to use this tool versus the sibling analysis tools. No mention of prerequisites, appropriate contexts, or exclusions; the intended use is only implied by the name and description.

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

list_objectsC
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

C2.9/5.0
Behavior2/5

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

The description adds no behavioral context beyond the readOnlyHint annotation; it simply restates the tool's purpose in a generic way. It does not mention pagination, default object_type behavior, or scope limitations, and because annotations already declare read-only, the description provides no additional transparency.

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 concise (a single sentence) and free of fluff, but it is also under-specified and essentially repeats the title. It lacks any structured detail (e.g., parameter mentions, usage context) that would make the sentence earn its place beyond the obvious.

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, the input schema, readOnlyHint annotation, and presence of an output schema provide sufficient context for an agent to use it correctly. The description, while minimal, correctly states the high-level function, which is adequate for a straightforward list operation.

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 fully documents both parameters (schema_name required, object_type with allowed values), giving 100% schema description coverage. The description adds no parameter-level meaning, but the schema already handles the semantics, so the baseline of 3 applies.

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 identifies the action (list) and resource (objects in a schema), which is a specific verb+resource combination. However, it does not mention the object types or differentiate from sibling tools like get_object_details, so it lacks the scope and differentiation needed for a 5.

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 provides no guidance on when to use this tool versus alternatives such as list_schemas or get_object_details. There is no context about prerequisites, exclusions, or typical use cases, so the agent receives no decision-support information.

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

A4.1/5.0
Behavior3/5

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

Annotations already declare readOnlyHint=true, which covers safety. The description adds the scope 'all schemas' but does not disclose other behavioral traits like ordering, pagination, or return format. With annotations present, a neutral score 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 concise sentence, 'List all schemas in the database', with no wasted words. It front-loads the action and object clearly.

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?

For a simple read-only tool with no parameters and an output schema, the description fully covers the necessary context. It is complete without over-explaining, and annotations cover the safety profile.

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 baseline is 4. The description adds no param info, but none is needed; the empty schema is self-explanatory.

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 'List' with a clear resource 'schemas' and scope 'in the database'. It distinguishes from siblings like list_objects and get_object_details by explicitly focusing on schemas.

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 clearly implies when to use the tool (when needing all schemas), but it does not explicitly state alternatives or exclusions. The presence of siblings like list_objects suggests a need for more differentiation, but none is provided.

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.

  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

Scored across 9 tools

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

ActivityStale
ResponsivenessUnresponsive

Related MCP Connectors

Related MCP Servers

  • A
    license
    B
    quality
    D
    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,631 npm
    201
    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.
    MIT
  • 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