Skip to main content
Glama

analyze_sql

Read-onlyIdempotent

Analyze SQL queries for validation, parsing, metadata extraction, security vulnerabilities, linting issues, and formatting compliance in a single operation.

Instructions

Run all 6 analysis tools concurrently and return a composite report (validate, parse, metadata, security, lint, format).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYesThe SQL string to analyze

Implementation Reference

  • Handler function 'analyzeCommand' executes the 'analyze' command by spawning a process with the GoSQLX binary, capturing its stdout as analysis output.
    async function analyzeCommand(): Promise<void> {
        const timer = new PerformanceTimer();
        timer.start();
    
        const editor = vscode.window.activeTextEditor;
        if (!editor || !isSqlLanguageId(editor.document.languageId)) {
            vscode.window.showWarningMessage(
                'No SQL file is open. Open a .sql file to analyze.',
                'Open File'
            ).then(action => {
                if (action === 'Open File') {
                    vscode.commands.executeCommand('workbench.action.files.openFile');
                }
            });
            return;
        }
    
        const text = editor.document.getText();
        const config = vscode.workspace.getConfiguration('gosqlx');
        const executablePath = await getBinaryPath();
        const analysisTimeout = config.get<number>('timeouts.analysis', 30000);
    
        // Show progress indicator
        await vscode.window.withProgress({
            location: vscode.ProgressLocation.Notification,
            title: 'Analyzing SQL...',
            cancellable: true
        }, async (progress, cancellationToken) => {
            try {
                const result = await new Promise<{ stdout: string; stderr: string }>((resolve, reject) => {
                    const child = spawn(executablePath, ['analyze'], {
                        stdio: ['pipe', 'pipe', 'pipe']
                    });
    
                    let stdout = '';
                    let stderr = '';
                    let outputSize = 0;
                    const maxSize = 5 * 1024 * 1024; // 5MB limit
    
                    // Set a timeout using configured value
                    const timeout = setTimeout(() => {
                        child.kill();
                        reject(new Error(`Analysis timed out after ${analysisTimeout / 1000} seconds. Try increasing gosqlx.timeouts.analysis in settings.`));
                    }, analysisTimeout);
    
                    // Handle cancellation
                    cancellationToken.onCancellationRequested(() => {
                        child.kill();
                        clearTimeout(timeout);
                        reject(new Error('Analysis cancelled by user'));
                    });
    
                    if (child.stdout) {
                        child.stdout.on('data', (data: Buffer) => {
                            outputSize += data.length;
                            if (outputSize < maxSize) {
                                stdout += data.toString();
                            }
                        });
                    }
    
                    if (child.stderr) {
                        child.stderr.on('data', (data: Buffer) => {
                            stderr += data.toString();
                        });
                    }
    
                    child.on('close', (code: number | null) => {
                        clearTimeout(timeout);
                        if (code === 0 || code === null) {
                            resolve({ stdout, stderr });
                        } else {
                            reject(new Error(`Process exited with code ${code}: ${stderr || 'Unknown error'}`));
                        }
                    });
    
                    child.on('error', (err: Error) => {
                        clearTimeout(timeout);
                        reject(err);
                    });
    
                    // Send SQL content via stdin
                    if (child.stdin) {
                        child.stdin.write(text);
                        child.stdin.end();
                    }
                });
    
                const duration = timer.stop();
                metrics.record('command.analyze', duration, true, { outputSize: result.stdout.length });
                telemetry.recordCommand('analyze', duration, true);
    
                if (result.stderr) {
                    outputChannel.appendLine(`Analysis stderr: ${result.stderr}`);
                }
    
                // Show analysis results in a new document
                const doc = await vscode.workspace.openTextDocument({
                    content: result.stdout || 'No analysis output',
                    language: 'markdown'
                });
                await vscode.window.showTextDocument(doc, { preview: true });
    
                outputChannel.appendLine(`Analyzed: ${editor.document.uri.fsPath} (${duration}ms)`);
    
                if (performanceStatusBarItem) {
                    updatePerformanceStatusBar(performanceStatusBarItem, metrics);
                }
            } catch (error) {
                const duration = timer.stop();
                const errorMessage = formatError(error);
                const errorCode = extractErrorCode(error);
    
                metrics.record('command.analyze', duration, false, { error: errorCode || 'unknown' });
                telemetry.recordCommand('analyze', duration, false, errorCode);
    
                const detailedMessage = getAnalysisErrorMessage(errorMessage);
                outputChannel.appendLine(detailedMessage);
    
                vscode.window.showErrorMessage(
                    `Analysis failed: ${errorMessage}`,
                    'Show Details'
                ).then(action => {
                    if (action === 'Show Details') {
                        outputChannel.show();
                    }
                });
            }
        });
    }
  • Registration of the 'gosqlx.analyze' command in the VS Code extension activate method.
    context.subscriptions.push(
        vscode.commands.registerCommand('gosqlx.validate', validateCommand),
        vscode.commands.registerCommand('gosqlx.format', formatCommand),
        vscode.commands.registerCommand('gosqlx.analyze', analyzeCommand),
        vscode.commands.registerCommand('gosqlx.restartServer', restartServerCommand),
        vscode.commands.registerCommand('gosqlx.showOutput', () => outputChannel.show()),
        vscode.commands.registerCommand('gosqlx.showMetrics', showMetricsCommand),
        vscode.commands.registerCommand('gosqlx.validateConfiguration', validateConfigurationCommand)
    );
Behavior4/5

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

The description adds valuable behavioral context beyond annotations: it explains that the tool runs 6 specific analyses concurrently and returns a composite report. While annotations already indicate it's read-only, non-destructive, and idempotent, the description provides operational details about concurrency and report composition that aren't captured in structured fields.

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 perfectly concise and front-loaded: a single sentence that efficiently communicates the tool's purpose, behavior, and differentiation from siblings. Every word earns its place with zero wasted information.

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

Completeness4/5

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

Given the tool's complexity (running 6 analyses concurrently) and the absence of an output schema, the description provides good context about what the tool does and returns. However, it doesn't detail the report format or structure, which would be helpful given no output schema exists.

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?

With 100% schema description coverage, the input schema already fully documents the single 'sql' parameter. The description doesn't add any parameter-specific information beyond what the schema provides, so it meets the baseline expectation without adding extra value.

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 action ('Run all 6 analysis tools concurrently') and the resource ('SQL string'), specifying it returns a composite report. It explicitly distinguishes from siblings by naming all 6 individual analysis tools that this tool consolidates.

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

Usage Guidelines5/5

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

The description provides explicit guidance on when to use this tool versus alternatives: use this tool to run all 6 analyses concurrently for a composite report, implying that individual sibling tools (validate_sql, parse_sql, etc.) should be used for specific analyses instead. This creates clear differentiation.

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/ajitpratap0/GoSQLX'

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