使用说明
DB-MCP:通用数据库MCP服务器
将AI代理连接到任何SQL数据库 使用模型上下文协议(MCP)。
DB-MCP 是一个基于 Python 的 MCP 服务器,它允许 AI 代理通过自然语言查询、分析并与您的数据库进行交互。支持 PostgreSQL、MySQL、SQL Server 和 SQLite。
安装
快速入门(推荐)
# Install from PyPI
pip install db-mcp
# Generate example configuration
db-mcp --init
# Edit config.json with your database details
# Then run the server
db-mcp --config config.json
在Python中使用db-mcp库
from db_mcp.config import Config
from db_mcp.database import DatabaseManager
config = Config("config.json")
db = DatabaseManager(config.get_database("my_database"))
result = db.execute_query("SELECT * FROM users")
if result["success"]:
print(result["data"])
db.close()
就这些!现在请配置您的AI代理以连接到服务器(见下文)。
系统架构
graph LR
A[AI Agent] -->|MCP Protocol| B[DB-MCP Server]
B -->|SQLAlchemy| C[PostgreSQL]
B -->|SQLAlchemy| D[MySQL]
B -->|SQLAlchemy| E[SQLite]
B -->|SQLAlchemy| F[SQL Server]
G[config.json] -.->|Configuration| B
H[.env] -.->|Credentials| B
style A fill:#4CAF50
style B fill:#2196F3
style C fill:#336791
style D fill:#4479A1
style E fill:#003B57
style F fill:#CC2927
组件:
- 人工智能代理 任何兼容MCP的人工智能客户端(如Claude Desktop、Cursor等)
- DB-MCP 服务器 带有安全控制的通用数据库适配器
- SQLAlchemy 针对多种数据库类型的数据库抽象层
- 配置 JSON 配置 + 环境变量用于凭据
查询流程图
sequenceDiagram
participant Agent as AI Agent
participant MCP as DB-MCP Server
participant Pool as Connection Pool
participant DB as Database
Agent->>MCP: Natural Language Query
Note over MCP: Parse request & validate
MCP->>MCP: Security Check<br/>(read-only mode?)
MCP->>Pool: Request connection
Pool->>DB: Execute SQL
DB->>Pool: Return results
Pool->>MCP: Results (max 100 rows)
MCP->>MCP: Format results as JSON
MCP->>Agent: Structured response
Note over Agent: Agent processes and<br/>presents to user
流程步骤:
- 代理通过MCP协议发送自然语言查询
- DB-MCP进行验证并转换为SQL
- 已应用安全检查(只读强制执行)
- 连接池管理数据库访问
- 返回并格式化结果
- 代理向用户展示结果
特点/特性
- 通用连接性 一个服务器支持PostgreSQL、MySQL、SQL Server和SQLite
- 默认安全 只读模式,查询验证,连接池
- 轻松设置 简单的JSON配置,适用于任何MCP兼容的代理
- 5款强大工具 查询执行、模式检查、执行计划解释等
- 已准备好发布到PyPI 可通过 pip 安装,便于分发
完整安装指南
步骤1:安装DB-MCP
pip install db-mcp
步骤2:安装数据库驱动程序
为您的数据库安装所需的驱动程序:
# For PostgreSQL
pip install psycopg2-binary
# For MySQL
pip install mysql-connector-python
# For SQL Server (Windows only)
pip install pyodbc
注: SQLite 支持内置,无需额外驱动程序。
步骤3:创建配置
生成一个示例配置文件:
db-mcp --init
这造成了一个 config.json 包含所有数据库类型示例的文件。请使用您实际的数据库详细信息进行编辑:
{
"databases": {
"my_database": {
"type": "postgresql",
"host": "localhost",
"port": 5432,
"database": "mydb",
"username": "user",
"password": "password",
"read_only": true
}
}
}
支持的数据库类型: postgresql, mysql, sqlite, mssql
重要提示: 从config.json中移除你不需要的数据库条目
步骤4:测试服务器
运行服务器以确保其能够连接:
db-mcp --config config.json
你应该看到:
==================================================
DB-MCP Server Starting...
==================================================
Loaded 1 database(s): my_database
Connected to database 'my_database' (postgresql)
Server ready and listening for connections
==================================================
新闻界 Ctrl+C 停止测试。
第五步:连接您的AI代理
对于Claude Desktop
编辑您的Claude桌面配置文件:
Windows: %APPDATA%\Claude\claude_desktop_config.json
Mac: ~/Library/Application Support/Claude/claude_desktop_config.json
Linux: ~/.config/Claude/claude_desktop_config.json
添加此配置:
Windows:
{
"mcpServers": {
"database": {
"command": "db-mcp",
"args": [
"--config",
"C:\\path\\to\\your\\config.json"
]
}
}
}
Mac/Linux:
{
"mcpServers": {
"database": {
"command": "db-mcp",
"args": [
"--config",
"/path/to/your/config.json"
]
}
}
}
重要提示: 为config.json的位置使用绝对路径。
对于其他兼容MCP的代理
根据您的代理的MCP服务器设置说明进行配置。服务器通过标准MCP协议在stdio上进行通信。
步骤6:重启您的AI代理
完全重启您的AI代理以加载MCP服务器。
使用示例
一旦连接成功,您可以向您的客服代表提出诸如以下问题:
- “我的数据库里有哪些表?”
- “给我看看用户表的架构”
- “我有多少活跃用户?”
- “销量前十的产品是什么?”
- “解释选择最近订单的查询计划”
- “给我一份来自客户表的数据样本”
您的代理将自动使用适当的工具来查询您的数据库。
配置参考
数据库配置选项
{
"databases": {
"database_name": {
"type": "postgresql", // Required: postgresql, mysql, sqlite, mssql
"host": "localhost", // Required for all except SQLite
"port": 5432, // Optional: default port for each DB type
"database": "dbname", // Required: database name
"username": "user", // Required for most databases
"password": "pass", // Required for most databases
"read_only": true, // Optional: default true (recommended)
"pool_size": 5, // Optional: connection pool size (default 5)
"max_overflow": 2, // Optional: max extra connections (default 2)
"pool_timeout": 30 // Optional: connection timeout (default 30s)
}
}
}
SQLite 配置
{
"databases": {
"my_sqlite": {
"type": "sqlite",
"path": "./database.db", // Path to SQLite file
"read_only": false // SQLite can be read-write
}
}
}
使用环境变量
您可以在配置中引用环境变量(推荐用于密码):
{
"databases": {
"prod": {
"type": "postgresql",
"host": "localhost",
"username": "$DB_USER", // Will read from environment
"password": "$DB_PASSWORD" // Will read from environment
}
}
}
创建一个 .env 文件:
DB_USER=myuser
DB_PASSWORD=mysecurepassword
可用工具
您的AI代理可以使用以下5种工具:
1. list_databases
列出所有已配置的数据库。
2. get_schema
获取数据库架构信息。
- 不指定表名:列出所有表和列
- 表名为:特定表的详细模式
3. execute_query
执行SQL查询(仅在只读模式下执行SELECT)。
- 自动将结果限制为100行
- 返回JSON格式的数据
4. explain_query
在不执行查询的情况下获取查询执行计划。
- 有助于查询优化
- 展示数据库将如何执行查询
5. get_table_sample
表格数据的快速预览。
- 默认返回前10行
- 快速检查表内容的方法
安全最佳实践
- 始终使用
read_only: true用于生产数据库 - 创建专用的只读数据库用户
- 永远不要将密码提交到版本控制系统中
- 使用环境变量存储敏感凭据
- 限制连接池大小以防止数据库过载
- 在允许写入访问之前审查代理查询
创建只读数据库用户
PostgreSQL:
CREATE USER readonly_user WITH PASSWORD 'password';
GRANT CONNECT ON DATABASE mydb TO readonly_user;
GRANT USAGE ON SCHEMA public TO readonly_user;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly_user;
MySQL:
CREATE USER 'readonly_user'@'localhost' IDENTIFIED BY 'password';
GRANT SELECT ON mydb.* TO 'readonly_user'@'localhost';
启用写入访问权限
⚠️ 警告: 写访问权限允许您的AI代理修改数据!
允许执行INSERT、UPDATE、DELETE操作:
-
首先备份您的数据库
-
改变
"read_only": false在 config.json 中 -
确保数据库用户具有写入权限
-
重启您的代理
-
使用非关键数据进行彻底测试 允许执行INSERT、UPDATE、DELETE操作:
-
改变
"read_only": false在 config.json 中 -
确保数据库用户具有写入权限
-
重启您的代理
-
首先备份您的数据库
看见 WRITE_ACCESS_GUIDE.md 以获取详细说明和安全提示。
发展
项目结构
db-mcp/
├── src/
│ └── db_mcp/
│ ├── __init__.py # Package initialization
│ ├── server.py # Main MCP server
│ ├── database.py # Database connection manager
│ ├── tools.py # MCP tool definitions
│ └── config.py # Configuration handling
├── config.example.json # Example configuration
├── requirements.txt # Python dependencies
├── setup.py # PyPI packaging
└── README.md # This file
运行测试
# Test with SQLite (no setup required)
echo '{"databases": {"test": {"type": "sqlite", "path": ":memory:", "read_only": false}}}' > test_config.json
python src/db_mcp/server.py --config test_config.json
多数据库支持
DB-MCP能够同时连接到多个数据库:
{
"databases": {
"prod_postgres": {
"type": "postgresql",
"host": "prod.server.com",
"database": "production",
"read_only": true
},
"staging_mysql": {
"type": "mysql",
"host": "staging.server.com",
"database": "staging",
"read_only": false
},
"local_sqlite": {
"type": "sqlite",
"path": "./local.db",
"read_only": false
}
}
}
然后,您的代理可以指定要查询哪个数据库:
- “查询prod_postgres数据库”
- “显示 staging_mysql 中的表”
- “将数据添加到本地_sqlite”
性能调优
连接池
根据您的工作负载调整池设置:
{
"pool_size": 10, // Max persistent connections
"max_overflow": 5, // Additional connections during spikes
"pool_timeout": 30, // Wait time for available connection
"pool_recycle": 3600 // Recycle connections after 1 hour
}
查询优化
- 使用
explain_query分析查询性能的工具 - 在经常查询的列上添加索引
- 限制结果集(自动限制为100行)
- 使用连接池(默认启用)
故障排除
“数据库未连接”
- 检查config.json中的数据库凭据
- 验证数据库服务器是否正在运行
- 首先使用数据库客户端测试连接
“队列池限制超出”
- 减少
pool_size在配置中 - 检查长时间运行的查询
- 确保连接被正确释放
“仅允许SELECT查询”
- 数据库处于只读模式(出于安全考虑的设计)
- 改变
read_only: false如果你需要写入权限 - 创建一个独立的非只读数据库配置
Windows ODBC 驱动程序问题(SQL Server)
- 从微软安装“适用于 SQL Server 的 ODBC 驱动程序 17”
- 下载链接:https://docs.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server(下载适用于 SQL Server 的 ODBC 驱动程序)
“未找到 config.json 文件”
- 在Claude Desktop配置中使用绝对路径
- 跑
db-mcp --init生成示例配置 - 确保你处于正确的目录中
命令未找到:db-mcp
- 确保您使用 pip 进行了安装:
pip install db-mcp - 尝试:
python -m db_mcp.server --config config.json - 检查Python脚本目录是否在PATH环境变量中
支持的数据库
| 数据库 | 驱动程序 | 连接字符串格式 |
|---|---|---|
| PostgreSQL | psycopg2 | postgresql://user:pass@host:port/db |
| MySQL | mysql-connector-python(MySQL连接器-Python) | mysql+mysqlconnector://user:pass@host:port/db |
| SQLite | 内置的 | sqlite:///path/to/file.db |
| SQL Server | pyodbc(Python数据库适配器) | mssql+pyodbc://user:pass@host:port/db?driver=... |
开发与贡献
本地开发环境设置
如果您想贡献代码或进行修改:
# Clone the repository
git clone https://github.com/fenil210/Database-MCP
cd Database-MCP
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install in development mode
pip install -e .
# Install all database drivers
pip install -e ".[all]"
项目结构
db-mcp/
├── src/
│ └── db_mcp/
│ ├── __init__.py # Package initialization
│ ├── server.py # Main MCP server
│ ├── database.py # Database connection manager
│ ├── tools.py # MCP tool definitions
│ └── config.py # Configuration handling
├── requirements.txt # Python dependencies
├── setup.py # PyPI packaging
└── README.md # This file
运行测试
# Test with SQLite (no setup required)
db-mcp --init
# Edit config.json to only include the my_sqlite_db entry
db-mcp --config config.json
欢迎投稿!请随时:
- 添加对更多数据库的支持
- 改进错误处理
- 添加更多工具
- 加强文档编制
许可证
MIT 许可证 - 详情请参阅 LICENSE 文件
支持
对于问题和疑问:
- GitHub Issues(问题页面): https://github.com/fenil210/Database-MCP/issues
- MCP 文档:https://modelcontextprotocol.io/
更新日志
版本 0.1.0
- 初始发布
- 支持 PostgreSQL、MySQL、SQLite、SQL Server
- 数据库操作的5大核心工具
- 默认为只读模式
- 连接池
- 环境变量支持
--init用于轻松配置的命令
致谢
由Anthropic采用模型上下文协议(MCP)构建。使用SQLAlchemy实现通用数据库连接。
使用DB-MCP,将任何AI代理连接到任何数据库!
立即安装: pip install db-mcp