mysql_query
Execute SQL queries to retrieve, insert, update, or delete data in MySQL databases. Supports parameterized queries for secure database operations.
Instructions
执行 SQL 查询
Tool call template
Replace each placeholder with a value matching the input schema. Only required parameters are included; add optional parameters as needed.
{
"id": 1,
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"arguments": {
"sql": "<sql>"
},
"name": "mysql_query"
}
}Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| sql | Yes | SQL 查询语句 | |
| params | No | 参数化查询的参数(可选) |
Implementation Reference
- src/server.ts:139-154 (schema)Input schema definition for the 'mysql_query' tool, including name, description, and input parameters (sql and optional params).
{ name: 'mysql_query', description: '执行 SQL 查询', inputSchema: { type: 'object', properties: { sql: { type: 'string', description: 'SQL 查询语句' }, params: { type: 'array', description: '参数化查询的参数(可选)', items: { type: 'string' } }, }, required: ['sql'], }, }, - src/server.ts:251-252 (registration)Dispatches the 'mysql_query' tool call to the handleQuery method.
case 'mysql_query': return await this.handleQuery(args as any); - src/server.ts:395-407 (handler)Executes the mysql_query tool: validates SQL, runs query via DatabaseManager, formats and returns the result as MCP content.
private async handleQuery(args: { sql: string; params?: any[] }): Promise<any> { validateSQL(args.sql); const result = await this.dbManager.query(args.sql, args.params); return { content: [ { type: 'text', text: `${formatQueryResult(result)}\n\n查询结果:\n${JSON.stringify(result.rows, null, 2)}`, }, ], }; } - src/database.ts:51-77 (helper)Core query execution method in DatabaseManager using mysql2 pool.execute, handles both SELECT and mutations.
async query(sql: string, params?: any[]): Promise<QueryResult> { if (!this.pool) { throw new Error('数据库未连接,请先调用 connect() 方法'); } try { const [rows, fields] = await this.pool.execute(sql, params); if (Array.isArray(rows)) { return { rows: rows as any[], fields: fields as any[] }; } else { // 对于 INSERT, UPDATE, DELETE 等操作 const result = rows as mysql.ResultSetHeader; return { rows: [], fields: [], affectedRows: result.affectedRows, insertId: result.insertId }; } } catch (error) { throw new Error(`SQL 执行失败: ${error instanceof Error ? error.message : String(error)}`); } }