Skip to main content
Glama
database-mcp

database-mcp

by thhart

database-mcp

SQL MCP сервер для баз данных с настоящей постраничной выдачей результатов на стороне сервера — функция, которой нет ни у одного устоявшегося MCP сервера для баз данных (DBHub ограничивает количество строк, Google's MCP Toolbox возвращает всё, mcp-alchemy обрезает на 4000 символов).

Эталонная реализация для PostgreSQL.

Зачем

Каждый существующий SQL MCP сервер либо обрезает большие результаты, либо сбрасывает их целиком в контекст модели. Спецификация MCP поддерживает пагинацию только для операций list (tools/list), но не для результатов инструментов. database-mcp закрывает этот пробел:

  • Запрос выполняется один раз как серверный курсор PostgreSQL (DECLARE/FETCH FORWARD) внутри удерживаемой транзакции.

  • Каждый fetch(cursor) продолжает ровно с того места, где закончилась последняя страница — без повторного выполнения, без повторного сканирования OFFSET, а снимок MVCC сохраняет результат стабильным даже при конкурентных записях.

  • Страницы ограничены количеством строк (page_size) и размером в байтах (max_page_bytes); слишком большие ячейки обрезаются с явным маркером.

  • Удерживаемые курсоры ограничены: максимум N одновременных (вытеснение LRU), вытеснение по TTL простоя, плюс idle_in_transaction_session_timeout как серверная страховка. Исчерпанные курсоры закрываются автоматически.

Related MCP server: pgsql-mcp

Профили подключения — управляются ИИ в рантайме

Подключения — это именованные профили, сохраняемые в ~/.config/database-mcp/profiles.json (chmod 600). ИИ может добавлять, изменять, тестировать и удалять их на лету через инструменты — без перезапуска сервера:

  • profile_add(name, dsn, allow_writes=false, description, make_default, test=true)

  • profile_remove(name) · profile_test(name) · profiles()

  • каждый инструмент запроса принимает необязательный параметр profile; при его отсутствии используется профиль по умолчанию.

Профили по умолчанию доступны только для чтения (сессионный default_transaction_read_only); запись требует явного профиля с allow_writes=true.

SSH-мост

Профиль может получить доступ к базе данных, доступной только через SSH (классическая схема «Postgres слушает localhost на удалённом хосте»):

profile_add(name="prod", dsn="postgresql://app@dbhost:5432/app",
            ssh_host="dbhost")
  • Туннель — это подпроцесс системного ssh (-N -L, BatchMode, keepalives) — ваш ~/.ssh/config, ключи и агент применяются без изменений. Аутентификация должна работать без интерактивного ввода.

  • ssh_remote_host/ssh_remote_port по умолчанию соответствуют хосту/порту DSN, видимому с SSH-хоста; если хост DSN совпадает с SSH-хостом, по умолчанию используется 127.0.0.1 (обычный случай).

  • Туннели запускаются лениво, проверяются на каждом использовании и автоматически пересоздаются. Если туннель умирает во время пагинации, его курсоры инвалидируются с понятной ошибкой, а следующий запрос переподключается.

  • Мультиплексирование (ControlMaster) явно отключено для туннельных соединений, чтобы время жизни туннеля точно совпадало с временем жизни подпроцесса.

Инструменты

Инструмент

Назначение

query

Выполнить SQL, получить первую страницу + cursor, если есть ещё строки

fetch

Следующая страница из удерживаемого курсора — без повторного выполнения

close

Закрыть один/все курсоры досрочно

tables

Список таблиц/представлений с оценкой строк и размерами

describe

Колонки, ограничения, индексы одной таблицы

explain

План запроса (опционально analyze)

overview

Ориентационная карточка: все таблицы + оценка строк + имена колонок одним вызовом

search_objects

Поиск таблиц/колонок/функций по имени или комментарию

profile

Статистика колонок из pg_stats — распределения без сканирования

relations

Внешние ключи таблицы, в обе стороны

join_path

Кратчайший путь по внешним ключам между двумя таблицами как готовая цепочка JOIN

count

Мгновенная оценка планировщика (опционально where), exact=true для реального count(*)

sample

Действительно случайные строки через TABLESAMPLE (без смещения LIMIT)

profiles / profile_add / profile_remove / profile_test

Управление подключениями в рантайме

status

Профили, пулы, открытые курсоры, лимиты

Результаты — компактный JSON: колонки один раз, строки как массивы — примерно вдвое меньше токенов, чем формат «строка-словарь», который используют другие серверы. query также возвращает estimated_rows (оценка планировщика через EXPLAIN), чтобы модель знала, с чем она работает при пагинации.

Установка и запуск

uv pip install -e .
database-mcp --dsn postgresql://user@host:5432/db      # registers profile "default"
database-mcp                                           # start empty, add profiles at runtime

Регистрация в Claude Code:

claude mcp add database -- database-mcp --dsn postgresql://user@host:5432/db

Опции: --profiles FILE, --allow-writes, --page-size 50, --max-page-size 500, --max-page-bytes 32000, --max-cell 400, --cursor-ttl 300, --max-cursors 4, --statement-timeout 30, --keepalive 120, --connect-timeout 5. Переменные окружения: DATABASE_MCP_DSN / DATABASE_URL, DATABASE_MCP_PROFILES.

Обработка устаревших соединений

Мёртвые соединения обнаруживаются быстро на каждом уровне, а не зависают:

  • SSH-туннели: ServerAliveInterval = --keepalive (по умолчанию 2 мин) с ServerAliveCountMax=1 — один пропущенный пробный пакет завершает процесс туннеля, который менеджер движка обнаруживает при следующем использовании и лениво пересоздаёт.

  • Соединения с БД: TCP keepalives (keepalives_idle = --keepalive, пробы каждые 10 с, 3 пропуска) ловят мёртвых пиров за ~30 с — включая закреплённые курсорные соединения вне пула.

  • Проверка при выдаче из пула: каждое выдаваемое соединение проверяется дешёвым round-trip; устаревшее отбрасывается и прозрачно заменяется — вызывающий никогда не видит ошибку. Простаивающие соединения в пуле перерабатываются через --keepalive секунд; попытки подключения завершаются ошибкой через --connect-timeout (по умолчанию 5 с) вместо стандартных ~2 мин TCP.

Тесты

uv pip install -e '.[dev]'
pytest            # needs a local PostgreSQL (DBMCP_TEST_DSN to override)

Лицензия

MIT

Available Tools

18 tools
closeA

Close an open cursor (or all cursors when no token is given) to free its connection early.

Inputs: cursor. Returns: result

countA

Row count, estimate-first: instant planner estimate (no scan), optionally with a WHERE clause; exact=true runs a real count(*) under the statement timeout. Prefer the estimate.

Inputs: table (required), exact, where, profile. Returns: result

describeA

Describe one table: columns with types/nullability/defaults, constraints (PK/FK/unique/check), and indexes.

Inputs: table (required), profile. Returns: result

explainA

Show the query plan (EXPLAIN). Set analyze=true to actually run the statement and get real timings.

Inputs: sql (required), params, analyze, profile. Returns: result

fetchA

Fetch the next page from an open cursor returned by query. No re-execution: rows continue exactly where the last page ended. The cursor auto-closes when exhausted (has_more=false).

Inputs: cursor (required), page_size. Returns: result

join_pathB

Shortest foreign-key path between two tables, rendered as a ready-to-use JOIN chain (up to 3 equally short paths). Use this instead of guessing joins on unfamiliar schemas.

Inputs: to_table (required), from_table (required), profile, max_hops. Returns: result

overviewA

Orientation card for an unknown database: every table with row estimate and its column names in ONE compact call — use this before tables/describe round-trips. Optional table-name filter.

Inputs: filter, profile. Returns: result

profileA

Column statistics from pg_stats WITHOUT touching the table: null fraction, distinct count (negative = fraction of rows, -1 = unique), most common values with frequencies, histogram bounds, physical correlation. Replaces exploratory SELECT DISTINCT / GROUP BY scans.

Inputs: table (required), profile. Returns: result

profile_addA

Add or update a named connection profile at runtime and persist it. Tests the connection first (set test=false to skip). Profiles are read-only unless allow_writes=true. make_default=true switches the default profile. For a database only reachable via SSH, set ssh_host (an ssh destination or ~/.ssh/config alias; BatchMode, so keys/agent must work non-interactively) — a tunnel is opened automatically and kept alive; ssh_remote_host/ssh_remote_port default to the DSN's host/port as seen FROM the ssh host (usually 127.0.0.1:5432).

Inputs: dsn (required), name (required), test, ssh_host, +5 more. Returns: result

profile_removeB

Remove a connection profile (open cursors on it are closed).

Inputs: name (required). Returns: result

profilesA

List all connection profiles (DSNs password-redacted) and which one is the default.

Inputs: no named parameters. Returns: result

profile_testA

Test connectivity of a profile (default profile when omitted): server version and connect latency.

Inputs: name. Returns: result

queryA

Execute SQL on a profile (default profile when omitted). Returns the first page as compact {"columns":[...],"rows":[[...],...],"page":{"returned","has_more","estimated_rows","cursor"}}. When has_more is true, pass page.cursor to the fetch tool — the query is NOT re-executed; a server-side cursor is held open (stable snapshot). Placeholders: %s positional with the params array.

Inputs: sql (required), params, profile, page_size. Returns: result

relationsA

Foreign keys of one table, both directions: what it references and what references it.

Inputs: table (required), profile. Returns: result

sampleA

A few genuinely random rows from a table (TABLESAMPLE on big tables — no scan, no physically-adjacent LIMIT bias).

Inputs: table (required), n, profile. Returns: result

search_objectsB

Find tables, columns, and functions by name OR by comment (pg_description — often the only documentation a schema has). Answers 'where is the customer email?' in one call.

Inputs: term (required), limit, profile. Returns: result

statusA

Server status: profiles with pool statistics, open cursors, configured limits, profiles file location.

Inputs: no named parameters. Returns: result

tablesA

List tables/views/matviews with estimated row counts and sizes (system schemas excluded). Optional name filter.

Inputs: filter, profile. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.8/5.0

    Scored across 18 tools

    Disambiguation5/5

    Each tool targets a distinct concern: cursor-paginated queries (query/fetch/close), schema exploration (tables/describe/overview/search_objects), statistical analysis (profile/count/sample/relations/join_path), explain plans, and connection profile management (profiles/profile_add/profile_remove/profile_test). No overlapping responsibilities that would cause an agent to misselect.

    Naming Consistency4/5

    Tool names are mostly snake_case verbs or nouns that clearly map to actions (query, fetch, describe, count) or objects (tables, profiles). The profile_add/profile_remove/profile_test trio uses a consistent prefix. The only minor inconsistency is mixing singular nouns like 'profile' with plural 'profiles' and standalone verbs, but this does not impair predictability.

    Tool Count4/5

    At 18 tools, the set is slightly heavy but each tool earns its place—covering query execution, pagination, schema discovery, row sampling, join pathing, explain, column statistics, and connection management. It leans toward the upper bound of reasonable scope for a database MCP server, but avoids bloat.

    Completeness5/5

    The tool surface covers the full read-side lifecycle: discover schema (overview, tables, describe, search_objects), analyze data (profile, count, sample, relations, join_path), execute and paginate queries (query, fetch, close), inspect performance (explain), and manage connections (profiles, profile_add/remove/test, status). No critical operations are missing for the intended read/diagnostics purpose.

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      B
      quality
      D
      maintenance
      Enables comprehensive PostgreSQL database management including index tuning, query plan analysis, health monitoring, schema-aware SQL generation, and safe SQL execution with configurable access control for both development and production environments.
      9
      MIT
    • A
      license
      B
      quality
      D
      maintenance
      Enables interaction with PostgreSQL databases through comprehensive database management tools including index tuning, query execution plans, health checks, schema intelligence, and safe SQL execution with configurable read-only mode for production use.
      35
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables querying PostgreSQL databases via MCP, with multi-database routing, credential isolation, and truncated results plus full CSV export.
      -