execute_query
Execute read-only SQL queries to retrieve data from MySQL databases using SELECT, SHOW, DESCRIBE, and EXPLAIN statements for database analysis and information retrieval.
Instructions
Execute a read-only SQL query
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| database | No | Database name (optional, uses default if not specified) | |
| query | Yes | SQL query (only SELECT, SHOW, DESCRIBE, and EXPLAIN statements are allowed) |
Implementation Reference
- src/index.ts:196-222 (handler)MCP tool handler for 'execute_query': validates input, checks query safety, executes the query via helper function, and returns JSON results.case "execute_query": { console.error('[Tool] Executing execute_query'); const query = request.params.arguments?.query as string; const database = request.params.arguments?.database as string | undefined; if (!query) { throw new McpError(ErrorCode.InvalidParams, "Query is required"); } // Validate that the query is read-only validateQuery(query); const { rows } = await executeQuery( pool, query, [], database ); return { content: [{ type: "text", text: JSON.stringify(rows, null, 2) }] }; }
- src/connection.ts:63-109 (helper)Core helper function that performs the actual SQL query execution using MySQL pool, with database switching, timeout protection, row limiting, and connection management.export async function executeQuery( pool: mysql.Pool, sql: string, params: any[] = [], database?: string ): Promise<{ rows: any; fields: mysql.FieldPacket[] }> { console.error(`[Query] Executing: ${sql}`); let connection: mysql.PoolConnection | null = null; try { // Get connection from pool connection = await pool.getConnection(); // Use specific database if provided if (database) { console.error(`[Query] Using database: ${database}`); await connection.query(`USE \`${database}\``); } // Execute query with timeout const [rows, fields] = await Promise.race([ connection.query(sql, params), new Promise<never>((_, reject) => { setTimeout(() => reject(new Error('Query timeout')), DEFAULT_TIMEOUT); }), ]); // Apply row limit if result is an array const limitedRows = Array.isArray(rows) && rows.length > DEFAULT_ROW_LIMIT ? rows.slice(0, DEFAULT_ROW_LIMIT) : rows; // Log result summary console.error(`[Query] Success: ${Array.isArray(rows) ? rows.length : 1} rows returned`); return { rows: limitedRows, fields }; } catch (error) { console.error('[Error] Query execution failed:', error); throw error; } finally { // Release connection back to pool if (connection) { connection.release(); } } }
- src/index.ts:108-124 (schema)Input schema definition for the execute_query tool, specifying required 'query' parameter and optional 'database'.name: "execute_query", description: "Execute a read-only SQL query", inputSchema: { type: "object", properties: { query: { type: "string", description: "SQL query (only SELECT, SHOW, DESCRIBE, and EXPLAIN statements are allowed)" }, database: { type: "string", description: "Database name (optional, uses default if not specified)" } }, required: ["query"] } }
- src/validators.ts:79-92 (helper)Helper function to validate that the SQL query is read-only, used in the tool handler.export function validateQuery(query: string): void { console.error('[Validator] Validating query:', query); if (!query || typeof query !== 'string') { throw new Error('Query must be a non-empty string'); } if (!isReadOnlyQuery(query)) { console.error('[Validator] Query rejected: not read-only'); throw new Error('Only read-only queries are allowed (SELECT, SHOW, DESCRIBE, EXPLAIN)'); } console.error('[Validator] Query validated as read-only'); }