database-mcp
database-mcp
SQL 数据库 MCP 服务器,具备真正的服务端结果分页——这是现有数据库 MCP 服务器都没有的功能(DBHub 限制行数,Google 的 MCP Toolbox 返回全部内容,mcp-alchemy 在 4000 字符处截断)。
PostgreSQL 参考实现。
为什么
每个现有的 SQL MCP 服务器要么截断大型结果,要么将整个结果转储到模型的上下文中。MCP 规范仅对 列表 操作(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
连接配置文件——由 AI 在运行时管理
连接是命名的配置文件,持久化在 ~/.config/database-mcp/profiles.json(chmod 600)中。AI 可以通过工具即时添加、更改、测试和删除它们,无需重启服务器:
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),因此隧道的生命周期恰好是子进程的生命周期。
工具
工具 | 用途 |
| 执行 SQL,获取第一页 + 当有更多行时返回 |
| 从持有的游标获取下一页——无需重新执行 |
| 提前关闭一个/所有游标 |
| 列出表/视图,附带行估计和大小 |
| 一个表的列、约束、索引 |
| 查询计划(可选 |
| 概览卡片:一次调用获取所有表 + 行估计 + 列名 |
| 按名称或注释查找表/列/函数 |
| 来自 |
| 一个表的外键,双向 |
| 两个表之间的最短外键路径,作为现成的 JOIN 链 |
| 即时规划器估计(可选 |
| 通过 |
| 运行时连接管理 |
| 配置文件、连接池、打开的游标、限制 |
结果是紧凑的 JSON——列只出现一次,行作为数组——大约是其他服务器发出的行字典格式的 token 数的一半。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 runtimeClaude 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 秒内捕获死对端——包括连接池外固定的游标连接。连接池检出检查:每个分发的连接都通过廉价的往返验证;过期的连接被丢弃并透明替换——调用者永远不会看到错误。空闲的池化连接在
--keepalive秒后被回收;连接尝试在--connect-timeout(默认 5 秒)后失败,而不是 TCP 默认的约 2 分钟。
测试
uv pip install -e '.[dev]'
pytest # needs a local PostgreSQL (DBMCP_TEST_DSN to override)许可证
MIT
Available Tools
18 toolscloseA
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
Scored across 18 tools
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.
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.
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.
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
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Connect to PlanetScale databases, branches, schema, query insights, and execute SQL
Managed Postgres MCP: projects, SQL, docs search, and storage buckets via OAuth.
Related MCP Servers
- AlicenseBqualityDmaintenanceEnables 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.9MIT
- AlicenseBqualityDmaintenanceEnables 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.35MIT
- FlicenseNot gradedqualityDmaintenanceEnables querying PostgreSQL databases via MCP, with multi-database routing, credential isolation, and truncated results plus full CSV export.-
- FlicenseNot gradedqualityDmaintenanceEnables secure, direct access to PostgreSQL databases for queries, modifications, and schema exploration.-