数据库访问服务

MCP Database Server 是一个为AI助手和基于LLM的工具提供安全数据库访问的服务,支持SQLite、PostgreSQL、MySQL和MariaDB,具有查询验证、审计日志和安全控制功能。

  • by amusphere
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 amusphere/mcp-db

使用说明

MCP 数据库服务器

一个模型上下文协议(MCP)服务器,为人工智能助手和基于大型语言模型(LLM)的工具提供安全的数据库访问。该服务器内置安全控制、查询验证和审计日志功能,支持查询SQLite、PostgreSQL、MySQL和MariaDB数据库。

特点/功能

  • 🔒(锁形符号,常用于表示安全、保密或锁定状态) 默认安全具有细粒度权限控制的只读模式
  • 🗄️ 该符号在中文中通常没有直接对应的翻译,它在Unicode中代表“文件柜”或“文件夹”的意思。在中文语境下,可以直接用“文件柜”或“文件夹”来描述这个符号所代表的含义。所以,这个符号可以翻译为“文件柜”或“文件夹”。 多数据库支持 SQLite、PostgreSQL、MySQL 和 MariaDB
  • 🛡️ 翻译为中文是“盾牌”。这个符号通常用来表示保护、防御或安全。 SQL验证自动查询验证和注入防护
  • 📊 表格/数据图表 表格允许列表限制对特定表的访问
  • ⏱️(时钟图标,通常表示时间或倒计时) 查询超时防止长时间运行的查询
  • 📝 翻译为中文是:📝(此表情符号本身无直接文字含义,若需描述其用途,可译为“待办事项/笔记/记录”等,具体根据上下文确定)。在实际应用中,这个表情符号常用来表示待办事项、笔记或记录等概念。 审计日志记录JSON格式的操作日志
  • 🔌(电源插头/插座) MCP协议AI助手的原生stdio传输
  • 🌐 代表“互联网”或“全球网络”的符号。 HTTP 模式可选的用于旧版集成的REST API

支持的MCP客户端

快速入门

安装

使用这个MCP服务器最简单的方法是通过 npx (无需安装):

npx @amusphere/mcp-db

MCP客户端的配置

这台服务器旨在让AI助手能够通过(某种方式)动态地指定数据库连接 db_url 参数。你可以启动服务器 未指定默认数据库并且人工智能将在需要时提供连接字符串。

Codex CLI(注:CLI 通常指“命令行界面”,但在此上下文中,Codex CLI 可能是一个特定工具或框架的名称,直接翻译为“Codex 命令行接口”或保持原样,具体取决于上下文)

添加到你的Codex配置文件中(~/.codex/mcp.toml 或类似情况:

[mcp_servers.mcp-db]
command = "npx"
args = ["-y", "@amusphere/mcp-db"]

然后,人工智能助手将在每次工具调用中指定数据库URL:

You: "Show me tables in my SQLite database at ./data/app.db"
AI: Uses db_url = "sqlite:///./data/app.db" in the tool call

Claude Desktop(可译为“克劳德桌面版”或根据具体语境简化为“克劳德桌面”,但为保持原名特色,建议直接使用“Claude Desktop”或译为“克劳德桌面应用”)

添加到您的Claude桌面配置中(~/Library/Application Support/Claude/claude_desktop_config.json (在 macOS 上):

{
  "mcpServers": {
    "mcp-db": {
      "command": "npx",
      "args": ["-y", "@amusphere/mcp-db"]
    }
  }
}

可选:设置默认数据库

如果您想设置一个默认数据库(仍可被AI覆盖):

[mcp_servers.mcp-db]
command = "npx"
args = ["-y", "@amusphere/mcp-db", "--host", "sqlite:///./dev.db"]

使用示例

推荐:动态数据库选择

启动服务器时不使用默认数据库,并让AI指定连接:

# Start server (AI will provide db_url in each request)
npx @amusphere/mcp-db

# With security controls
npx @amusphere/mcp-db --allow-writes --allowlist users,posts,comments

# With custom limits
npx @amusphere/mcp-db --max-rows 100 --timeout 30

用户对话示例:

  • “显示 sqlite:///./dev.db 数据库中的表”
  • “查询 PostgreSQL://localhost/prod 生产数据库”
  • “比较 ./dev.db 和 ./prod.db 中的用户数量”

备选方案:默认数据库

如果你主要使用一个数据库,你可以设置一个默认值(但仍可被覆盖):

# SQLite default
npx @amusphere/mcp-db --host sqlite:///./dev.db

# PostgreSQL default
npx @amusphere/mcp-db --host postgresql://user:password@localhost:5432/mydb

# With allowlist for default database
npx @amusphere/mcp-db \
  --host sqlite:///./dev.db \
  --allowlist users,posts,comments

用户对话示例:

  • “显示表”(使用默认数据库)
  • “现在检查位于 ./other.db 的另一个数据库”(覆盖默认设置)

本地开发

从源代码克隆并构建:

git clone https://github.com/amusphere/mcp-db.git
cd mcp-db
npm install
npm run build
npm start -- --host sqlite:///./dev.db

热加载开发模式:

npm run dev

测试

所有支持的数据库均可进行综合测试。请参阅 tests/README.md(文件名,可译为“测试/README.md”或保持原样,因为文件名通常不翻译) 以获取详细的测试文档。

快速测试命令:

# Run all tests (requires Docker)
npm test

# Run individual database tests
npm run test:sqlite      # No Docker required
npm run test:postgres    # Requires PostgreSQL container
npm run test:mysql       # Requires MySQL container
npm run test:mariadb     # Requires MariaDB container

基于Docker的测试:

# Run all tests in Docker (recommended - auto cleanup)
npm run test:docker

# Or manually manage containers
docker compose up -d postgres mysql mariadb  # Start databases
npm test                                     # Run tests
docker compose down -v                       # Stop and clean up

HTTP服务器模式(旧版)

为了与基于HTTP的集成保持向后兼容性:

npx @amusphere/mcp-db --host sqlite:///./dev.db --http-mode --port 8080

这暴露了REST端点在 http://localhost:8080/tools/* 针对非MCP客户端。

配置参考

命令行参数

参数 描述 默认值
--host <url> 可选的默认数据库URL(可由AI覆盖) db_url 参数) 无
--allow-writes 启用 INSERT/UPDATE/DELETE 操作 false
--allow-ddl 启用 CREATE/ALTER/DROP 操作 false
--allowlist <tables> 允许的表名列表,以逗号分隔(适用于所有数据库) 所有表
--max-rows <number> SELECT 查询返回的最大行数 500
--timeout <seconds> 查询超时时间(秒) 20
--http-mode 以HTTP服务器模式运行,而非MCP标准输入输出模式 false
--port <number> HTTP模式的端口 8080
--require-api-key 要求X-API-Key头部(仅限HTTP模式) false
--api-key <value> 预期的API密钥值 -

注: 该 --host 参数是可选的。如果未指定,AI必须提供 db_url 在每次工具调用中,如果指定了此值,则它作为默认值,但每个请求可以覆盖此默认值。

数据库URL格式

SQLite:

sqlite:///./path/to/database.db    # Relative path
sqlite:////absolute/path/to/db.db  # Absolute path
sqlite:///:memory:                 # In-memory database

PostgreSQL:

postgresql://username:password@host:port/database
postgresql://localhost/mydb        # Local with defaults

MySQL:

mysql://username:password@host:port/database
mysql://root:password@localhost:3306/mydb

MariaDB:

mariadb://username:password@host:port/database
mariadb://root:password@localhost:3306/mydb

注:MariaDB 的 URL 会在内部自动转换为 MySQL 格式。

环境变量

所有命令行参数也可以通过环境变量来设置(命令行参数具有优先权):

环境变量 等效参数
DB_URL --host
ALLOW_WRITES --allow-writes
ALLOW_DDL --allow-ddl
ALLOWLIST_TABLES --allowlist
MAX_ROWS --max-rows
QUERY_TIMEOUT_SEC --timeout
PORT --port
REQUIRE_API_KEY --require-api-key
API_KEY --api-key

使用环境变量的示例:

export DB_URL="postgresql://user:pass@localhost:5432/mydb"
export ALLOW_WRITES="true"
export ALLOWLIST_TABLES="users,posts,comments"
npx @amusphere/mcp-db

可用的MCP工具

此服务器提供了四种用于数据库操作的MCP工具:

db_tables

列出数据库中的所有表。

参数:

  • db_url (必填/可选):数据库URL。如果没有默认值,则必填 --host 已设置,否则可选择性覆盖
  • schema (可选):按模式过滤(仅适用于 PostgreSQL)

示例 - 动态数据库选择:

{
  "db_url": "sqlite:///./data/myapp.db"
}

示例 - 带有模式的 PostgreSQL:

{
  "db_url": "postgresql://user:pass@localhost:5432/mydb",
  "schema": "public"
}

db_describe_table

获取特定表的列信息。

参数:

  • table (必填):要描述的表名
  • db_url (必填/可选):数据库URL。如果没有默认值,则为必填项 --host 已设置,否则可选择性覆盖
  • schema (可选):模式名称(仅适用于 PostgreSQL)

示例 - 动态数据库选择:

{
  "db_url": "sqlite:///./users.db",
  "table": "users"
}

示例 - 带有模式(PostgreSQL):

{
  "db_url": "postgresql://localhost/mydb",
  "table": "users",
  "schema": "public"
}

db_execute

执行带有安全控制的SQL语句。

参数:

  • sql (必填):要执行的SQL语句
  • db_url (必填/可选):数据库URL。如果没有默认设置,则必填 --host 已设置,否则可选择性覆盖
  • args (可选):命名参数(使用 :param SQL中的语法
  • allow_write (可选):必须是 true 用于写入操作
  • row_limit (可选):覆盖默认最大行数

示例 - 带参数的动态查询:

{
  "db_url": "sqlite:///./data/app.db",
  "sql": "SELECT * FROM users WHERE status = :status LIMIT 10",
  "args": {
    "status": "active"
  }
}

示例 - 跨数据库查询:

{
  "db_url": "postgresql://user:pass@prod-server:5432/analytics",
  "sql": "SELECT COUNT(*) as total FROM events WHERE date >= :start_date",
  "args": {
    "start_date": "2024-01-01"
  }
}

db_explain

使用 EXPLAIN 获取查询执行计划和性能信息。

参数:

  • sql (必填):用于分析的SQL查询(通常为SELECT语句)
  • db_url (必填/可选):数据库URL。如果没有默认设置,则为必填项 --host 已设置,否则可选择性覆盖
  • args (可选):命名参数(使用 :param SQL中的语法
  • analyze (可选):运行 EXPLAIN ANALYZE 以获取实际执行统计信息(执行查询)

示例 - 基本查询计划(SQLite):

{
  "db_url": "sqlite:///./data/app.db",
  "sql": "SELECT * FROM users WHERE email = :email",
  "args": {
    "email": "user@example.com"
  }
}

示例 - 性能分析(PostgreSQL):

{
  "db_url": "postgresql://localhost/mydb",
  "sql": "SELECT u.name, COUNT(o.id) FROM users u JOIN orders o ON u.id = o.user_id GROUP BY u.name",
  "analyze": true
}

用例:

  • 识别慢查询和缺失的索引
  • 分析JOIN性能及查询优化机会
  • 比较不同数据库之间的执行计划
  • 在部署到生产环境前验证查询效率

人工智能助手如何使用这些工具

这台服务器是为……设计的 动态数据库连接AI助手在每次请求中指定数据库URL,使您能够无缝地操作多个数据库。

示例对话

使用 SQLite:

You: "Connect to my SQLite database at ./data/users.db and show me all tables"
AI: Calls db_tables with db_url="sqlite:///./data/users.db"

在数据库之间切换:

You: "Now check the production database at /var/lib/app/prod.db"
AI: Calls db_tables with db_url="sqlite:////var/lib/app/prod.db"

You: "And also show me tables in the PostgreSQL analytics database"
AI: Calls db_tables with db_url="postgresql://user:pass@localhost:5432/analytics"

自然语言查询:

You: "How many users are in the SQLite database at ./users.db?"
AI: Calls db_execute with:
    - db_url="sqlite:///./users.db"
    - sql="SELECT COUNT(*) FROM users"

支持的操作

当你将一个人工智能助手(如Claude或Codex)连接到这个MCP服务器时,它可以:

  1. 动态连接到任何数据库用自然语言指定不同的数据库
  2. 探索数据库结构“数据库X中有哪些表?”
  3. 理解表结构“给我显示数据库Y中users表的列”
  4. 查询数据“生产数据库中有多少活跃用户?”
  5. 分析查询性能“解释这个查询的执行计划”
  6. 跨数据库进行比较“比较 dev.db 和 prod.db 中的用户数量”
  7. 优化查询“查找慢查询并建议创建索引”

人工智能助手将自动从您的请求中提取数据库路径/URL,并使用正确的工具进行处理 db_url 参数。

配置参考

  1. 默认设置为只读写操作和DDL(数据定义语言)操作需要显式启用
  2. 使用允许列表限制对特定表的访问权限 --allowlist
  3. 设置查询限制使用 --max-rows 和 --timeout 防止资源耗尽
  4. 命名参数始终使用 :param 语法以避免SQL注入
  5. 审计日志记录所有操作均以JSON格式记录到标准错误输出(stderr)

安全最佳实践

  1. 默认设置为只读写入和DDL(数据定义语言)操作需要显式启用
  2. 使用允许列表限制对特定表的访问权限 --allowlist
  3. 设置查询限制使用 --max-rows 和 --timeout 防止资源耗尽
  4. 命名参数总是使用 :param 语法以避免SQL注入
  5. 审计日志记录所有操作均以JSON格式记录到标准错误输出(stderr)
  6. 分开的凭证在可能的情况下,使用只读数据库用户
  7. 网络安全对于远程数据库,请使用SSL/TLS连接

审计日志

所有数据库操作均以JSON格式记录到标准错误输出(stderr)中:

{
  "timestamp": "2024-01-17T10:30:45.123Z",
  "tool": "db_execute",
  "category": "read",
  "duration_ms": 42,
  "rowcount": 10,
  "sql": "SELECT * FROM users LIMIT 10"
}

故障排除

连接问题

未找到 SQLite 文件:

# Use absolute path
npx @amusphere/mcp-db --host sqlite:////absolute/path/to/db.db

# Or relative from current directory
npx @amusphere/mcp-db --host sqlite:///./relative/path/db.db

PostgreSQL 连接被拒绝:

  • 验证数据库是否正在运行: pg_isready -h localhost
  • 检查连接字符串格式
  • 确保网络访问权限(防火墙、安全组)

权限错误

“写操作已禁用”:

# Enable writes (both server AND request must allow)
npx @amusphere/mcp-db --host sqlite:///./dev.db --allow-writes

“表未被列入允许列表”

# Add tables to allowlist
npx @amusphere/mcp-db --host sqlite:///./dev.db --allowlist users,posts

性能问题

查询超时:

# Increase timeout
npx @amusphere/mcp-db --host sqlite:///./dev.db --timeout 60

返回的数据过多:

# Reduce row limit
npx @amusphere/mcp-db --host sqlite:///./dev.db --max-rows 100

MCP客户端配置

服务器未出现在Claude桌面版中:

  1. 检查配置文件位置: ~/Library/Application Support/Claude/claude_desktop_config.json (macOS)
  2. 验证JSON语法是否有效
  3. 完全重启Claude桌面版

密码本无法连接:

  1. 检查 ~/.codex/mcp.toml 语法
  2. 确保 npx 在 PATH 中
  3. 首先尝试手动运行命令

Docker 部署

使用 Docker Compose

# Start the server with PostgreSQL
docker-compose up --build

# Access at http://localhost:8080 (HTTP mode)

独立容器

# Build
docker build -t mcp-db:latest .

# Run with SQLite (mount volume for persistence)
docker run --rm \
  -v $(pwd)/data:/data \
  -e DB_URL='sqlite:////data/mydb.db' \
  mcp-db:latest

# Run with PostgreSQL
docker run --rm \
  -e DB_URL='postgresql://user:pass@host:5432/db' \
  -e ALLOW_WRITES=false \
  mcp-db:latest

做出贡献

欢迎投稿!请:

  1. 为仓库创建分支(或“克隆仓库”)
  2. 创建一个特性分支(git checkout -b feature/amazing-feature)
  3. 提交您的更改(git commit -m 'Add amazing feature')
  4. 推送到分支(git push origin feature/amazing-feature)
  5. 打开一个拉取请求

开发环境设置

git clone https://github.com/amusphere/mcp-db.git
cd mcp-db
npm install
npm run dev        # Start development server with hot-reload
npm run lint       # Run ESLint
npm run typecheck  # Run TypeScript type checking
npm test           # Run all tests (requires Docker)
npm run test:docker # Run tests in Docker (recommended)

持续集成/持续交付流水线(CI/CD Pipeline)

所有拉取请求都会自动通过我们的CI/CD流水线:

  • ✅ 安全扫描Gitleaks(用于检测机密信息泄露)和Trivy(用于检测漏洞)
  • ✅ 代码质量ESLint 和 TypeScript 类型检查
  • ✅ 构建验证将TypeScript编译成JavaScript
  • ✅ 全面测试所有数据库测试(SQLite、PostgreSQL、MySQL、MariaDB)

无需额外设置 - 所有安全扫描均使用GitHub内置的令牌。

许可证

MIT 许可证 - 详见 许可证 文件详情请见附件

支持

相关项目


为MCP社区用心打造