Skip to main content
Glama
Himanshu-Agg12

mcp-mysql-lens

execute_query

Execute read-only SQL queries (SELECT, SHOW, DESCRIBE, EXPLAIN) to retrieve data from MySQL databases for analysis and reporting.

Instructions

Execute a read-only SQL query

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSQL query (only SELECT, SHOW, DESCRIBE, and EXPLAIN statements are allowed)
databaseNoDatabase name (optional, uses default if not specified)

Implementation Reference

  • The handler logic for the 'execute_query' tool within the CallToolRequestSchema request handler. Extracts query and database parameters, validates the query is read-only, executes it using the executeQuery helper, and returns JSON-formatted 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/index.ts:107-123 (registration)
    Registration of the 'execute_query' tool in the ListToolsRequestSchema handler, including name, description, and input schema definition.
    {
      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"]
      }
  • Core helper function executeQuery that performs the actual database query execution using a MySQL connection pool, with timeout, row limiting, and database switching.
    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();
        }
      }
    }
  • Input validation schema enforcement for execute_query via validateQuery and supporting isReadOnlyQuery functions, ensuring only read-only SQL queries (SELECT, SHOW, etc.) are permitted.
    export function isReadOnlyQuery(query: string): boolean {
      // Normalize query by removing comments and extra whitespace
      const normalizedQuery = query
        .replace(/--.*$/gm, '') // Remove single-line comments
        .replace(/\/\*[\s\S]*?\*\//g, '') // Remove multi-line comments
        .replace(/\s+/g, ' ') // Normalize whitespace
        .trim()
        .toUpperCase();
      
      // Check if query starts with an allowed command
      const startsWithAllowed = ALLOWED_COMMANDS.some(cmd => 
        normalizedQuery.startsWith(cmd + ' ') || normalizedQuery === cmd
      );
      
      // Check if query contains any disallowed commands
      const containsDisallowed = DISALLOWED_COMMANDS.some(cmd => {
        const regex = new RegExp(`(^|\\s)${cmd}(\\s|$)`);
        return regex.test(normalizedQuery);
      });
      
      // Check for multiple statements (;)
      const hasMultipleStatements = normalizedQuery.includes(';') && 
        !normalizedQuery.endsWith(';');
      
      // Query is read-only if it starts with an allowed command,
      // doesn't contain any disallowed commands, and doesn't have multiple statements
      return startsWithAllowed && !containsDisallowed && !hasMultipleStatements;
    }
    
    /**
     * Validates if a SQL query is safe to execute
     * @param query SQL query to validate
     * @throws Error if the query is not safe
     */
    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');
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

B3.3/5.0
Behavior2/5

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

No annotations provided, so description carries burden. It declares read-only, which is a key behavioral trait, but does not disclose result format, performance, or error handling. The parameter schema already specifies allowed statements, so description adds little beyond that.

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?

Single sentence of 5 words with no redundancy. Front-loaded and efficient.

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 no output schema, the description does not explain the return format of the executed query. It also omits potential side effects (though read-only) and error scenarios. For a query tool, this is somewhat acceptable but could be more complete.

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%, with clear descriptions for both parameters. The tool description adds no additional parameter information beyond what the schema provides. Baseline 3.

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' and the resource 'read-only SQL query', distinguishing it from sibling tools like describe_table which describe schema. The title is null but description suffices.

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

Usage Guidelines2/5

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

No explicit guidance on when to use this tool over alternatives. It does not mention that for table metadata users should use describe_table or list_tables. The description is standalone without context.

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