Skip to main content
Glama
cocaxcode

@cocaxcode/database-mcp

by cocaxcode

快速概览

功能最全面的数据库 MCP 服务器。覆盖 3 种引擎(PostgreSQL、MySQL、SQLite)的 33 个工具,支持连接组、命名连接管理、自动回滚、转储/恢复、通过 MCP Resources 实现 Schema 自动发现,以及完整的查询历史——全部通过自然语言完成。

这不仅仅是一个查询执行器。它是一个完整的数据库工作台:将连接组织到与项目目录绑定的组中,设置跨会话持久化的默认连接,以三个详细级别检查 Schema,在每次写入前获取变更前快照,用反向 SQL 撤销错误操作,转储和恢复整个数据库,并跟踪你执行的每一条查询——按项目、按连接。

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

你描述需求即可。AI 会读取你的 Schema、编写 SQL 并安全执行——自动注入 LIMIT、变更前快照,以及破坏性操作前的确认。无需云账户、无需 ORM、无需配置文件。凭据永远不会离开你的机器。一切都在本地运行。

兼容 Claude CodeClaude DesktopCursorWindsurfVS CodeCodex CLIGemini CLI 以及任何兼容 MCP 的客户端。


Related MCP server: Database MCP Server

直接对话

你不需要记住工具名称或 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

AI 已经通过 MCP Resources 了解你的 Schema。它读取 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 Code

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

Claude Desktop

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

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

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

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

添加到 .vscode/mcp.json

{
  "servers": {
    "database": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@cocaxcode/database-mcp@latest"]
    }
  }
}
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/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 分支。 你在组内创建一次 devstagingprod,它们就一直在那里。切换是即时的——一条命令,零重新配置:

"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% 本地凭据。 每个连接都存储为 ~/.database-mcp/connections/ 下的 JSON 文件。密码永远不会离开你的机器。不会发送到云端。不会提交到 git。你的凭据只属于你。

实时管理。 在对话中创建、复制、重命名、测试、导出和切换连接。无需重启,无需编辑配置文件,不会丢失上下文。

内置安全保护

保护措施

工作原理

只读模式

连接级强制——阻止所有变更操作

需要确认

破坏性操作需要显式 confirm: true

自动 LIMIT

读取查询默认添加 LIMIT 100(尊重已有的 LIMIT)

密码掩码

凭据在 conn_get 输出中显示为 ***

变更前快照

每次 INSERT/UPDATE/DELETE 都会捕获行状态用于回滚

自动 gitignore

首次写入时自动将 .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)

记录日志但不可逆

Schema 内省

三个详细级别,支持模式过滤:

"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 Resources(db://schemadb://tables/{name}/schema)让 AI 代理自动访问你的 Schema——多表查询无需手动编写 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 结果通常包含每行可达数 KB 的 TEXT / JSON / HTML 列。AI 代理需要为进入上下文窗口的每个字节付费。execute_queryexecute_mutationexplain_query 接受四个可选参数,可削减 60-95% 的 token,同时保持行和结构完整。

参数

作用

verbosity

'minimal' / 'normal'(默认) / 'full'

控制详细程度

only_columns

['id', 'title']

只返回这些列(客户端投影)

max_cell_bytes

数字(默认 500

'normal' 模式下每个单元格的字节上限

max_rows_in_response

数字

超出 SQL LIMIT 的行数上限

模式:

  • minimal — 只包含 rowCountexecutionTimeMsaffectedRows 和第一行的预览。适合 INSERT/UPDATE/DELETE 确认、COUNT 查询、轮询。节省约 90-95% 的 token。

  • normal (默认) — 完整行,但每个单元格截断到 max_cell_bytes,并带有 …(+NB) 标记。保留表结构。宽行节省约 60-80% 的 token。

  • full — 完整结果,不做任何处理。当你需要每个单元格的完整值时使用。

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

模式

消耗的 token

节省

full

~50,000

0%(基线)

normal(500B 单元格)

~12,500

~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
}

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

database 不可用时,此 MCP 与 Claude Code 的原生选项(Bash + psqlsqlite3mysql CLI 等)的对比。

TL;DR:与原始 psql 相比,execute_query 根据模式不同可节省 78% 到 96% 的上下文 token,且不损失任何调试信息。实测于 PostgreSQL 表上执行 SELECT * FROM blog_posts LIMIT 5,其中 content 列每行约 1KB HTML:

How the agent calls it

Uses MCP?

Tokens consumed

Delta vs psql

Bash + psql -c "..."(原始表格输出)

❌ 原生

~1,800

基线

Bash + psql + 手动 awk/列过滤器

❌ 原生

脆弱,由代理拼装

难以衡量

execute_query verbosity=full

✅ MCP

~1,500

−17%(更少的格式化开销)

execute_query verbosity=normal (默认,单元格上限 500 B)

✅ MCP

~400

−78%

execute_query verbosity=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 时,你必须重新执行,再次消耗数据库 CPU,并可能重新触发 RETURNING 子句上的副作用。

  • MCP 还添加了没有直接原生对应物的功能:限定在项目目录范围内的连接组、变更时的自动回滚快照、查询历史、通过 MCP 资源进行的模式内省,以及转储/恢复。

  • 相关时,模式上下文会附加在响应末尾(normal/full 的默认值为 true)。如果代理已经知道模式,请使用 include_schema_context: false 禁用它。

  • 每个注册的 MCP 都会为每个会话增加约 300-600 token 的固定开销(其指令块 + 工具名称)。典型的盈亏平衡点:每个会话 1 次真实查询。

转储与恢复

以 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、外键禁用/启用,以及方言感知的 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

工具参考

共 33 个工具,分属 8 个类别,外加 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

提示: 你永远不需要直接调用这些工具。只需描述你想要什么,AI 就会选择合适的工具。


存储

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

全局:~/.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"

优先级:环境变量 > 已保存配置 > 默认值。

警告: 如果你将 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/sdkzod

  • 严格 TypeScript — 无 any

  • 动态驱动加载 — 运行时 import('postgres') / import('mysql2/promise') / import('sql.js')

  • < 60KB,通过 tsup 打包

  • 工厂模式createServer(storageDir?, projectDir?) 用于隔离的测试实例


MIT · 由 cocaxcode 构建

Install Server
A
license - permissive license
B
quality
D
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

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

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    A modular MCP server that enables interaction with multiple database types including PostgreSQL, MySQL, SQLite, Redis, MongoDB, and LDAP. It provides tools for executing queries, managing SQL commands, and exploring database schemas with configurable read-only security.
    29
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    An extensible MCP server for database operations that supports PostgreSQL for managing schemas, tables, data, and user permissions. It features automatic migration recording for DDL changes and integrates with various AI-powered editors like Cursor, Zed, and Claude Code.
    22
    2
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    A secure multi-database MCP server supporting MySQL, PostgreSQL, and SQLite with read-only enforcement, SQL injection prevention, and tools for schema analysis, performance optimization, and visualization.
    4
  • A
    license
    A
    quality
    D
    maintenance
    A multi-database MCP server supporting MySQL, PostgreSQL, MongoDB, and SQLite with read-only and read-write query capabilities, schema inspection, and SSH tunneling, all without Docker.
    5
    2
    MIT

View all related MCP servers

Related MCP Connectors

  • GibsonAI MCP server: manage your databases with natural language

  • MCP server for managing Prisma Postgres.

  • Butterbase MCP server — manage your backend: schemas, auth, functions, storage, RAG, deploys.

View all MCP Connectors

Latest Blog Posts

MCP directory API

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

curl -X GET 'https://glama.ai/api/mcp/v1/servers/cocaxcode/database-mcp'

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