Skip to main content
Glama

get-execution-plan

get-execution-plan

Analyze SQL query execution plans to understand how Firebird databases will process queries, helping optimize performance and identify bottlenecks.

Instructions

Gets the execution plan for a SQL query to understand how the database will execute it

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYesSQL query to analyze
paramsNoParameters for parameterized queries

Implementation Reference

  • Zod input schema for the get-execution-plan tool defining sql and optional params
    export const GetExecutionPlanArgsSchema = z.object({
        sql: z.string().min(1).describe("SQL query to analyze"),
        params: z.array(z.string().or(z.number()).or(z.boolean()).or(z.null())).optional().describe("Parameters for parameterized queries")
    });
  • Registration of the get-execution-plan tool in setupDatabaseTools, including inline handler that delegates to getExecutionPlan
    tools.set("get-execution-plan", {
        name: "get-execution-plan",
        description: "Gets the execution plan for a SQL query to understand how the database will execute it",
        inputSchema: GetExecutionPlanArgsSchema,
        handler: async (request) => {
            const { sql, params } = request;
            logger.info(`Executing get-execution-plan tool for query: ${sql.substring(0, 50)}...`);
    
            try {
                const result = await getExecutionPlan(sql, params || []);
    
                return {
                    content: [{
                        type: "text",
                        text: formatForClaude(result)
                    }]
                };
            } catch (error) {
                const errorResponse = wrapError(error);
                logger.error(`Error getting execution plan: ${errorResponse.error} [${errorResponse.errorType || 'UNKNOWN'}]`);
    
                return {
                    content: [{
                        type: "text",
                        text: stringifyCompact(errorResponse)
                    }]
                };
            }
        }
    });
  • Core getExecutionPlan function implementation that handles validation and returns detailed explanation why execution plans are not retrievable via Node.js drivers, with tool recommendations
    export const getExecutionPlan = async (
        sql: string,
        params: any[] = [],
        config = getGlobalConfig() || DEFAULT_CONFIG
    ): Promise<ExecutionPlanResult> => {
        try {
            // Validate the SQL query to prevent injection
            if (!validateSql(sql)) {
                throw new FirebirdError(
                    `Invalid SQL query: ${sql}`,
                    'VALIDATION_ERROR'
                );
            }
    
            logger.info(`Getting execution plan for query: ${sql.substring(0, 100)}${sql.length > 100 ? '...' : ''}`);
    
            // Only SELECT queries are supported for execution plan analysis
            if (!sql.trim().toUpperCase().startsWith('SELECT')) {
                throw new FirebirdError(
                    `Only SELECT queries are supported for execution plan analysis`,
                    'UNSUPPORTED_OPERATION'
                );
            }
    
            // Check if we're using the native driver by checking DriverFactory
            const { DriverFactory } = await import('./driver-factory.js');
            const driverInfo = await DriverFactory.getDriverInfo();
    
            logger.debug('Driver info for execution plan', {
                driverType: driverInfo.current,
                nativeAvailable: driverInfo.nativeAvailable
            });
    
            // Note: node-firebird-driver-native and node-firebird do not expose a direct method to get execution plans
            // The Firebird API has isc_dsql_sql_info with isc_info_sql_get_plan (constant value: 22), but this is not
            // exposed in the high-level driver interfaces. The low-level node-firebird-native-api would be needed,
            // but it's complex to use directly and would require significant refactoring.
            //
            // Research findings:
            // - FDB (Python driver) uses: isc_dsql_sql_info(statement_handle, [isc_info_sql_get_plan])
            // - node-firebird-driver-native Statement object does not have getPlan() or getInfo() methods
            // - node-firebird (pure JS) does not support SET PLANONLY or SET PLAN commands (isql-specific)
            //
            // Recommendation: Use Firebird tools for execution plan analysis:
            // - isql: SET PLANONLY ON; <query>; SET PLANONLY OFF;
            // - FlameRobin: GUI tool with built-in plan visualization
            // - IBExpert: Commercial tool with advanced plan analysis
    
            logger.info('Execution plan retrieval is not available through Node.js Firebird drivers');
            logger.info('The drivers do not expose the isc_dsql_sql_info API needed to get execution plans');
            logger.info('Recommendation: Use Firebird tools like isql, FlameRobin, or IBExpert for execution plans');
    
            // Return informative message
            return {
                query: sql,
                plan: "Execution plan not available",
                planDetails: [],
                success: true,
                analysis: "Node.js Firebird drivers do not expose the execution plan API.\n\n" +
                         "The Firebird API provides isc_dsql_sql_info with isc_info_sql_get_plan (constant: 22) " +
                         "to retrieve execution plans, but neither node-firebird-driver-native nor node-firebird " +
                         "expose this functionality in their high-level interfaces.\n\n" +
                         "To view execution plans, please use one of these Firebird tools:\n\n" +
                         "1. isql (Firebird command-line tool):\n" +
                         "   SET PLANONLY ON;\n" +
                         "   <your query>;\n" +
                         "   SET PLANONLY OFF;\n\n" +
                         "2. FlameRobin (Free GUI tool):\n" +
                         "   - Open SQL Editor\n" +
                         "   - Enter your query\n" +
                         "   - Click 'Show Plan' button\n\n" +
                         "3. IBExpert (Commercial GUI tool):\n" +
                         "   - SQL Editor with built-in plan visualization\n" +
                         "   - Advanced plan analysis features\n\n" +
                         "Alternatively, you can use the 'analyze-query-performance' tool to measure " +
                         "query execution time and identify performance issues."
            };
    
        } catch (error: any) {
            const errorMessage = `Error getting execution plan: ${error.message || error}`;
            logger.error(errorMessage);
    
            return {
                query: sql,
                plan: "",
                planDetails: [],
                success: false,
                error: errorMessage,
                analysis: "Failed to get execution plan."
            };
        }
    };
  • TypeScript interface defining the structure of execution plan results
    export interface ExecutionPlanResult {
        query: string;
        plan: string;
        planDetails: any[];
        success: boolean;
        error?: string;
        analysis: string;
    }
  • Helper function to analyze execution plans (currently unused as plans can't be retrieved)
    function analyzePlan(plan: string): string {
        const analysis: string[] = [];
        const upperPlan = plan.toUpperCase();
    
        // Check for NATURAL scans (table scans without index)
        if (upperPlan.includes('NATURAL')) {
            analysis.push('⚠️ NATURAL scan detected - table is being scanned without using an index. Consider adding an index for better performance.');
        }
    
        // Check for INDEX usage
        const indexMatches = plan.match(/INDEX\s+\(([^)]+)\)/gi);
        if (indexMatches && indexMatches.length > 0) {
            analysis.push(`✅ Using ${indexMatches.length} index(es): ${indexMatches.join(', ')}`);
        }
    
        // Check for JOIN operations
        if (upperPlan.includes('JOIN')) {
            analysis.push('🔗 Query contains JOIN operations');
        }
    
        // Check for SORT operations
        if (upperPlan.includes('SORT')) {
            analysis.push('📊 SORT operation detected - may impact performance on large datasets');
        }
    
        // Check for FILTER operations
        if (upperPlan.includes('FILTER')) {
            analysis.push('🔍 FILTER operation detected - rows are being filtered after retrieval');
        }
    
        if (analysis.length === 0) {
            return 'Plan retrieved successfully. The query appears to be optimized.';
        }
    
        return analysis.join('\n');
    }
Behavior2/5

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

With no annotations provided, the description carries full burden but offers minimal behavioral details. It states the tool 'gets' and 'analyzes' a plan, implying a read-only operation, but doesn't disclose if it requires specific permissions, has rate limits, affects database performance, or what the output format might be, which is inadequate for a tool with potential side effects.

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

Conciseness4/5

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

The description is a single, efficient sentence that front-loads the core purpose. It avoids redundancy and wastes no words, though it could be slightly more structured by including usage context, but it's appropriately sized for its content.

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

Completeness2/5

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

Given the tool's complexity (analyzing SQL execution plans), lack of annotations, and no output schema, the description is incomplete. It doesn't explain return values, potential errors, or behavioral traits like performance impact, which are crucial for an AI agent to use it correctly in a database context.

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 fully documents the 'sql' and 'params' parameters. The description adds no additional meaning beyond implying analysis occurs, but doesn't clarify parameter interactions or usage nuances. This meets the baseline for high schema coverage without extra value.

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

Purpose4/5

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

The description clearly states the tool's purpose with a specific verb ('Gets') and resource ('execution plan for a SQL query'), explaining it helps 'understand how the database will execute it.' However, it doesn't explicitly differentiate from siblings like analyze-query-performance or execute-query, which might also involve query analysis, keeping it from a perfect score.

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?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention siblings like analyze-query-performance (for performance insights) or execute-query (for running queries), nor does it specify prerequisites or exclusions, leaving usage context unclear.

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/PuroDelphi/mcpFirebird'

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