MySQL MCP服务器
一种安全的模型上下文协议(MCP)服务器,使大型语言模型(LLM)能够通过标准化的接口与MySQL数据库进行交互。该服务器提供具有全面安全控制的读写操作,使其成为人工智能驱动的数据库交互的理想选择。
🌟 特性
- 🛡️ 缺省巩固安全:只读模式,可选写操作
- 🚀 高性能:连接池和查询优化
- 🔐 SQL注入保护:参数化查询和标识符验证
- 📊 综合工具集:18个数据库操作工具
- ⚡ 速率限制:可配置的限制以防止滥用
- 📝 审计日志:JSON格式的完整操作历史记录
- 🔄 资源系统:将数据库模式作为MCP资源公开
- ⏱️ 查询超时:防止长时间运行的查询
- 🎯 结果限制:内存高效的结果处理
📋 目录
🚀 安装
先决条件
- Node.js 18或更高版本
- MySQL 5.7+或MariaDB 10.2+
- npm或yarn包管理器
步骤1:克隆和构建
git clone https://github.com/yourusername/mav-mysql-mcp-server.git
cd mav-mysql-mcp-server
npm install
npm run build步骤2:创建MySQL只读用户(推荐)
为了安全起见,请创建一个专用的只读用户:
mysql -u root -p ? AND city = ?",
"params": [18, "New York"]
}2. list_tables -列出数据库表
获取当前数据库中的所有表。
{}返回:表名数组
3. describe_table -获取表架构
获取有关表结构的详细信息。
{
"table": "users"
}返回:具有类型、可空性、默认值等的列定义。
4. database_info -数据库统计
获取全面的数据库信息。
{}返回:数据库版本、大小、表计数、字符集等。
5. show_indexes -显示表索引
列出特定表的所有索引。
{
"table": "orders"
}6. explain_query -查询执行计划
分析查询性能。
{
"sql": "SELECT * FROM orders JOIN users ON orders.user_id = users.id WHERE orders.total > 100"
}7. show_constraints -表约束
显示外键和唯一约束。
{
"table": "order_items"
}写入操作工具(需要 ALLOW_WRITE_OPERATIONS=true)
8. insert -插入单行
在表中插入新行。
{
"table": "users",
"data": {
"name": "John Doe",
"email": "john@example.com",
"age": 30
}
}9. update -更新行
用条件更新现有行。
{
"table": "users",
"data": {
"status": "active",
"updated_at": "2024-01-01 00:00:00"
},
"where": {
"id": 123
}
}10. delete -删除行
删除符合条件的行。
{
"table": "sessions",
"where": {
"expired": true
}
}11. bulk_insert -插入多行
在一次操作中高效地插入多行。
{
"table": "products",
"rows": [
{"name": "Product 1", "price": 19.99},
{"name": "Product 2", "price": 29.99},
{"name": "Product 3", "price": 39.99}
]
}12. create_table -创建新表
使用指定列创建新表。
{
"table": "products",
"columns": [
{
"name": "id",
"type": "INT",
"primary": true,
"autoIncrement": true
},
{
"name": "name",
"type": "VARCHAR(255)",
"nullable": false
},
{
"name": "price",
"type": "DECIMAL(10,2)",
"nullable": false,
"default": "0.00"
},
{
"name": "created_at",
"type": "TIMESTAMP",
"default": "CURRENT_TIMESTAMP"
}
]
}13. alter_table -修改表结构
添加、删除、修改或重命名列。
{
"table": "users",
"operation": "add_column",
"column": {
"name": "phone",
"type": "VARCHAR(20)",
"nullable": true,
"after": "email"
}
}操作: add_column, drop_column, modify_column, rename_column
14. drop_table -删除表
放下一张桌子(需要确认)。
{
"table": "old_logs",
"confirm": "DROP_TABLE_old_logs"
}15. add_index -创建索引
添加索引以提高查询性能。
{
"table": "orders",
"indexName": "idx_user_date",
"columns": ["user_id", "order_date"],
"unique": false
}16. drop_index -删除索引
删除现有索引。
{
"table": "orders",
"indexName": "idx_user_date"
}17. rename_table -重命名表
重命名现有表。
{
"oldName": "user_profiles",
"newName": "profiles"
}18. execute_procedure -调用存储过程
使用参数执行存储过程。
{
"procedure": "calculate_user_stats",
"params": [123, "2024-01-01"]
}🔒 安全功能
1.访问控制
- 默认情况下为只读:必须显式启用写入操作
- 系统表保护:访问mysql。*,信息模式。*等被阻塞
- 敏感数据检测:包含密码/令牌/秘密模式的查询被阻止
2.SQL注入防护
- 参数化查询:所有用户输入都已正确转义
- 标识符验证:表/列名必须是字母数字+下划线
- 查询模式匹配:检测并阻止危险操作
3.操作限制
- 无文件操作:进入OUTFILE,加载数据被阻止
- 没有权限更改:格兰特,雷沃基被阻止
- 无系统命令:系统功能被阻止
4.费率限制
- 每分钟查询限制
- 每小时查询限制
- 并发查询限制
- 达到限制时自动节流
5.审计追踪
所有操作都记录在:
- 时间戳
- 查询类型和详细信息
- 用户信息
- 执行时间
- 成功/失败状态
📚 使用示例
基本查询示例
// In Claude or another MCP client
const result = await use_mcp_tool({
server_name: "mysql-myproject",
tool_name: "query",
arguments: {
sql: "SELECT id, name, email FROM users WHERE created_at > ? ORDER BY created_at DESC LIMIT 10",
params: ["2024-01-01"]
}
});创建带索引的表
// Create the table
await use_mcp_tool({
server_name: "mysql-myproject",
tool_name: "create_table",
arguments: {
table: "products",
columns: [
{ name: "id", type: "INT", primary: true, autoIncrement: true },
{ name: "sku", type: "VARCHAR(50)", nullable: false },
{ name: "name", type: "VARCHAR(255)", nullable: false },
{ name: "price", type: "DECIMAL(10,2)", nullable: false },
{ name: "category_id", type: "INT", nullable: false }
]
}
});
// Add indexes
await use_mcp_tool({
server_name: "mysql-myproject",
tool_name: "add_index",
arguments: {
table: "products",
indexName: "idx_sku",
columns: ["sku"],
unique: true
}
});批量操作
// Bulk insert
await use_mcp_tool({
server_name: "mysql-myproject",
tool_name: "bulk_insert",
arguments: {
table: "inventory_updates",
rows: [
{ product_id: 1, quantity: 100, updated_by: "system" },
{ product_id: 2, quantity: 50, updated_by: "system" },
{ product_id: 3, quantity: 75, updated_by: "system" }
]
}
});🏗️ 建筑
组件概述
┌─────────────────┐ ┌──────────────────┐ ┌──────────────┐
│ MCP Client │────▶│ MCP Server │────▶│ MySQL │
│ (Claude) │◀────│ (This Tool) │◀────│ Database │
└─────────────────┘ └──────────────────┘ └──────────────┘
│ │ │
│ ├── Connection Pool │
│ ├── Query Validator │
│ ├── Rate Limiter │
│ └── Audit Logger │
│ │
└───────────── stdio (JSON-RPC) ────────────────┘关键组件
- MCP协议处理程序 (
server.ts)
- 处理工具和资源请求 - 通往合适处理者的路线 - 管理协议合规性
- 数据库管理器 (
database.ts)
- 连接池 - 查询执行 - 交易管理 - 安全验证
- 安全层
- 输入验证 - 查询分析 - 权限检查 - 速率限制
- 记录系统 (
logger.ts)
- 结构化JSON日志记录 - 审计跟踪 - 误差跟踪 - 性能指标
设计模式
- 工厂模式:数据库连接创建
- 存储库模式:数据库操作封装
- 策略模式:用于各种操作的不同处理程序
- 防护图案:多个验证层
🔧 故障排除
常见问题
连接被拒绝
Error: connect ECONNREFUSED 127.0.0.1:3306解决方案:确保MySQL在指定的主机/端口上运行并可访问。
认证失败
Error: Access denied for user 'username'@'localhost'解决方案:验证用户名、密码和用户权限。
速率限制已超出
Error: Rate limit exceeded. Please wait before making more requests.解决方案:降低查询频率或增加配置中的速率限制。
查询超时
Error: Query timeout of 30000ms exceeded解决方案:优化您的查询或增加query_TIMEOUT设置。
调试模式
启用调试日志记录以获取详细信息:
MCP_DEBUG=true node build/index.js健康检查
测试您的连接:
await use_mcp_tool({
server_name: "mysql-myproject",
tool_name: "database_info",
arguments: {}
});🤝 贡献
我们欢迎捐款!请查看我们的 贡献指南 了解详情。
开发设置
# Clone the repository
git clone https://github.com/yourusername/mav-mysql-mcp-server.git
cd mav-mysql-mcp-server
# Install dependencies
npm install
# Run in development mode
npm run dev
# Run tests
npm test
# Build for production
npm run build代码风格
- 具有严格模式的TypeScript
- 包括ESLint配置
- 格式化预处理
- 常规承诺
📄 许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
🙏 致谢
📞 支持
- 问题:
- 讨论:
- 安全:向报告漏洞derrick@derricksiawor.com
______________________________________________________________________
由以下材料制成❤️ 作者Derrick S.K.Siawor
