Skip to main content
Glama
devakone

MySQL Query MCP Server

by devakone

query

Execute read-only SQL queries against a specified MySQL environment to retrieve data or explore database structure.

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 main handler function runQueryTool that executes read-only SQL queries against MySQL databases. It validates the query is read-only, parses the environment, acquires a connection from the pool, executes the query with a timeout, and returns results as JSON.
    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}`);
      }
    } 
  • QueryParams Zod schema defining input validation for the query tool: sql (string min 1), environment (enum: local/development/staging/production), timeout (optional number, defaults to 30000).
    export const QueryParams = z.object({
      sql: z.string().min(1),
      environment: Environment,
      timeout: z.number().optional().default(30000),
    });
  • QueryResult interface defining the shape of the tool's output: rows, fields (name/type/length), executionTime, and rowCount.
    export interface QueryResult {
      rows: unknown[];
      fields: {
        name: string;
        type: string;
        length: number;
      }[];
      executionTime: number;
      rowCount: number;
    }
  • src/index.ts:207-213 (registration)
    Registration of the query tool in the CallToolRequestSchema handler: case statement routing the 'query' tool name to parse args with QueryToolSchema and call runQueryTool.
    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);
    }
  • Helper function isReadOnlyQuery that validates SQL is read-only (SELECT, SHOW, DESCRIBE, DESC) before execution.
    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?

No annotations are present, so the description bears full responsibility. It declares read-only behavior but does not elaborate on error handling, authentication, rate limits, or result limits. The constraint 'SELECT and SHOW only' is only in the schema, not the description.

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, front-loaded sentence with no superfluous words. It efficiently conveys the tool's purpose.

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?

The description lacks details about output format, pagination, or behavior under errors/timeouts. Given no output schema, the agent might need more context. However, for a simple query tool, the description is minimally sufficient.

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 coverage is 100%, so all parameters have descriptions. The description adds no extra parameter semantics beyond the schema, which is adequate but not additive.

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 verb 'Execute', the resource 'SQL queries', and the context 'against MySQL databases', specifying 'read-only'. This distinguishes it well from its siblings 'environments' and 'info'.

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 implicitly indicates usage for read-only SQL queries but does not explicitly state when to use or avoid it, nor does it mention alternative tools. However, the sibling tools are distinct enough that ambiguity is low.

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