数据库管理工具

@cocaxcode/database-mcp 是一款功能全面的数据库管理工具,支持 PostgreSQL、MySQL、SQLite 等多种数据库,提供连接组管理、自动回滚、数据转储与恢复、模式自动发现等功能,适用于本地数据库管理和开发工作流程。

  • by cocaxcode
  • TypeScript
  • 本地部署
  • 2 星标
  • 更新于
在 GitHub 查看 cocaxcode/database-mcp

使用说明

@cocaxcode/database-mcp

Your databases, one conversation away.
33 tools · PostgreSQL · MySQL · SQLite · Connection Groups · Rollback · Dump/Restore · Schema auto-discovery

Overview · Just Talk to It · Connection Groups · Installation · Features · Tool Reference · Storage · Architecture


快速概览

最完整的数据库MCP服务器。跨3个引擎(PostgreSQL、MySQL、SQLite)的33个工具,具有连接组、命名连接管理、自动回滚、转储/恢复、通过MCP资源自动发现模式以及完整的查询历史记录——所有这些都来自自然语言。

这不仅仅是一个查询运行器。它是一个完整的数据库工作台:将连接组织到项目目录范围内的组中,设置会话之间持续存在的默认值,在三个详细级别上反思模式,在每次写入时获取变异前快照,使用反向SQL撤消错误,转储和还原整个数据库,并跟踪您运行的每个查询——每个项目、每个连接。

每个连接都属于一个组。组具有作用域(目录)、默认连接和活动连接。当你在一个作用域目录中工作时,你只能看到该组的连接——没有混乱,没有混淆。

你描述你需要什么。AI读取你的模式,编写SQL,并安全地执行它——通过自动LIMIT注入、突变前快照和破坏性操作前的确认。没有云帐户,没有ORM,没有配置文件。凭证永远不会离开你的机器。一切都在本地运行。

适用于 克劳德代码, 克劳德桌面版, 光标, 帆板运动, VS Code, Codex CLI, Gemini CLI,以及任何兼容MCP的客户端。


只需与它对话

您不需要记住工具名称或SQL语法。你想说什么就说什么。

> "Connect to my local PostgreSQL on port 5432, database myapp, user admin"

> "Create a group called backend and add this directory"

> "Connect to my PostgreSQL on localhost, put it in the backend group"

> "Set local-pg as the default connection"

> "Show me all tables"

> "What columns does the users table have?"

> "Show me the last 10 orders with the customer name"
  -> AI reads FKs from schema, builds the JOIN, applies LIMIT 10

> "Insert a test user called Alice"
  -> Snapshot captured for rollback

> "Oops, undo that"
  -> Rows restored via reverse SQL

> "Switch to the production database for this session"
  -> Instant context change, all queries now go to prod

> "Delete all inactive users"
  -> "This will affect N rows. Call again with confirm=true to proceed."

> "What did I run today?"
  -> Full query history with timestamps and execution times

> "Dump the database — structure and data"
  -> SQL file generated, ready for restore

人工智能已经通过以下方式知道你的模式 MCP资源。上面写着 db://schema 查找表格和 db://tables/{name}/schema 用于列、外键和索引。当您跨表请求数据时,它会自动构建正确的JOIN。


连接组

每个连接都属于一个组。组是数据库连接的组织单位——它们使事情保持范围、干净和自动化。

一个组有三个关键概念:

  • 范围:共享组连接的目录。当您在作用域目录中工作时,您只能看到该组的连接。没有全球混乱。
  • 默认:当您输入作用域目录时自动激活的连接。在两次会议之间持续。
  • 积极的:当前正在使用的连接。仅会话--重新启动时重置为默认值。

以下是一个实用的工作流程:

"Create a group called backend"
"Add this directory as scope"
"Create a PostgreSQL connection called local-dev in the backend group"   <- auto-default (first connection)
"Create another called production in backend"
"List connections"                                                       <- shows local-dev (active, default)
"Switch to production"                                                   <- session only
"Set production as default"                                              <- persists between sessions

添加到组中的第一个连接将自动成为默认连接。切换连接只会更改当前会话的活动状态——重新启动后,您将恢复到默认状态。如果希望更改保持不变,请明确设置新的默认值。

这意味着您可以安全地切换到生产环境进行快速查询,并知道下次打开项目时,您将返回开发数据库。


安装

克劳德代码

claude mcp add --scope user database -- npx -y @cocaxcode/database-mcp@latest

克劳德桌面版

添加到配置文件(~/Library/Application Support/Claude/claude_desktop_config.json 在macOS上, %APPDATA%\Claude\claude_desktop_config.json 在Windows上):

{
  "mcpServers": {
    "database": {
      "command": "npx",
      "args": ["-y", "@cocaxcode/database-mcp@latest"]
    }
  }
}
Cursor / Windsurf

添加 .cursor/mcp.json 或 .windsurf/mcp.json 在项目根目录中:

{
  "mcpServers": {
    "database": {
      "command": "npx",
      "args": ["-y", "@cocaxcode/database-mcp@latest"]
    }
  }
}
VS Code

添加 .vscode/mcp.json:

{
  "servers": {
    "database": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@cocaxcode/database-mcp@latest"]
    }
  }
}
Codex CLI (OpenAI)
codex mcp add database -- npx -y @cocaxcode/database-mcp@latest

或添加到 ~/.codex/config.toml:

[mcp_servers.database]
command = "npx"
args = ["-y", "@cocaxcode/database-mcp@latest"]
Gemini CLI (Google)

添加 ~/.gemini/settings.json:

{
  "mcpServers": {
    "database": {
      "command": "npx",
      "args": ["-y", "@cocaxcode/database-mcp@latest"]
    }
  }
}

驱动程序安装

只安装您需要的驱动程序——它们在运行时动态加载:

npm install -g postgres       # PostgreSQL (postgres.js)
npm install -g mysql2         # MySQL
npm install -g sql.js         # SQLite (runs in-process, no native bindings)

注: 使用时 npx,驱动程序必须全局安装。如果全局安装服务器(npm install -g @cocaxcode/database-mcp),驱动程序可以是本地的或全球的。


特性

多数据库,一个界面

大多数数据库MCP服务器都会让您在每次会话中重新配置凭据。这个没有。命名连接在组内持久存在——创建一次,永远使用。

命名连接的工作方式类似于git分支。 您创建 dev, staging, prod 一旦进入一个群体,他们总是在那里。切换是即时的——一个命令,零重新配置:

"Create a group called my-project and add this directory as scope"
"Create a connection called dev with host localhost, database myapp, user admin in my-project"
"Create a read-only connection called analytics pointing to ./data/metrics.db in my-project"
"Switch to dev"               -> queries go to PostgreSQL
"Switch to analytics"         -> queries go to SQLite
"Duplicate dev as dev-readonly with read-only mode"

组范围的连接 意味着不同的项目会自动查看不同的数据库。正在进行项目A?您可以看到项目A的组和连接。切换到项目B的目录,它将使用自己的默认值拾取项目B的组。无需手动切换,项目之间无干扰:

"Create a group called frontend with scope /home/user/frontend"
"Create a group called backend with scope /home/user/backend"

现在,每个目录都有自己的独立连接集。

100%本地凭据。 每个连接都存储为JSON文件 ~/.database-mcp/connections/密码永远不会离开你的机器。没有任何东西被发送到云端。git没有任何承诺。你的证书是你的。

现场管理。 在对话过程中创建、复制、重命名、测试、导出和切换连接。无需重新启动,无需编辑配置文件,无需丢失上下文。

内置安全功能

保护 它是如何工作的
只读模式 连接级别强制--阻止所有突变
需要确认 破坏性行动需要明确 confirm: true
自动限制 读取查询 LIMIT 100 默认情况下(遵守现有的LIMIT)
密码屏蔽 凭据显示为 *** 在 conn_get 输出
突变前快照 每次插入/更新/删除都会捕获行状态以进行回滚
汽车无视。 .database-mcp/ 添加到 .gitignore 首次写作时

回滚快照

每个突变都会捕获一个状态前快照。撤销任何事情。

"Show me available rollbacks"
"Rollback the last delete"
  -> "This will INSERT 47 rows back into orders. Confirm?"
  -> Rows restored via reverse SQL
原始操作 回滚生成
DELETE WHERE id = 5 INSERT INTO ... VALUES (...)
UPDATE SET name = 'Bob' UPDATE SET name = 'Alice' (更新前值)
INSERT INTO ... DELETE WHERE id = {new_id}
DDL(CREATE、ALTER、DROP) 已记录但不可逆

模式自省

三个细节级别,带模式过滤:

"List all tables"                         -> names only (fast)
"Show me the users table with columns"    -> columns + types + nullable
"Full schema for orders including FKs"    -> columns + foreign keys + indexes
"Tables starting with user"              -> pattern: 'user%'

MCP资源(db://schema 和 db://tables/{name}/schema)让AI代理自动访问您的模式——多表查询不需要手动SQL。

使用EXPLAIN执行查询

"Show me all users"
  -> SELECT * FROM users LIMIT 100         <- auto LIMIT

"Show the execution plan for this query"
  -> EXPLAIN ANALYZE with dialect-specific syntax (PostgreSQL/MySQL/SQLite)

压缩模式(v0.3+)

SQL结果通常包含每行可以为千字节的TEXT/JSON/HTML列。AI代理为到达上下文窗口的每个字节付费。 execute_query, execute_mutation 和 explain_query 接受四个可选参数,在保持行和结构完整的同时减少60-95%的标记。

参数 值 它的作用
verbosity 'minimal' / 'normal' (默认)/ 'full' 控制详细程度
only_columns ['id', 'title'] 仅返回这些列(客户端投影)
max_cell_bytes 数字(默认值 500) 每单元格字节上限 'normal'
max_rows_in_response number 超出SQL限制的行上限

模式:

  • minimal --只有 rowCount, executionTimeMs, affectedRows,以及第一行的预览。非常适合插入/更新/删除确认、计数查询和轮询。 节省约90-95%的代币。
  • normal (默认) --整行,但每个单元格截断为 max_cell_bytes 带着一个 …(+NB) 标记。保留表结构。 在宽行上节省约60-80%的令牌。
  • full --整个结果未受影响。当您需要每个单元格的完整值时使用。

典型的节省 SELECT * FROM blog_posts LIMIT 100 哪里 content 每行约2KB HTML(总计约200KB):

模式 消耗代币 节省
full ~50000 0%(基线)
normal (500B细胞) ~12500 ~75%
only_columns: ['id','title','slug'] ~2,500 ~95%
minimal ~300 ~99%

与原始进行直接比较 psql 关于测量的数字,请参见 本地替代品 在......下面

恢复完整结果: 每个压缩响应都包括 call_id。如果您以后需要完整的单元格,请致电 inspect_last_query({ call_id }) — 不重新执行SQL,保留数据库负载和任何副作用。结果保存在20个槽的环形缓冲区中,并持久化到 ~/.database-mcp/last-queries/ TTL为1小时。

// Example: normal (default) response
{
  "call_id": "k3m9a2xp",
  "columns": ["id", "title", "content"],
  "rows": [
    { "id": 1, "title": "Hello", "content": "<h1>Long HTML…(+1847B)" }
  ],
  "rowCount": 1,
  "executionTimeMs": 12,
  "cells_truncated": 1,
  "hint": "1 cell(s) truncated to 500 bytes. Use inspect_last_query({ call_id: \"k3m9a2xp\" }) for full values.",
  "tokens_saved_estimate": 462
}

原生替代方案:真实代币成本

此MCP与Claude Code在以下情况下的本机选项相比如何 database 不可用(Bash+ psql, sqlite3, mysql CLI等)。

太长,读不下去了:与生相比 psql, execute_query 节省之间 78%和96% 取决于模式的上下文令牌,而不会丢失调试信息。通过实际通话进行测量 SELECT * FROM blog_posts LIMIT 5 在PostgreSQL表上使用 content 每行约1KB的HTML列:

代理人如何称呼它 使用MCP? 消耗的代币 Delta与psql
Bash + psql -c "..." (原始表格输出) ❌ 原生 ~1800 基线
Bash +psql+手册 awk/列筛选器 ❌ 原生 易碎,试剂组装 难以测量
execute_query 冗长=full ✅ MCP ~1500 -17%(更少的格式化开销)
execute_query 冗长=normal (默认情况下,单元格上限为500 B) ✅ MCP ~400 −78%
execute_query 冗长=minimal ✅ MCP ~80 −96%
execute_query 随着 only_columns: ["id","title","slug"] ✅ MCP ~130 −93%

为什么这个表的数字与上面的“压缩模式”部分不同:这些来自一个5行的真实世界查询,而上一个表推断出内容更重的100行结果。趋势和数量级是相同的。

笔记:

  • 原始 psql 随着行数的增加,输出会变得更糟——JSONB和长TEXT列没有本机过滤器。MCP单元截断保留了结构(行数+列列表),同时用 …(+NB) 标记。
  • inspect_last_query 恢复完整结果 不重新运行SQL.与 psql 您将不得不重新执行,再次支付DB CPU的费用,并冒着重新触发副作用的风险 RETURNING 条款。
  • MCP还添加了没有直接本地等效功能的功能:作用于项目目录的连接组、突变的自动回滚快照、查询历史、通过MCP资源进行模式自检以及转储/还原。
  • 相关时,在响应末尾添加架构上下文(默认 true 为了 normal/full).禁用 include_schema_context: false 如果代理已经知道模式。
  • 每个注册的MCP每个会话都会增加约300-600个令牌的固定开销(其指令块+工具名称)。典型的盈亏平衡:每个会话一个实际查询。

转储和恢复

SQL格式的完整数据库备份——仅结构或结构+数据。

"Dump the database"
  -> Choose: structure only or full
  -> Choose: all tables or specific ones
  -> SQL file saved to .database-mcp/dumps/

"Restore from the last dump"
  -> Lists available dumps, asks for confirmation, executes

生成的SQL句柄 DROP TABLE IF EXISTS、FK禁用/启用和方言感知DDL。

查询历史

每个项目记录的每个查询都有时间戳、连接、执行时间和结果类型。

"What queries did I run today?"
"Show me only mutations"
"History for the prod connection"

导出和导入连接

"Export all connections"                    -> JSON with masked passwords
"Export with secrets included"             -> JSON with real credentials
"Import these connections: { ... }"        -> creates missing connections

工具参考

8个类别的33个工具,加上2个MCP资源:

类别 工具 计数
连接 conn_create conn_list conn_get conn_set conn_switch conn_rename conn_delete conn_duplicate conn_test conn_export conn_import 11
群组 conn_group_create conn_group_list conn_group_delete conn_group_add_scope conn_group_remove_scope conn_set_default conn_set_group 7
模式 search_schema 1
查询 execute_query execute_mutation explain_query 3
转储 db_dump db_restore db_dump_list 3
回滚 rollback_list rollback_apply 2
历史 history_list history_clear 2
配置 config_get config_set 2

资源: db://schema · db://tables/{tableName}/schema

提示: 你永远不需要直接调用这些工具。只需描述你想要什么,人工智能就会选择正确的。


存储

存储按设计分为两个位置。这种分离是有意的,解决了一个真正的问题:你的凭据属于你,你的项目历史属于项目。

全球的: ~/.database-mcp/ --组、连接、凭据和设置。位于您的主目录中。从不参与项目。从来没有在git。除非您明确导出,否则切勿与任何人共享。

每个项目: {project}/.database-mcp/ --查询历史记录、回滚快照和数据库转储。位于项目目录中,并自动添加到 .gitignore 第一次写作。

~/.database-mcp/                          # Global (configurable via DATABASE_MCP_DIR)
├── groups/                               # Connection groups with scopes and defaults
├── connections/                          # Connection configs (credentials, chmod 600)
├── project-conns.json                    # Session-only active connections (cleared on restart)
└── config.json                           # Server config (limits)

{your-project}/.database-mcp/            # Per-project (auto-gitignored)
├── history.json                          # Query history (max 5000)
├── rollbacks.json                        # Pre-mutation snapshots (max 1000)
└── dumps/
    └── {conn}-{timestamp}-{mode}.sql     # Database dumps

结果:您可以自由共享项目仓库——合作者可以获得历史记录和回滚结构,但没有凭据。他们在当地建立自己的联系和团体。

配置

可通过对话或环境变量进行配置:

变量 描述 默认值
DATABASE_MCP_DIR 全局存储目录 ~/.database-mcp/
DATABASE_MCP_MAX_ROLLBACKS 每个项目的最大回滚快照数 1000
DATABASE_MCP_MAX_HISTORY 每个项目的最大历史条目数 5000
"Set max rollbacks to 2000"
"Set max history to 10000"

优先: env var>保存的配置>默认值.

警告: 如果你覆盖 DATABASE_MCP_DIR 在git存储库中的路径中,添加 .database-mcp/ 给你的 .gitignore 以避免推送凭证。


建筑

src/
├── index.ts              # Entry point (StdioServerTransport)
├── server.ts             # createServer() factory
├── tools/                # 33 tool handlers (one file per category)
├── resources/            # MCP Resources (schema auto-discovery)
├── services/             # Business logic
│   ├── connection-manager    # Lazy connect, driver caching
│   ├── schema-introspector   # Multi-dialect introspection (3 detail levels)
│   ├── query-executor        # Read/mutation/explain with safety
│   ├── rollback-manager      # Snapshot capture + reverse SQL
│   ├── history-logger        # Per-project query log
│   └── dump-manager          # Dump/restore (SQL generation)
├── drivers/              # Database adapters (postgres, mysql, sqlite)
├── lib/                  # Types, storage, sanitization
└── utils/                # SQL classifier, parser, formatter
  • 零运行时间消耗 超越 @modelcontextprotocol/sdk 和 zod
  • 严格的TypeScript --没有 any
  • 动态驾驶员加载 — import('postgres') / import('mysql2/promise') / import('sql.js') 运行时
  • <60KB 通过tsup捆绑
  • 工厂模式 — createServer(storageDir?, projectDir?) 对于孤立的测试实例

麻省理工学院 ·建造于 可卡因