Skip to main content
Glama
devakone

MySQL Query MCP Server

by devakone

query

Execute read-only SQL queries against MySQL databases to retrieve data and explore database structures for analysis and investigation purposes.

Instructions

Execute read-only SQL queries against MySQL databases

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYesSQL query to execute (SELECT and SHOW only)
environmentYesTarget environment to run the query against
timeoutNoQuery timeout in milliseconds (default: 30000)

Implementation Reference

  • The core handler function for the 'query' tool. It validates the input parameters, checks if the SQL query is read-only, acquires a database connection from the appropriate pool, executes the query with a configurable timeout, processes the results, and returns a formatted JSON response.
    export async function runQueryTool(params: z.infer<typeof QueryToolSchema>): Promise<{ content: { type: string; text: string }[] }> {
      const { sql, environment: rawEnvironment, timeout = 30000 } = params;
      
      debug('Starting query execution with params:', { sql, environment: rawEnvironment, timeout });
      debug('Raw environment type:', typeof rawEnvironment);
      debug('Raw environment value:', rawEnvironment);
    
      // Validate query
      if (!isReadOnlyQuery(sql)) {
        debug('Query validation failed: not a read-only query');
        throw new Error("Only SELECT, SHOW, DESCRIBE, and DESC queries are allowed");
      }
      debug('Query validation passed: is read-only');
    
      // Validate environment
      debug('Validating environment:', rawEnvironment);
      debug('Environment enum:', Environment);
      debug('Environment enum values:', Object.values(Environment.enum));
      const environment = Environment.parse(rawEnvironment);
      debug('Environment validated successfully:', environment);
      debug('Validated environment type:', typeof environment);
      debug('Validated environment value:', environment);
    
      // Get connection pool
      debug('Getting connection pool for environment:', environment);
      debug('Available pools:', Array.from(pools.keys()));
      debug('Pool map type:', typeof pools);
      debug('Pool keys type:', Array.from(pools.keys()).map(k => typeof k));
      debug('Pool keys:', Array.from(pools.keys()));
      debug('Environment type:', typeof environment);
      debug('Environment value:', environment);
      debug('Pool has environment?', pools.has(environment));
      
      const pool = pools.get(environment);
      if (!pool) {
        debug('No pool found for environment:', environment);
        debug('Current pools state:', {
          size: pools.size,
          keys: Array.from(pools.keys()),
          envType: typeof environment,
          envValue: environment,
          poolsType: typeof pools,
          poolsEntries: Array.from(pools.entries()).map(([k]) => ({ key: k, type: typeof k }))
        });
        throw new Error(`No connection pool available for environment: ${environment}`);
      }
      debug('Found pool for environment:', environment);
    
      try {
        // Execute query with timeout
        const startTime = Date.now();
        debug('Getting connection from pool');
        const connection = await pool.getConnection();
        debug('Connection acquired successfully');
        
        try {
          debug('Executing query with timeout:', timeout);
          const result = await Promise.race([
            connection.query(sql),
            new Promise((_, reject) => 
              setTimeout(() => reject(new Error(`Query timeout after ${timeout}ms`)), timeout)
            ),
          ]) as [any[], any[]];
    
          const [rows, fields] = result;
          const executionTime = Date.now() - startTime;
          debug('Query executed successfully:', { 
            rowCount: rows.length, 
            executionTime,
            fieldCount: fields.length 
          });
    
          const queryResult: QueryResult = {
            rows: rows as unknown[],
            fields: fields.map(f => ({
              name: f.name,
              type: f.type,
              length: f.length,
            })),
            executionTime,
            rowCount: rows.length,
          };
    
          return {
            content: [{
              type: "text",
              text: JSON.stringify(queryResult, null, 2),
            }],
          };
        } finally {
          debug('Releasing connection back to pool');
          connection.release();
          debug('Connection released');
        }
      } catch (error) {
        const message = error instanceof Error ? error.message : "Unknown error occurred";
        debug('Error executing query:', message);
        throw new Error(`Query execution failed: ${message}`);
      }
    } 
  • Zod schema definition for the 'query' tool input parameters: SQL query string, target environment, and optional timeout. Re-exported as QueryToolSchema in query.ts and used for validation.
    export const QueryParams = z.object({
      sql: z.string().min(1),
      environment: Environment,
      timeout: z.number().optional().default(30000),
    });
    export type QueryParameters = z.infer<typeof QueryParams>;
  • src/index.ts:222-228 (registration)
    Registration of the 'query' tool in the MCP server's CallTool request handler. Validates arguments using QueryToolSchema and invokes the runQueryTool handler.
    case queryToolName: {
      debug('Validating query tool arguments...');
      const validated = QueryToolSchema.parse(args);
      debug('Validated query tool args:', validated);
      debug('Executing query tool...');
      return await runQueryTool(validated);
    }
  • src/index.ts:102-123 (registration)
    Declaration of the 'query' tool in the MCP server capabilities, specifying description and input schema for tool discovery.
    [queryToolName]: {
      description: queryToolDescription,
      inputSchema: {
        type: "object",
        properties: {
          sql: {
            type: "string",
            description: "SQL query to execute (SELECT and SHOW only)",
          },
          environment: {
            type: "string",
            enum: ["local", "development", "staging", "production"],
            description: "Target environment to run the query against",
          },
          timeout: {
            type: "number",
            description: "Query timeout in milliseconds (default: 30000)",
          },
        },
        required: ["sql", "environment"],
      },
    },
  • Helper function to validate that the SQL query is read-only by checking if it starts with SELECT, SHOW, DESCRIBE, or DESC.
    export function isReadOnlyQuery(sql: string): boolean {
      const upperSql = sql.trim().toUpperCase();
      return upperSql.startsWith("SELECT") || upperSql.startsWith("SHOW") || 
             upperSql.startsWith("DESCRIBE") || upperSql.startsWith("DESC");
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states 'read-only' which is crucial for safety, but doesn't mention other behavioral traits like authentication needs, rate limits, error handling, or what the output looks like (no output schema). It adds some value but leaves significant gaps for a database query tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with zero waste. It's front-loaded with the core purpose and appropriately sized for the tool's complexity. Every word earns its place by conveying essential information without redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (database queries), no annotations, and no output schema, the description is minimally adequate. It covers the read-only nature and target database, but lacks details on return values, error cases, or operational constraints. It meets basic needs but has clear gaps for effective agent use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description doesn't add any parameter-specific meaning beyond what's in the schema (e.g., it doesn't explain SQL syntax or environment implications). Baseline 3 is appropriate when the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Execute read-only SQL queries') and target resource ('against MySQL databases'), distinguishing it from sibling tools like 'environments' and 'info' which likely serve different purposes. It uses precise language that leaves no ambiguity about what the tool does.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context by specifying 'read-only SQL queries' and implying usage for SELECT/SHOW operations (reinforced in the schema), but it doesn't explicitly state when to use this tool versus alternatives or mention any exclusions beyond read-only. It gives enough guidance for basic usage but lacks sibling differentiation details.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/devakone/mysql-query-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server