数据库浏览器MCP服务器
一个强大的模型上下文协议(MCP)服务器,用于使用自然语言探索和查询数据库。该服务器提供用于连接数据库、探索模式以及使用AI辅助的自然语言到SQL转换执行查询的工具。
🚀 特性
- 多数据库支持:目前支持MySQL(可扩展到PostgreSQL、SQLite等)
- 自然语言查询:使用客户端AI将自然语言问题转换为SQL
- 模式探索:发现数据库结构、表、列、关系和索引
- 安全查询执行:内置安全限制(行限制、超时)以防止资源耗尽
- 连接管理:同时管理多个数据库连接
- MCP协议:实现无缝AI集成的完整模型上下文协议
📋 目录
🔧 安装
先决条件
- Python 3.10或更高版本
- MySQL数据库(或其他支持的数据库)
再进行
使用 uv (推荐):
uv sync或使用 pip:
pip install -e .依赖项
fastmcp>=2.14.3-MCP服务器的FastMCP框架pymysql>=1.1.2-MySQL数据库连接器
🏃 快速开始
1.创建数据库连接配置
在中创建连接配置文件 src/config/connections/:
mkdir -p src/config/connections例子: src/config/connections/my_database.json
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"user": "your_username",
"password": "your_password",
"database": "your_database",
"charset": "utf8mb4"
}安全说明:对于生产环境,使用环境变量作为密码:
{
"type": "mysql",
"host": "localhost",
"user": "your_username",
"password": "env:DB_PASSWORD",
"database": "your_database"
}2.启动MCP服务器
python main.py服务器在stdio上运行,并已准备好接受MCP协议请求。
3.与MCP客户端一起使用
此服务器旨在与MCP兼容的客户端配合使用,例如:
- 克劳德桌面版
- 自定义MCP客户端
- 支持MCP的AI助手
📖 用法
连接管理
列出可用连接
# Returns all configured connections and their status
list_connections_tool()连接到数据库
connect_tool("my_database")测试连接
test_connection_tool("my_database")获取数据库信息
get_database_info_tool("my_database")
# Returns: version, size, character set, table count, etc.断开
disconnect_tool("my_database")模式探索
列出所有表格
list_tables_tool("my_database")获取完整架构
# Get schema for all tables
get_schema_tool("my_database")
# Get schema for specific table
get_schema_tool("my_database", table_name="users")获取详细表格信息
get_table_info_tool("my_database", "users")
# Returns: columns, primary keys, foreign keys, indexes, row count查询执行
自然语言查询(人工智能辅助)
服务器为AI生成SQL提供模式上下文:
result = natural_language_query_tool(
connection_name="my_database",
question="Show me all customers from New York",
max_rows=100
)答复包括:
schema_context:完整的数据库架构prompt:您的AI/LLM即用型提示instructions:分步工作流程
工作流程:
- 服务器提取模式并创建提示
- 客户端使用带有AI的提示生成SQL
- 客户电话
execute_sql_query_tool()使用生成的SQL
执行SQL查询
execute_sql_query_tool(
connection_name="my_database",
sql_query="SELECT * FROM users WHERE city = 'New York' LIMIT 100",
max_rows=1000,
timeout=30
)安全特性:
- 自动行限制(
max_rows) - 查询超时保护(
timeout) - 参数化查询以防止SQL注入
- 自然语言查询的只读强制
📚 API 参考
连接工具
list_connections_tool() -> Dict[str, Any]
列出所有可用的数据库连接。
connect_tool(connection_name: str) -> Dict[str, Any]
使用配置文件连接到数据库。
disconnect_tool(connection_name: str) -> Dict[str, Any]
断开与数据库的连接。
test_connection_tool(connection_name: str) -> Dict[str, Any]
测试数据库连接是否处于活动状态。
get_database_info_tool(connection_name: str) -> Dict[str, Any]
获取有关连接数据库的元数据。
架构工具
get_schema_tool(connection_name: str, table_name: Optional[str] = None) -> Dict[str, Any]
获取所有表或特定表的数据库架构信息。
list_tables_tool(connection_name: str) -> Dict[str, Any]
列出数据库中的所有表。
get_table_info_tool(connection_name: str, table_name: str) -> Dict[str, Any]
获取特定表格的详细信息。
查询工具
natural_language_query_tool(connection_name: str, question: str, max_rows: int = 100) -> Dict[str, Any]
使用客户端的AI将自然语言转换为SQL。返回模式上下文和提示。
execute_sql_query_tool(connection_name: str, sql_query: str, max_rows: int = 1000, timeout: int = 30) -> Dict[str, Any]
在数据库上执行SQL查询。
MCP资源
服务器还公开MCP资源用于模式缓存:
schema://{connection_name}-完整数据库架构schema://{connection_name}/{table_name}-特定表架构connections://list-所有连接列表
🏗️ 建筑
项目结构
EDAEDA/
├── main.py # MCP server entry point
├── pyproject.toml # Project configuration
├── README.md # This file
│
└── src/
├── __init__.py
│
├── database/ # Database abstraction layer
│ ├── __init__.py
│ ├── base.py # Abstract base class
│ └── mysql.py # MySQL implementation
│
├── tools/ # MCP tools
│ ├── __init__.py
│ ├── connection_tools.py # Connection management
│ ├── query_tools.py # Query execution
│ └── schema_tools.py # Schema exploration
│
└── config/
└── connections/ # Connection config files
└── *.json设计原则
- 抽象:数据库无关接口,通过
DatabaseConnection基类 - 安全:内置限制(行限制、超时)可防止资源耗尽
- 可扩展性:易于添加新的数据库类型(PostgreSQL、SQLite等)
- 类型安全:完整的类型提示,以获得更好的IDE支持和错误检测
- 错误处理:具有自定义错误类型的全面异常处理
数据库连接流
1. Client calls connect_tool("my_db")
2. Server loads config from src/config/connections/my_db.json
3. Server creates MySQLConnection instance
4. Server establishes connection using PyMySQL
5. Server stores connection in _active_connections
6. Client can now use other tools with "my_db"自然语言查询流程
1. Client: natural_language_query_tool("my_db", "Show customers from NY")
2. Server: Extracts schema, formats context, creates prompt
3. Server: Returns prompt + schema_context
4. Client: Uses prompt with AI/LLM to generate SQL
5. Client: execute_sql_query_tool("my_db", generated_sql)
6. Server: Executes SQL with safety limits
7. Server: Returns results🔒 安全特性
- 参数化查询:所有查询都使用参数化语句来防止SQL注入
- 只读执行:自然语言查询仅生成SELECT语句
- 行限制:自动限制结果集
- 超时:查询执行超时阻止挂起操作
- 环境变量:通过env-vars支持安全密码存储
🛠️ 发展
运行测试
# Run connection test
python test_mysql_connection.py代码质量
该项目使用:
- 全程键入提示
- 全面的文档字符串
- 调试日志
- 处理自定义异常时出错
添加新数据库类型
- 创建一个继承自的新类
DatabaseConnection - 实现所有抽象方法
- 添加
DatabaseType枚举 - 在中更新连接工厂
connection_tools.py
示例结构:
class PostgreSQLConnection(DatabaseConnection):
def connect(self, config: Dict[str, Any]) -> bool:
# Implementation
pass
# ... implement other abstract methods📝 配置示例
MySQL连接
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"user": "root",
"password": "env:MY_DB_PASSWORD",
"database": "mydb",
"charset": "utf8mb4",
"ssl": false,
"connect_timeout": 10
}使用SSL的远程MySQL
{
"type": "mysql",
"host": "db.example.com",
"port": 3306,
"user": "app_user",
"password": "env:PROD_DB_PASSWORD",
"database": "production_db",
"charset": "utf8mb4",
"ssl": true,
"connect_timeout": 30
}🐛 故障排除
连接问题
错误:“找不到配置文件”
- 确保配置文件存在于
src/config/connections/ - 检查文件名是否与连接名称完全匹配
错误:“未设置环境变量”
- 设置环境变量:
export DB_PASSWORD=your_password - 或者在配置中使用直接密码(不建议用于生产)
错误:“连接被拒绝”
- 验证数据库是否正在运行
- 检查主机、端口和防火墙设置
- 验证凭据
查询问题
错误:“查询超时”
- 增加
timeout参数 - 优化您的查询
- 检查数据库性能
警告:“结果可能被截断”
- 增加
max_rows参数(如果需要) - 这是一种安全功能,可防止出现大的结果集
🤝 贡献
欢迎投稿!需要改进的地方:
- 额外的数据库支持(PostgreSQL、SQLite等)
- 查询优化建议
- 增强的模式分析
- 性能改进
- 文档改进
📄 许可证
\[在此处添加您的许可证\]
🙏 致谢
📞 支持
对于问题、疑问或贡献,请在存储库上打开问题。
______________________________________________________________________
版本: 0.1.0\ python: 3.10+\ 状态:积极发展
