# mysqlmcp **Repository Path**: lwp919/mysqlmcp ## Basic Information - **Project Name**: mysqlmcp - **Description**: 本地使用springboot搭建mysql mcp - **Primary Language**: Java - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2025-09-16 - **Last Updated**: 2025-09-16 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # MySQL MCP 服务 这是一个基于Spring Boot的MySQL MCP(Model Context Protocol)服务,提供了MySQL数据库操作的标准化接口。 ## 功能特性 - 🔗 MySQL数据库连接管理 - 📊 执行SQL查询(SELECT) - ✏️ 执行SQL更新操作(INSERT、UPDATE、DELETE) - 📋 获取数据库表列表 - 🏗️ 获取表结构信息 - 🧪 数据库连接测试 - 🔍 健康检查接口 ## 快速开始 ### 1. 启动服务 ```bash # 克隆项目 git clone cd mslocalmcp # 编译项目 mvn clean compile # 启动服务 mvn spring-boot:run ``` 服务将在 `http://localhost:8099` 启动。 ### 2. 配置数据库连接 编辑 `src/main/resources/application.properties` 文件: ```properties # MySQL数据库配置 spring.datasource.url=jdbc:mysql://your-host:3306/your-database?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true spring.datasource.username=your-username spring.datasource.password=your-password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ``` ### 3. 验证服务状态 访问健康检查接口: ```bash curl http://localhost:8099/health ``` ## MCP协议接口 ### 基础URL ``` POST http://localhost:8099/mcp/call ``` ### 请求格式 ```json { "jsonrpc": "2.0", "id": "request-id", "method": "tools/call", "params": { "name": "tool-name", "arguments": { // 工具特定参数 } } } ``` ## 可用工具 ### 1. 测试数据库连接 ```json { "jsonrpc": "2.0", "id": "1", "method": "tools/call", "params": { "name": "test_connection", "arguments": {} } } ``` ### 2. 执行查询 ```json { "jsonrpc": "2.0", "id": "2", "method": "tools/call", "params": { "name": "query", "arguments": { "sql": "SELECT * FROM users WHERE age > ?", "params": [18] } } } ``` ### 3. 执行更新操作 ```json { "jsonrpc": "2.0", "id": "3", "method": "tools/call", "params": { "name": "execute", "arguments": { "sql": "INSERT INTO users (name, age) VALUES (?, ?)", "params": ["张三", 25] } } } ``` ### 4. 获取表列表 ```json { "jsonrpc": "2.0", "id": "4", "method": "tools/call", "params": { "name": "list_tables", "arguments": {} } } ``` ### 5. 获取表结构 ```json { "jsonrpc": "2.0", "id": "5", "method": "tools/call", "params": { "name": "describe_table", "arguments": { "table": "users" } } } ``` ## 在其他项目中使用 ### 1. 作为HTTP客户端调用 #### JavaScript/Node.js 示例 ```javascript const axios = require('axios'); class MySQLMCPClient { constructor(baseUrl = 'http://localhost:8099') { this.baseUrl = baseUrl; this.requestId = 0; } async callTool(name, arguments = {}) { const request = { jsonrpc: "2.0", id: (++this.requestId).toString(), method: "tools/call", params: { name, arguments } }; try { const response = await axios.post(`${this.baseUrl}/mcp/call`, request); return response.data.result; } catch (error) { throw new Error(`MCP调用失败: ${error.message}`); } } // 便捷方法 async query(sql, params = []) { return this.callTool('query', { sql, params }); } async execute(sql, params = []) { return this.callTool('execute', { sql, params }); } async listTables() { return this.callTool('list_tables'); } async describeTable(tableName) { return this.callTool('describe_table', { table: tableName }); } async testConnection() { return this.callTool('test_connection'); } } // 使用示例 async function example() { const client = new MySQLMCPClient(); try { // 测试连接 const connectionStatus = await client.testConnection(); console.log('连接状态:', connectionStatus); // 查询数据 const result = await client.query('SELECT * FROM users LIMIT 10'); console.log('查询结果:', result); // 获取表列表 const tables = await client.listTables(); console.log('数据库表:', tables); } catch (error) { console.error('操作失败:', error.message); } } ``` #### Python 示例 ```python import requests import json class MySQLMCPClient: def __init__(self, base_url="http://localhost:8099"): self.base_url = base_url self.request_id = 0 def call_tool(self, name, arguments=None): if arguments is None: arguments = {} self.request_id += 1 request = { "jsonrpc": "2.0", "id": str(self.request_id), "method": "tools/call", "params": { "name": name, "arguments": arguments } } try: response = requests.post(f"{self.base_url}/mcp/call", json=request) response.raise_for_status() return response.json()["result"] except Exception as e: raise Exception(f"MCP调用失败: {str(e)}") def query(self, sql, params=None): if params is None: params = [] return self.call_tool("query", {"sql": sql, "params": params}) def execute(self, sql, params=None): if params is None: params = [] return self.call_tool("execute", {"sql": sql, "params": params}) def list_tables(self): return self.call_tool("list_tables") def describe_table(self, table_name): return self.call_tool("describe_table", {"table": table_name}) def test_connection(self): return self.call_tool("test_connection") # 使用示例 def example(): client = MySQLMCPClient() try: # 测试连接 connection_status = client.test_connection() print("连接状态:", connection_status) # 查询数据 result = client.query("SELECT * FROM users LIMIT 10") print("查询结果:", result) # 获取表列表 tables = client.list_tables() print("数据库表:", tables) except Exception as e: print("操作失败:", str(e)) if __name__ == "__main__": example() ``` ### 2. 作为MCP服务器集成 如果您正在开发支持MCP协议的客户端,可以将此服务配置为MCP服务器: ```json { "mcpServers": { "mysql": { "command": "java", "args": ["-jar", "mslocalmcp-0.0.1-SNAPSHOT.jar"], "env": { "SPRING_PROFILES_ACTIVE": "production" } } } } ``` ## API 端点 ### 健康检查 - `GET /health` - 服务健康状态 - `GET /health/database` - 数据库状态 ### MCP接口 - `POST /mcp/call` - MCP协议调用入口 ## 错误处理 服务使用标准的JSON-RPC错误格式: ```json { "jsonrpc": "2.0", "id": "request-id", "error": { "code": -32603, "message": "内部错误: 具体错误信息" } } ``` 常见错误代码: - `-32601`: 方法不存在 - `-32602`: 无效参数 - `-32603`: 内部错误 ## 日志配置 服务使用SLF4J进行日志记录,可以在 `application.properties` 中配置日志级别: ```properties logging.level.com.mcp.mslocalmcp=DEBUG logging.level.org.springframework.web=DEBUG ``` ## 安全注意事项 1. 在生产环境中,请使用HTTPS 2. 配置适当的数据库用户权限 3. 使用环境变量管理敏感信息 4. 考虑添加认证和授权机制 ## 故障排除 ### 常见问题 1. **数据库连接失败** - 检查数据库配置 - 确认数据库服务正在运行 - 验证用户名和密码 2. **端口冲突** - 修改 `application.properties` 中的 `server.port` 3. **SQL执行错误** - 检查SQL语法 - 确认表名和字段名正确 - 验证参数类型匹配 ## 开发 ### 构建项目 ```bash mvn clean package ``` ### 运行测试 ```bash mvn test ``` ### Docker部署 ```bash # 构建镜像 docker build -t mysql-mcp-server . # 运行容器 docker run -p 8080:8080 mysql-mcp-server ``` ## 许可证 MIT License