execute_sql
Execute non-SELECT SQL commands (e.g., ALTER TABLE, DROP) directly on a MySQL database using a Model Context Protocol server, enabling efficient database management and modifications.
Instructions
执行任意非 SELECT 的 SQL 语句(如 ALTER TABLE、DROP 等)
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | 要执行的 SQL 语句 |
Input Schema (JSON Schema)
{
"properties": {
"query": {
"description": "要执行的 SQL 语句",
"type": "string"
}
},
"required": [
"query"
],
"type": "object"
}
Implementation Reference
- src/index.ts:486-536 (handler)The primary handler function for the 'execute_sql' tool. It validates the input arguments, ensures the query is not a SELECT statement, executes the SQL using the MySQL connection pool, and returns the result or error in MCP format.private async handleExecuteSql(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, 'execute_sql 工具不允许 SELECT 查询。' ); } console.error(`[${transactionId}] 执行通用 SQL: ${query}`); try { const [result] = await this.pool.query(query); console.error(`[${transactionId}] SQL 执行成功`); return { content: [ { type: 'text', text: JSON.stringify({ success: true, message: 'SQL 执行成功', result }, null, 2), }, ], }; } catch (error) { console.error(`[${transactionId}] SQL 执行出错:`, error); if (error instanceof Error) { return { content: [ { type: 'text', text: `MySQL 错误: ${error.message}`, }, ], isError: true, }; } throw error; } }
- src/index.ts:172-185 (schema)The tool definition in the listTools response, including name, description, and inputSchema for 'execute_sql' which requires a 'query' string.{ name: 'execute_sql', description: '执行任意非 SELECT 的 SQL 语句(如 ALTER TABLE、DROP 等)', inputSchema: { type: 'object', properties: { query: { type: 'string', description: '要执行的 SQL 语句', }, }, required: ['query'], }, },
- src/index.ts:206-207 (registration)Registration of the 'execute_sql' tool handler in the CallToolRequestSchema switch statement, dispatching to handleExecuteSql.case 'execute_sql': return this.handleExecuteSql(request, transactionId);
- src/index.ts:26-29 (helper)Helper function to validate SQL query arguments, ensuring it has a 'query' string property. Used in the handler.const isValidSqlQueryArgs = (args: any): args is SqlQueryArgs => typeof args === 'object' && args !== null && typeof args.query === 'string';
- src/index.ts:32-33 (helper)Helper function to check if a query is a read-only SELECT statement. Used in the handler to forbid SELECTs.const isReadOnlyQuery = (query: string): boolean => query.trim().toLowerCase().startsWith('select');