使用说明
数据库MCP服务器
一种模型上下文协议(MCP)服务器,为LLM驱动的应用程序提供数据库操作作为工具。支持PostgreSQL、MySQL和MongoDB数据库,具有连接池和灵活的结果格式。
特性
- 多数据库支持:PostgreSQL、MySQL和MongoDB
- 连接池:高效的数据库连接管理
- 多种结果格式:JSON和Markdown表格输出
- 流式HTTP:通过HTTP的现代MCP传输
- 异步操作:对非阻塞数据库查询的完全异步/等待支持
工具
| 工具 | 说明 |
|---|---|
execute_query |
对数据库执行任意SQL查询 |
list_databases |
列出所有可用数据库 |
list_tables |
列出数据库中的所有表(默认为已配置的数据库) |
describe_table |
获取特定表的架构信息 |
需求
- Python 3.11+
- PostgreSQL 12+、MySQL 8.0+或MongoDB 4.0+
安装
# Clone the repository
git clone <repository-url>
cd database-mcp-server
# Install dependencies using uv (recommended)
uv pip install -e .
# Or using pip
pip install -e .
配置
复制 .env.example 到 .env 并配置环境变量:
cp .env.example .env
然后编辑 .env 使用您的数据库凭据和设置:
# Database Configuration
DATABASE_PROVIDER=postgres # or mysql, mongodb
DATABASE_HOST=localhost
DATABASE_PORT=5432 # 3306 for MySQL, 27017 for MongoDB
DATABASE_USER=your_username
DATABASE_PASSWORD=your_password
DATABASE_NAME=your_database
DATABASE_MIN_POOL_SIZE=1
DATABASE_MAX_POOL_SIZE=10
# Server Configuration (optional)
HTTP_HOST=0.0.0.0 # Bind address (defaults to all interfaces)
HTTP_PORT=8080
配置选项
| 变量 | 必填 | 默认 | 描述 |
|---|---|---|---|
DATABASE_PROVIDER |
是 | - | 数据库提供程序: postgres, mysql,或 mongodb |
DATABASE_HOST |
是 | - | 数据库服务器主机名或IP |
DATABASE_PORT |
是 | - | 数据库服务器端口(PostgreSQL为5432,MySQL为3306,MongoDB为27017) |
DATABASE_USER |
是 | - | 数据库用户名 |
DATABASE_PASSWORD |
否 | - | 数据库密码 |
DATABASE_NAME |
是 | - | 要连接的默认数据库 |
DATABASE_MIN_POOL_SIZE |
是 | - | 连接的最小池大小 |
DATABASE_MAX_POOL_SIZE |
是 | - | 连接的最大池大小 |
HTTP_HOST |
没有 | 0.0.0.0 |
HTTP服务器绑定地址 |
HTTP_PORT |
MCP没有 | 8080 | HTTP服务器端口 |
READ_ONLY_MODE |
没有 | true |
启用只读模式(阻止写入操作) |
只读模式
默认情况下,服务器以只读模式运行,以防止意外的数据修改。启用时:
- PostgreSQL/MySQL:只有
SELECT,SHOW,以及DESCRIBE允许查询 - MongoDB:仅读取操作(
find,find_one,aggregate,count)被允许
写入操作如下 INSERT, UPDATE, DELETE, DROP, CREATE, ALTER 被封锁。
要禁用只读模式(允许所有操作):
READ_ONLY_MODE=false
用法
运行服务器
# Using uv (recommended)
uv run python main.py
# Using Python directly
python main.py
MCP客户端配置
将服务器添加到MCP客户端配置中:
使用紫外线(建议用于依赖隔离):
{
"mcpServers": {
"sql": {
"command": "uv",
"args": [
"--directory",
"/path/to/database-mcp-server",
"run",
"python",
"main.py"
]
}
}
}
直接使用Python:
{
"mcpServers": {
"sql": {
"command": "python",
"args": ["/path/to/database-mcp-server/main.py"]
}
}
}
直接HTTP连接:
服务器公开了一个可流式传输的HTTP端点。配置您的MCP客户端以直接连接:
{
"mcpServers": {
"sql": {
"url": "http://localhost:8080/mcp"
}
}
}
备注:对于直接HTTP连接,请确保服务器正在运行,并且可以在指定的URL上访问。
工具调用示例
常见示例(所有提供商)
# List all databases
list_databases()
# List tables/collections in the configured database
list_tables()
# List tables/collections in a specific database
list_tables(database="another_db")
# Describe a table/collection schema
describe_table("users")
PostgreSQL/MySQL示例(SQL)
对于PostgreSQL和MySQL,使用标准SQL语法:
# Execute a SELECT query
execute_query("SELECT * FROM users WHERE active = true LIMIT 10")
# Execute with specific columns
execute_query("SELECT name, email FROM users WHERE age > 18")
# Get results in Markdown format
execute_query("SELECT name, email FROM users", format_type="markdown")
# INSERT, UPDATE, DELETE queries
execute_query("INSERT INTO users (name, email) VALUES ('John', 'john@example.com')")
execute_query("UPDATE users SET status = 'active' WHERE status = 'pending'")
execute_query("DELETE FROM users WHERE inactive = true")
# Join queries
execute_query("""
SELECT u.name, o.order_id
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.active = true
""")
MongoDB示例(JSON)
对于MongoDB,查询使用JSON格式,操作类型为:
# Find documents
execute_query('{"collection": "users", "operation": "find", "filter": {"active": true}, "limit": 10}')
# Find with projection (select specific fields)
execute_query('{"collection": "users", "operation": "find", "projection": {"name": 1, "email": 1}}')
# Find with sorting and pagination
execute_query('{"collection": "users", "operation": "find", "filter": {"active": true}, "sort": {"created_at": -1}, "skip": 0, "limit": 20}')
# Find one document
execute_query('{"collection": "users", "operation": "find_one", "filter": {"_id": "64f8a2b1c9d8e7f6a5b4c3d2"}}')
# Insert a document
execute_query('{"collection": "users", "operation": "insert_one", "document": {"name": "John", "email": "john@example.com", "created_at": "2024-01-15T10:30:00"}}')
# Insert multiple documents
execute_query('{"collection": "users", "operation": "insert_many", "documents": [{"name": "John"}, {"name": "Jane"}]}')
# Update documents
execute_query('{"collection": "users", "operation": "update_one", "filter": {"email": "john@example.com"}, "update": {"$set": {"status": "active"}}}')
execute_query('{"collection": "users", "operation": "update_many", "filter": {"status": "pending"}, "update": {"$set": {"status": "active"}}}')
# Delete documents
execute_query('{"collection": "users", "operation": "delete_one", "filter": {"email": "john@example.com"}}')
execute_query('{"collection": "users", "operation": "delete_many", "filter": {"inactive": true}}')
# Aggregation pipeline
execute_query('{"collection": "orders", "operation": "aggregate", "pipeline": [{"$group": {"_id": "$status", "count": {"$sum": 1}}}]}')
# Count documents
execute_query('{"collection": "users", "operation": "count", "filter": {"active": true}}')
支持的MongoDB操作:
| 操作 | 说明 |
|---|---|
find |
使用可选过滤器、投影、排序、跳过、限制查询文档 |
find_one |
按筛选器查询单个文档 |
insert_one |
插入单个文档 |
insert_many |
插入多个文档 |
update_one |
更新单个文档匹配筛选器 |
update_many |
更新与筛选器匹配的多个文档 |
delete_one |
删除单个文档匹配筛选器 |
delete_many |
删除多个匹配筛选器的文档 |
aggregate |
运行聚合管道 |
count |
统计与筛选器匹配的文档 |
查询格式参考:
{
"collection": "collection_name", // Required: Collection to query
"operation": "find", // Required: Operation type (see above)
"filter": {}, // Optional: Query filter (MongoDB query syntax)
"projection": {}, // Optional: Fields to include/exclude
"sort": {"field": 1}, // Optional: Sort order (1=asc, -1=desc)
"skip": 0, // Optional: Number of documents to skip
"limit": 10, // Optional: Maximum documents to return
"document": {}, // For insert_one: Document to insert
"documents": [{}, {}], // For insert_many: Array of documents
"update": {"$set": {}}, // For update operations: Update operators
"pipeline": [{}, {}] // For aggregate: Aggregation pipeline stages
}
项目结构
database-mcp-server/
├── main.py # Entry point
├── pyproject.toml # Project configuration
├── .env # Environment variables (create this)
└── src/
├── server.py # MCP server and tool definitions
├── lib/
│ ├── config.py # Configuration management
│ ├── utils.py # Utility functions
│ ├── middleware.py # Middleware for MCP server
│ └── mcp.py # MCP-specific utilities
└── database/
├── manager.py # Database connection pool manager
├── formatter.py # Result formatting (JSON/Markdown)
├── postgres_client.py # PostgreSQL-specific operations
├── mysql_client.py # MySQL-specific operations
└── mongodb_client.py # MongoDB-specific operations
发展
# Run in development mode with auto-reload (requires watching tool)
uv run watch -c "python main.py" .
依赖项
| 包装 | 用途 |
|---|---|
mcp>=1.26.0 |
模型上下文协议框架 |
asyncpg |
PostgreSQL异步驱动程序 |
aiomysql |
MySQL异步驱动程序 |
pymongo>=4.9.0 |
MongoDB异步驱动程序 |
python-dotenv |
环境变量管理 |
运行测试
测试尚未实施。
许可证
麻省理工学院
更新日志
v1.2.0(2026-02-19)
- 添加了MCP中间件支持(
src/lib/middleware.py) - 添加了MCP实用程序模块(
src/lib/mcp.py) - 添加了ruff代码格式化程序和linter配置
v1.1.0版本(2026-02-14)
- 通过PyMongo异步驱动程序添加了对MongoDB的支持
- 新
mongodb_client.py具有完整的CRUD操作(查找、插入、更新、删除、聚合、计数) - 模式推理
describe_table通过文件抽样 - MongoDB的连接池支持
- 更新文档,提供特定于提供商的示例
v1.0.0(2026-02-05)
- 初始版本
- 为MCP添加了流式HTTP传输支持
- 将HTTP主机配置分离到专用环境变量中
- 添加了全面的README文档
- 改进了服务器模块组织(将server.py移动到src/server.py)
- 添加了示例.env配置文件