mysql
Execute SQL queries in MySQL databases directly from Claude AI. Retrieve table information and manage database interactions using natural language commands.
Instructions
Execute a query in MySQL
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | SQL query to execute |
Input Schema (JSON Schema)
{
"$schema": "http://json-schema.org/draft-07/schema#",
"additionalProperties": false,
"properties": {
"query": {
"description": "SQL query to execute",
"type": "string"
}
},
"required": [
"query"
],
"type": "object"
}
Implementation Reference
- index.js:18-38 (registration)Registers the 'mysql' tool on the MCP server with description, input schema using Zod, and an async handler function that invokes executeMysqlQuery with environment-based database config.server.tool("mysql", "Execute a query in MySQL", { query: z.string().describe("SQL query to execute"), }, async ({ query }) => { try { return executeMysqlQuery(query, { host: process.env.DB_HOST || 'localhost', user: process.env.DB_USER || 'root', password: process.env.DB_PASSWORD || '' }); } catch (error) { return { content: [ { type: "text", text: "Error executing query: " + (error.message || "Unknown error"), }, ], }; } });
- index.js:19-19 (schema)Zod schema defining the input parameter 'query' as a string for the mysql tool.query: z.string().describe("SQL query to execute"),
- index.js:20-37 (handler)The handler function for the mysql tool. It catches errors and calls the executeMysqlQuery helper with config from process.env.}, async ({ query }) => { try { return executeMysqlQuery(query, { host: process.env.DB_HOST || 'localhost', user: process.env.DB_USER || 'root', password: process.env.DB_PASSWORD || '' }); } catch (error) { return { content: [ { type: "text", text: "Error executing query: " + (error.message || "Unknown error"), }, ], }; }
- mysql.js:4-34 (handler)Core handler logic: creates MySQL connection using mysql2/promise, executes the query, formats results as JSON string, returns structured content.export const executeMysqlQuery = async (query, config) => { const connection = await mysql.createConnection(config); const [results] = await connection.execute(query); await connection.end(); let resultText; if (Array.isArray(results)) { if (results.length === 0) { resultText = "The query returned no results."; } else { resultText = `Results (${results.length} rows):\n\n${JSON.stringify(results, null, 2)}`; } } else { resultText = `Result: ${JSON.stringify(results, null, 2)}`; } return { content: [ { type: "text", text: resultText, }, ], }; };