Skip to main content
Glama

execute-batch-queries

execute-batch-queries

Execute multiple SQL queries in parallel to improve database performance when working with Firebird databases.

Instructions

Executes multiple SQL queries in parallel for improved performance.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queriesYesArray of query objects, each containing SQL and optional parameters
maxConcurrentNoMaximum number of concurrent queries (default: 5)

Implementation Reference

  • Zod input schema defining the parameters for the execute-batch-queries tool: array of queries with SQL and optional params, and maxConcurrent.
    export const ExecuteBatchQueriesArgsSchema = z.object({
        queries: z.array(
            z.object({
                sql: z.string().min(1).describe("SQL query to execute"),
                params: z.array(z.string().or(z.number()).or(z.boolean()).or(z.null())).optional().describe("Parameters for parameterized queries")
            })
        ).min(1).max(20).describe("Array of query objects, each containing SQL and optional parameters"),
        maxConcurrent: z.number().int().min(1).max(10).optional().default(5).describe("Maximum number of concurrent queries (default: 5)")
    });
  • Tool registration in setupDatabaseTools function, including name, description, schema, and handler.
    // Add execute-batch-queries tool
    tools.set("execute-batch-queries", {
        name: "execute-batch-queries",
        description: "Executes multiple SQL queries in parallel for improved performance.",
        inputSchema: ExecuteBatchQueriesArgsSchema,
        handler: async (args: z.infer<typeof ExecuteBatchQueriesArgsSchema>) => {
            const { queries, maxConcurrent = 5 } = args;
            logger.info(`Executing batch of ${queries.length} queries with max concurrency ${maxConcurrent}`);
    
            try {
                // Validate each query for security
                queries.forEach((query, index) => {
                    if (!validateSql(query.sql)) {
                        throw new FirebirdError(
                            `Potentially unsafe SQL query at index ${index}: ${query.sql.substring(0, 100)}${query.sql.length > 100 ? '...' : ''}`,
                            'SECURITY_ERROR'
                        );
                    }
                });
    
                const results = await executeBatchQueries(queries, undefined, maxConcurrent);
    
                logger.info(`Batch execution completed: ${results.filter(r => r.success).length} succeeded, ${results.filter(r => !r.success).length} failed`);
    
                return {
                    content: [{
                        type: "text",
                        text: formatForClaude(results)
                    }]
                };
            } catch (error) {
                const errorResponse = wrapError(error);
                logger.error(`Error executing batch queries: ${errorResponse.error} [${errorResponse.errorType || 'UNKNOWN'}]`);
    
                return {
                    content: [{
                        type: "text",
                        text: formatForClaude(errorResponse)
                    }]
                };
            }
        }
    });
  • The MCP tool handler function: extracts args, validates SQL, calls core executeBatchQueries, formats and returns results or error.
    handler: async (args: z.infer<typeof ExecuteBatchQueriesArgsSchema>) => {
        const { queries, maxConcurrent = 5 } = args;
        logger.info(`Executing batch of ${queries.length} queries with max concurrency ${maxConcurrent}`);
    
        try {
            // Validate each query for security
            queries.forEach((query, index) => {
                if (!validateSql(query.sql)) {
                    throw new FirebirdError(
                        `Potentially unsafe SQL query at index ${index}: ${query.sql.substring(0, 100)}${query.sql.length > 100 ? '...' : ''}`,
                        'SECURITY_ERROR'
                    );
                }
            });
    
            const results = await executeBatchQueries(queries, undefined, maxConcurrent);
    
            logger.info(`Batch execution completed: ${results.filter(r => r.success).length} succeeded, ${results.filter(r => !r.success).length} failed`);
    
            return {
                content: [{
                    type: "text",
                    text: formatForClaude(results)
                }]
            };
        } catch (error) {
            const errorResponse = wrapError(error);
            logger.error(`Error executing batch queries: ${errorResponse.error} [${errorResponse.errorType || 'UNKNOWN'}]`);
    
            return {
                content: [{
                    type: "text",
                    text: formatForClaude(errorResponse)
                }]
            };
        }
    }
  • Core helper function implementing batch query execution: validates inputs, processes queries in concurrent batches using executeQuery, collects success/error results.
    export const executeBatchQueries = async (
        queries: Array<{sql: string, params?: any[]}>,
        config = DEFAULT_CONFIG,
        maxConcurrent: number = 5
    ): Promise<Array<{success: boolean, data?: any[], error?: string, errorType?: string}>> => {
        // Try to load config from global variable first
        const globalConfig = getGlobalConfig();
        if (globalConfig && globalConfig.database) {
            logger.info(`Using global configuration for executeBatchQueries: ${globalConfig.database}`);
            config = globalConfig;
        }
    
        // Validate input
        if (!Array.isArray(queries) || queries.length === 0) {
            throw new FirebirdError(
                'Invalid queries array: must be a non-empty array of query objects',
                'VALIDATION_ERROR'
            );
        }
    
        // Limit the number of queries to prevent abuse
        const MAX_QUERIES = 20;
        if (queries.length > MAX_QUERIES) {
            throw new FirebirdError(
                `Too many queries: maximum allowed is ${MAX_QUERIES}`,
                'VALIDATION_ERROR'
            );
        }
    
        // Validate each query
        queries.forEach((query, index) => {
            if (!query.sql || typeof query.sql !== 'string') {
                throw new FirebirdError(
                    `Invalid SQL in query at index ${index}`,
                    'VALIDATION_ERROR'
                );
            }
    
            // Validate SQL for security
            if (!validateSql(query.sql)) {
                throw new FirebirdError(
                    `Potentially unsafe SQL query at index ${index}: ${query.sql.substring(0, 100)}${query.sql.length > 100 ? '...' : ''}`,
                    'SECURITY_ERROR'
                );
            }
    
            // Ensure params is an array if provided
            if (query.params !== undefined && !Array.isArray(query.params)) {
                throw new FirebirdError(
                    `Invalid params in query at index ${index}: must be an array`,
                    'VALIDATION_ERROR'
                );
            }
        });
    
        logger.info(`Executing batch of ${queries.length} queries`);
    
        // Execute queries in batches to limit concurrency
        const results: Array<{success: boolean, data?: any[], error?: string, errorType?: string}> = [];
    
        // Process queries in batches of maxConcurrent
        for (let i = 0; i < queries.length; i += maxConcurrent) {
            const batch = queries.slice(i, i + maxConcurrent);
    
            // Execute batch in parallel
            const batchPromises = batch.map(async (query, batchIndex) => {
                const queryIndex = i + batchIndex;
                try {
                    logger.debug(`Executing query ${queryIndex + 1}/${queries.length}: ${query.sql.substring(0, 100)}${query.sql.length > 100 ? '...' : ''}`);
                    const data = await executeQuery(query.sql, query.params || [], config);
                    return { success: true, data };
                } catch (error: any) {
                    logger.error(`Error executing query ${queryIndex + 1}: ${error.message || error}`);
    
                    // Format error response
                    const errorType = error instanceof FirebirdError ? error.type : 'QUERY_EXECUTION_ERROR';
                    const errorMessage = error instanceof Error ? error.message : String(error);
    
                    return {
                        success: false,
                        error: errorMessage,
                        errorType
                    };
                }
            });
    
            // Wait for all queries in this batch to complete
            const batchResults = await Promise.all(batchPromises);
            results.push(...batchResults);
        }
    
        logger.info(`Batch execution completed: ${results.filter(r => r.success).length} succeeded, ${results.filter(r => !r.success).length} failed`);
        return results;
    };
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'parallel execution' and 'improved performance,' but fails to address critical aspects: whether queries run in a transaction, error handling for partial failures, resource limits beyond maxConcurrent, side effects (e.g., data modification), or output format. For a batch execution tool with no annotation coverage, this leaves significant gaps in understanding its behavior.

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 that front-loads the core functionality: 'Executes multiple SQL queries in parallel for improved performance.' It avoids redundancy and wastes no words, making it easy for an agent to parse quickly. Every part of the sentence contributes value, earning a high score for conciseness.

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 complexity of batch query execution and the absence of both annotations and an output schema, the description is incomplete. It lacks details on behavioral traits (e.g., transactionality, error handling), usage guidelines compared to siblings, and output expectations. For a tool that could involve data mutation or performance impacts, this minimal description fails to provide sufficient context for safe and effective 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%, with clear documentation for both parameters ('queries' and 'maxConcurrent'). The description adds no additional parameter semantics beyond what the schema provides—it doesn't explain query constraints, performance implications of maxConcurrent, or parameter interactions. Given the high schema coverage, a baseline score of 3 is appropriate, as the description doesn't compensate but doesn't need to heavily.

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: 'Executes multiple SQL queries in parallel for improved performance.' It specifies the verb ('executes'), resource ('multiple SQL queries'), and key benefit ('parallel for improved performance'). However, it doesn't explicitly differentiate from sibling tools like 'execute-query' (which likely handles single queries), leaving room for improvement in sibling differentiation.

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 sibling tools like 'execute-query' for single queries or other batch-related tools, nor does it specify prerequisites, performance trade-offs, or error-handling scenarios. The agent must infer usage from the description alone, which is insufficient for optimal tool selection.

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