{"id":35094189,"url":"https://github.com/guangxiangdebizi/MySQL_MCP","last_synced_at":"2026-01-07T10:02:52.071Z","repository":{"id":295264703,"uuid":"989640454","full_name":"guangxiangdebizi/MySQL_MCP","owner":"guangxiangdebizi","description":"这是一个功能强大且易用的MySQL数据库MCP（Model Context Protocol）服务器，让你的AI助手可以安全地进行完整的数据库操作，支持多数据库连接管理、增删改查、事务管理和智能回滚功能。","archived":false,"fork":false,"pushed_at":"2025-12-17T02:47:36.000Z","size":10047,"stargazers_count":51,"open_issues_count":3,"forks_count":52,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-12-19T15:33:03.244Z","etag":null,"topics":["database","llm","llm2sql","mcp","mysql","rag","txt2sql"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/guangxiangdebizi.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-05-24T14:16:42.000Z","updated_at":"2025-12-18T02:14:28.000Z","dependencies_parsed_at":"2025-05-24T15:49:12.605Z","dependency_job_id":"6eaa7541-a386-4e19-9d60-1211468b0fb3","html_url":"https://github.com/guangxiangdebizi/MySQL_MCP","commit_stats":null,"previous_names":["guangxiangdebizi/mysql_mcp"],"tags_count":7,"template":false,"template_full_name":null,"purl":"pkg:github/guangxiangdebizi/MySQL_MCP","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/guangxiangdebizi%2FMySQL_MCP","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/guangxiangdebizi%2FMySQL_MCP/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/guangxiangdebizi%2FMySQL_MCP/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/guangxiangdebizi%2FMySQL_MCP/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/guangxiangdebizi","download_url":"https://codeload.github.com/guangxiangdebizi/MySQL_MCP/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/guangxiangdebizi%2FMySQL_MCP/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28234560,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2026-01-07T02:00:05.975Z","response_time":58,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","llm","llm2sql","mcp","mysql","rag","txt2sql"],"created_at":"2025-12-27T15:04:24.313Z","updated_at":"2026-01-07T10:02:52.066Z","avatar_url":"https://github.com/guangxiangdebizi.png","language":"TypeScript","funding_links":[],"categories":["📚 Projects (1974 total)"],"sub_categories":["MCP Servers"],"readme":"# MySQL MCP Server 🚀\n\n\u003e **v4.0.0** - 全新架构重写，更简洁、更强大！\n\n一个功能强大且易用的 MySQL 数据库 MCP（Model Context Protocol）服务器，支持 AI 助手安全地操作 MySQL 数据库。\n\n## 🌟 核心特性\n\n- 🌐 **StreamableHTTP 协议** - 基于最新 MCP 规范实现\n- 🔐 **Header 预配置** - 凭证不暴露给 AI，安全可靠\n- 🤖 **AI 动态管理** - AI 可以帮你添加/切换数据库连接\n- 🔗 **多数据库支持** - 同时管理多个数据库，随时切换\n- 📊 **完整 CRUD** - 支持所有 SQL 操作\n- 🏗️ **模块化架构** - 清晰的目录结构，易于扩展\n\n---\n\n## 📦 安装\n\n### 环境要求\n\n- Node.js 18+\n- MySQL 5.7+ 或 8.0+\n- MCP 客户端（Claude Desktop、Cursor 等）\n\n### 安装步骤\n\n```bash\n# 克隆项目\ngit clone https://github.com/guangxiangdebizi/MySQL_MCP.git\ncd MySQL_MCP\n\n# 安装依赖\nnpm install\n\n# 编译\nnpm run build\n\n# 启动服务器\nnpm start\n```\n\n---\n\n## ⚙️ 配置方法\n\n### 方式一：Header 预配置（推荐）\n\n编辑 MCP 配置文件：\n\n**Windows**: `%APPDATA%\\Claude\\claude_desktop_config.json`  \n**macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`  \n**Linux**: `~/.config/Claude/claude_desktop_config.json`\n\n#### 单数据库配置\n\n```json\n{\n  \"mcpServers\": {\n    \"mysql-mcp\": {\n      \"type\": \"streamableHttp\",\n      \"url\": \"http://localhost:3001/mcp\",\n      \"timeout\": 600,\n      \"headers\": {\n        \"X-MySQL-Host\": \"localhost\",\n        \"X-MySQL-Port\": \"3306\",\n        \"X-MySQL-User\": \"root\",\n        \"X-MySQL-Password\": \"your_password\",\n        \"X-MySQL-Database\": \"your_database\"\n      }\n    }\n  }\n}\n```\n\n#### 多数据库配置\n\n```json\n{\n  \"mcpServers\": {\n    \"mysql-mcp\": {\n      \"type\": \"streamableHttp\",\n      \"url\": \"http://localhost:3001/mcp\",\n      \"timeout\": 600,\n      \"headers\": {\n        \"X-MySQL-Host-1\": \"prod.mysql.com\",\n        \"X-MySQL-User-1\": \"prod_user\",\n        \"X-MySQL-Password-1\": \"prod_pass\",\n        \"X-MySQL-Database-1\": \"production\",\n        \n        \"X-MySQL-Host-2\": \"test.mysql.com\",\n        \"X-MySQL-User-2\": \"test_user\",\n        \"X-MySQL-Password-2\": \"test_pass\",\n        \"X-MySQL-Database-2\": \"testing\"\n      }\n    }\n  }\n}\n```\n\n**优势：**\n- ✅ 数据库凭证不暴露给 AI\n- ✅ 启动即连接，无需手动操作\n- ✅ 支持多数据库同时连接\n\n### 方式二：AI 动态添加（灵活）\n\n不配置 Header，让 AI 在对话中帮你添加连接：\n\n```json\n{\n  \"mcpServers\": {\n    \"mysql-mcp\": {\n      \"type\": \"streamableHttp\",\n      \"url\": \"http://localhost:3001/mcp\",\n      \"timeout\": 600\n    }\n  }\n}\n```\n\n**使用示例：**\n```\n你: 帮我连接到本地 MySQL，用户名 root，密码 123456，数据库 mydb\nAI: [调用 add_connection 工具]\n```\n\n---\n\n## 🔧 工具列表\n\n### 连接管理\n\n| 工具名称 | 功能说明 | 使用场景 |\n|---------|---------|---------|\n| `add_connection` | 添加数据库连接 | AI 帮你动态添加新连接 |\n| `list_connections` | 列出所有连接 | 查看当前有哪些数据库 |\n| `select_database` | 选择活跃数据库 | 切换到其他数据库 |\n| `remove_connection` | 移除连接 | 清理不需要的连接 |\n\n### 查询操作\n\n| 工具名称 | 功能说明 | 使用场景 |\n|---------|---------|---------|\n| `execute_query` | 执行 SQL | 任何 SQL 操作（SELECT、INSERT、UPDATE、DELETE） |\n| `show_tables` | 显示所有表 | 快速了解数据库结构 |\n| `describe_table` | 查看表结构 | 查看字段、类型、样本数据 |\n| `show_databases` | 显示所有数据库 | 查看可访问的数据库列表 |\n\n---\n\n## 🎮 使用示例\n\n### 场景一：使用 Header 预配置\n\n```\n你: 显示所有表\nAI: [调用 show_tables] \n    📊 数据库表列表 (共 5 个表)\n    1. users\n    2. orders\n    3. products\n    ...\n\n你: 查看 users 表的结构\nAI: [调用 describe_table，参数：users]\n    📋 表结构: users\n    字段信息:\n    - id (INT, 主键)\n    - name (VARCHAR)\n    - email (VARCHAR)\n    ...\n```\n\n### 场景二：AI 动态添加连接\n\n```\n你: 帮我连接两个数据库：\n    1. 生产库：prod.mysql.com，用户 admin，密码 xxx，数据库 shop\n    2. 测试库：test.mysql.com，用户 tester，密码 yyy，数据库 shop_test\n\nAI: [调用 add_connection，参数：id=prod, host=prod.mysql.com...]\n    [调用 add_connection，参数：id=test, host=test.mysql.com...]\n    ✅ 两个数据库连接已添加\n\n你: 列出所有连接\nAI: [调用 list_connections]\n    📊 当前数据库连接列表 (共 2 个)\n    🟢 [1] prod\n       └─ prod.mysql.com:3306/shop\n       └─ ✅ 当前活跃连接\n    ⚪ [2] test\n       └─ test.mysql.com:3306/shop_test\n\n你: 切换到测试库\nAI: [调用 select_database，参数：test]\n    ✅ 已选择数据库: test\n\n你: 查询用户表前 10 条\nAI: [调用 execute_query，SQL: SELECT * FROM users LIMIT 10]\n    ✅ 查询成功，返回 10 行数据\n    [显示 JSON 格式数据]\n```\n\n---\n\n## 🏗️ 项目架构\n\n```\nMySQL_MCP/\n├── src/\n│   ├── index.ts              # 主入口（HTTP Server + 会话管理）\n│   ├── database.ts           # 数据库连接管理器\n│   └── tools/                # 工具模块\n│       ├── index.ts          # 工具统一导出和路由\n│       ├── connection.ts     # 连接管理工具\n│       └── query.ts          # 查询工具\n├── dist/                     # 编译后的 JS 文件\n├── package.json\n├── tsconfig.json\n└── README.md\n```\n\n**核心设计：**\n- **index.ts** - Express HTTP 服务器 + MCP Server 初始化\n- **database.ts** - 封装数据库连接池和查询逻辑\n- **tools/** - 每个文件负责一类工具的定义和处理\n\n---\n\n## 🔒 安全建议\n\n### 数据库权限配置\n\n为 MCP 创建专用数据库用户，限制权限：\n\n```sql\n-- 创建专用用户\nCREATE USER 'mcp_user'@'%' IDENTIFIED BY 'strong_password';\n\n-- 授予必要权限\nGRANT SELECT, INSERT, UPDATE, DELETE ON your_database.* TO 'mcp_user'@'%';\n\n-- 生产环境只读用户\nGRANT SELECT ON your_database.* TO 'mcp_readonly'@'%';\n```\n\n### HTTP 模式安全\n\n- ✅ 使用 Header 预配置，避免凭证暴露给 AI\n- ✅ 生产环境使用 HTTPS（Nginx 反向代理）\n- ✅ 限制访问 IP（防火墙规则）\n- ✅ 定期更新数据库密码\n- ✅ 监控日志，发现异常访问\n\n---\n\n## 🚀 NPM 脚本\n\n```bash\n# 开发模式（TypeScript 直接运行）\nnpm run dev\n\n# 编译\nnpm run build\n\n# 生产模式（运行编译后的 JS）\nnpm start\n\n# 全局安装\nnpm run install-global\n```\n\n---\n\n## 📝 环境变量\n\n创建 `.env` 文件（可选）：\n\n```env\n# HTTP 服务器端口\nPORT=3001\n\n# Node 环境\nNODE_ENV=production\n```\n\n---\n\n## ❗ 常见问题\n\n### 1. 端口被占用\n\n**错误：** `EADDRINUSE: address already in use :::3001`\n\n**解决：** 修改 `.env` 文件中的 `PORT`，或终止占用进程\n\n```bash\n# Windows\nnetstat -ano | findstr :3001\ntaskkill /F /PID \u003cPID\u003e\n\n# Linux/Mac\nlsof -ti:3001 | xargs kill -9\n```\n\n### 2. 连接失败\n\n**错误：** `数据库连接失败`\n\n**检查：**\n- MySQL 服务是否运行\n- 主机、端口、用户名、密码是否正确\n- 防火墙是否允许连接\n\n### 3. 会话丢失\n\n**问题：** 重启服务器后提示 \"Session not found\"\n\n**原因：** 会话存储在内存中，重启后清空\n\n**解决：** 刷新 MCP 客户端（重新初始化）\n\n### 4. 连接已关闭错误\n\n**错误：** `Can't add new command when connection is in closed state`\n\n**原因：** \n- 数据库连接长时间空闲，MySQL 服务器关闭了连接\n- 网络中断导致连接断开\n\n**解决方案：** \n- ✅ v4.0.5+ 已使用连接池替代单连接，自动支持：\n  - 连接保活（Keep-Alive）机制\n  - 自动重连功能\n  - 并发查询支持\n- 如果仍遇到问题，请重启 MCP 服务器\n\n---\n\n## 📦 版本历史\n\n### v4.0.5 (2025-12-09) - 连接池优化\n\n- 🎯 使用连接池替代单连接\n- 🔄 自动连接保活（Keep-Alive）\n- 🔌 自动重连机制\n- 🚀 支持并发查询\n- 🐛 修复 \"connection in closed state\" 错误\n\n### v4.0.0 (2025-12-09) - 全新架构\n\n- 🔥 完全重写，全新模块化架构\n- ✨ 基于最新 MCP StreamableHTTP 协议\n- 🎯 简化工具：连接管理 + 查询操作\n- 🏗️ 清晰的目录结构：`tools/` 模块化\n- 🚀 更快的响应速度\n- 📖 更清晰的代码注释\n\n### v3.x - 旧版本\n\n- 支持事务管理、回滚等复杂功能\n- 较为复杂的架构\n\n---\n\n## 📞 支持与反馈\n\n- 🐛 **问题报告**: [GitHub Issues](https://github.com/guangxiangdebizi/MySQL_MCP/issues)\n- 💡 **功能建议**: [GitHub Discussions](https://github.com/guangxiangdebizi/MySQL_MCP/discussions)\n- 📧 **联系作者**: guangxiangdebizi@gmail.com\n\n---\n\n## 🔧 故障排除\n\n### 问题：`ERR_MODULE_NOT_FOUND` 错误\n\n**错误信息**：\n```\nError [ERR_MODULE_NOT_FOUND]: Cannot find module '...@modelcontextprotocol/sdk...'\n```\n\n**解决方案**：\n\n1. **删除并重新安装依赖**：\n```bash\n# 删除旧依赖\nrm -rf node_modules package-lock.json  # Linux/Mac\n# 或\nrmdir /s /q node_modules \u0026\u0026 del package-lock.json  # Windows\n\n# 清理缓存\nnpm cache clean --force\n\n# 重新安装\nnpm install\n```\n\n2. **检查 Node.js 版本**：\n```bash\nnode --version  # 需要 \u003e= 18.0.0\n```\n\n3. **使用全局安装**：\n```bash\nnpm install -g @xingyuchen/mysql-mcp-server@latest\n```\n\n### 问题：SSE 流断开\n\n**错误信息**：\n```\nSSE stream disconnected: TypeError: terminated\n```\n\n**解决方案**：\n\n在 `mcp.json` 中设置更长的超时或禁用超时：\n```json\n{\n  \"mysql-mcp-http\": {\n    \"type\": \"streamableHttp\",\n    \"url\": \"http://localhost:3002/mcp\",\n    \"timeout\": 0,  // 0 表示无超时限制\n    \"headers\": { ... }\n  }\n}\n```\n\n### 问题：安全漏洞警告\n\n**警告信息**：\n```\nnpm audit: vulnerabilities found\n```\n\n**解决方案**：\n```bash\n# 自动修复\nnpm audit fix\n\n# 如果还有问题，强制修复\nnpm audit fix --force\n\n# 重新构建\nnpm run build\n```\n\n### 问题：端口被占用\n\n**错误信息**：\n```\nError: listen EADDRINUSE: address already in use :::3002\n```\n\n**解决方案**：\n\n1. **更改端口**（在 `.env` 文件中）：\n```env\nPORT=3003\n```\n\n2. **或者关闭占用端口的进程**：\n```bash\n# Windows\nnetstat -ano | findstr :3002\ntaskkill /PID \u003c进程ID\u003e /F\n\n# Linux/Mac\nlsof -i :3002\nkill -9 \u003c进程ID\u003e\n```\n\n### 获取更多帮助\n\n- 🐛 [提交 Issue](https://github.com/guangxiangdebizi/MySQL_MCP/issues)\n- 📖 [查看文档](https://github.com/guangxiangdebizi/MySQL_MCP#readme)\n- 💬 [讨论区](https://github.com/guangxiangdebizi/MySQL_MCP/discussions)\n\n---\n\n## 📄 License\n\nApache 2.0 License - 详见 [LICENSE](./LICENSE) 文件\n\n---\n\n**⭐ 如果这个项目对你有帮助，请给个 Star 支持一下！**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fguangxiangdebizi%2FMySQL_MCP","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fguangxiangdebizi%2FMySQL_MCP","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fguangxiangdebizi%2FMySQL_MCP/lists"}