Skip to main content
Glama
dpflucas

MySQL Database Access

execute_query

Execute read-only SQL queries on MySQL databases. Run SELECT, SHOW, DESCRIBE, and EXPLAIN statements to retrieve data without modification.

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 main tool handler case for 'execute_query' that extracts arguments (query, database), validates the query is read-only, executes it via the helper, and returns 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)
        }]
      };
    }
  • The core database query execution function that acquires a connection from the pool, switches database if specified, executes the SQL with a timeout, applies a row limit, and releases the connection.
    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();
        }
      }
    }
  • src/index.ts:107-124 (registration)
    Tool registration for 'execute_query' within the ListToolsRequestSchema handler, defining name, description, and input schema (query required, database optional).
    {
      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"]
      }
    }
  • Validation helper that ensures queries are read-only (SELECT, SHOW, DESCRIBE, EXPLAIN only) and rejects write operations. Called by the execute_query handler.
    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');
    }
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.

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/dpflucas/mysql-mcp-server'

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