run_sql_query
Execute SQL SELECT queries to retrieve data from a MySQL database. This tool performs read-only operations, returning query results in JSON format for analysis and reporting.
Instructions
执行只读 SQL 查询(仅限 SELECT 语句)
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | 要执行的 SQL SELECT 查询语句 |
Implementation Reference
- src/index.ts:218-264 (handler)Main handler function that validates the SQL query arguments, ensures it's a SELECT query, executes it using the MySQL connection pool, and returns the results as JSON or an error message.private async handleReadQuery(request: any, transactionId: string) { if (!isValidSqlQueryArgs(request.params.arguments)) { throw new McpError( ErrorCode.InvalidParams, 'SQL 查询参数无效。' ); } const query = request.params.arguments.query; if (!isReadOnlyQuery(query)) { throw new McpError( ErrorCode.InvalidParams, 'run_sql_query 工具仅允许 SELECT 查询。' ); } console.error(`[${transactionId}] 执行 SELECT 查询: ${query}`); try { const [rows] = await this.pool.query(query); console.error(`[${transactionId}] 查询执行成功`); return { content: [ { type: 'text', text: JSON.stringify(rows, null, 2), }, ], }; } catch (error) { console.error(`[${transactionId}] 查询出错:`, error); if (error instanceof Error) { return { content: [ { type: 'text', text: `MySQL 错误: ${error.message}`, }, ], isError: true, }; } throw error; } }
- src/index.ts:102-115 (schema)Tool schema definition including input schema for 'query' parameter, provided in the ListTools response.{ name: 'run_sql_query', description: '执行只读 SQL 查询(仅限 SELECT 语句)', inputSchema: { type: 'object', properties: { query: { type: 'string', description: '要执行的 SQL SELECT 查询语句', }, }, required: ['query'], }, },
- src/index.ts:190-214 (registration)Tool call request handler that dispatches to handleReadQuery based on tool name 'run_sql_query'.this.server.setRequestHandler(CallToolRequestSchema, async (request) => { const transactionId = generateTransactionId(); console.error(`[${transactionId}] 正在处理请求: ${request.params.name}`); // 根据工具类型分发处理 switch (request.params.name) { case 'run_sql_query': return this.handleReadQuery(request, transactionId); case 'create_table': return this.handleCreateTable(request, transactionId); case 'insert_data': return this.handleInsertData(request, transactionId); case 'update_data': return this.handleUpdateData(request, transactionId); case 'delete_data': return this.handleDeleteData(request, transactionId); case 'execute_sql': return this.handleExecuteSql(request, transactionId); default: throw new McpError( ErrorCode.MethodNotFound, `未知工具: ${request.params.name}` ); } });
- src/index.ts:21-33 (helper)Helper functions and interface for validating SQL query arguments and checking if it's a read-only SELECT query.interface SqlQueryArgs { query: string; } // 校验 SQL 查询参数是否合法 const isValidSqlQueryArgs = (args: any): args is SqlQueryArgs => typeof args === 'object' && args !== null && typeof args.query === 'string'; // 判断是否为只读查询(SELECT) const isReadOnlyQuery = (query: string): boolean => query.trim().toLowerCase().startsWith('select');