query
Execute SELECT queries to read data from MySQL databases, enabling data retrieval through SQL statements with parameter support for prepared queries.
Instructions
Execute a SELECT query and return results. Use this for reading data.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| sql | Yes | SQL SELECT query to execute | |
| params | No | Query parameters for prepared statement |
Implementation Reference
- src/index.ts:150-171 (handler)Handler function that validates the SQL query is read-only, executes it against the MySQL pool, processes results into rows and count, and returns formatted content for MCP.async ({ sql, params }) => { // Validate that this is a read-only query validateReadOnlyQuery(sql); const p = await getPool(); const [rows] = await p.query<RowDataPacket[]>(sql, params || []); const output = { rows: rows as Record<string, unknown>[], rowCount: rows.length, }; return { content: [ { type: "text" as const, text: JSON.stringify(rows, null, 2), }, ], structuredContent: output, }; }
- src/index.ts:146-149 (schema)Input schema for the 'query' tool using Zod, defining 'sql' as required string and optional 'params' array.{ sql: z.string().describe("SQL SELECT query to execute"), params: z.array(z.unknown()).optional().describe("Query parameters for prepared statement"), },
- src/index.ts:143-172 (registration)Registration of the 'query' tool using McpServer's server.tool method, specifying name, description, input schema, and inline handler function.server.tool( "query", "Execute a SELECT query and return results. Use this for reading data.", { sql: z.string().describe("SQL SELECT query to execute"), params: z.array(z.unknown()).optional().describe("Query parameters for prepared statement"), }, async ({ sql, params }) => { // Validate that this is a read-only query validateReadOnlyQuery(sql); const p = await getPool(); const [rows] = await p.query<RowDataPacket[]>(sql, params || []); const output = { rows: rows as Record<string, unknown>[], rowCount: rows.length, }; return { content: [ { type: "text" as const, text: JSON.stringify(rows, null, 2), }, ], structuredContent: output, }; } );
- src/index.ts:46-73 (helper)Helper function used by the 'query' tool handler to ensure the SQL is read-only by checking against a list of modifying DDL/DML keywords.function validateReadOnlyQuery(sql: string): void { const normalizedSql = sql.trim().toUpperCase(); // List of forbidden keywords for read-only queries const forbiddenKeywords = [ "INSERT", "UPDATE", "DELETE", "DROP", "CREATE", "ALTER", "TRUNCATE", "RENAME", "REPLACE", "GRANT", "REVOKE", "LOCK", "UNLOCK", ]; for (const keyword of forbiddenKeywords) { if (normalizedSql.startsWith(keyword)) { throw new Error( `${keyword} operations are not allowed in query tool. Use the execute tool for data modifications or appropriate DDL tools for schema changes.` ); } } }