Skip to main content
Glama
bpamiri

CockroachDB MCP Server

by bpamiri

explain_query

Generate execution plans for SQL queries to analyze performance and optimize database operations in CockroachDB clusters.

Instructions

Get the execution plan for a query.

Args:
    sql: SQL query to explain.
    analyze: If True, actually execute to get runtime stats.

Returns:
    Query execution plan.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYes
analyzeNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • MCP tool registration for 'explain_query' using @mcp.tool() decorator. This wrapper function handles errors and delegates to the core implementation in query.py.
    @mcp.tool()
    async def explain_query(sql: str, analyze: bool = False) -> dict[str, Any]:
        """Get the execution plan for a query.
    
        Args:
            sql: SQL query to explain.
            analyze: If True, actually execute to get runtime stats.
    
        Returns:
            Query execution plan.
        """
        try:
            return await query.explain_query(sql, analyze)
        except Exception as e:
            return {"status": "error", "error": str(e)}
  • Core handler function that implements the logic for explaining a SQL query: validates input, constructs EXPLAIN(ANALYZE) statement, executes it, and formats the execution plan output.
    async def explain_query(query: str, analyze: bool = False) -> dict[str, Any]:
        """Get the execution plan for a query.
    
        Args:
            query: SQL query to explain.
            analyze: If True, actually execute to get runtime stats.
    
        Returns:
            Execution plan.
        """
        # Validate the underlying query
        validation = await validate_query(query)
        if not validation["is_valid"]:
            return {
                "status": "error",
                "error": "Query validation failed",
                "issues": validation["issues"],
            }
    
        # Build EXPLAIN query
        if analyze:
            explain_query_str = f"EXPLAIN ANALYZE {query}"
        else:
            explain_query_str = f"EXPLAIN {query}"
    
        result = await connection_manager.execute_query(explain_query_str)
    
        if result.get("status") == "error":
            return result
    
        # Format the plan output
        plan_lines = []
        for row in result.get("rows", []):
            # CockroachDB returns plan in 'info' column
            if "info" in row:
                plan_lines.append(row["info"])
            else:
                # Fallback for different column names
                plan_lines.append(str(list(row.values())[0]) if row else "")
    
        return {
            "status": "success",
            "query": query,
            "analyzed": analyze,
            "plan": "\n".join(plan_lines),
        }
  • Helper function validate_query used by explain_query to check for blocked commands, read-only mode compliance, and classify query type before execution.
    async def validate_query(query: str) -> dict[str, Any]:
        """Validate a SQL query without executing it.
    
        Args:
            query: SQL query to validate.
    
        Returns:
            Validation result with is_valid and any issues.
        """
        issues: list[str] = []
    
        # Check for empty query
        if not query or not query.strip():
            return {
                "is_valid": False,
                "issues": ["Query is empty"],
                "query_type": None,
            }
    
        # Check for blocked commands
        is_blocked, blocked_cmd = _is_blocked_command(query)
        if is_blocked:
            issues.append(f"Blocked command: {blocked_cmd}")
    
        # Check read-only mode
        if settings.read_only and not _is_read_only_query(query):
            issues.append("Server is in read-only mode; only SELECT/SHOW/EXPLAIN allowed")
    
        # Determine query type
        query_upper = query.strip().upper()
        if query_upper.startswith("SELECT") or query_upper.startswith("WITH"):
            query_type = "SELECT"
        elif query_upper.startswith("INSERT"):
            query_type = "INSERT"
        elif query_upper.startswith("UPDATE"):
            query_type = "UPDATE"
        elif query_upper.startswith("DELETE"):
            query_type = "DELETE"
        elif query_upper.startswith("SHOW"):
            query_type = "SHOW"
        elif query_upper.startswith("EXPLAIN"):
            query_type = "EXPLAIN"
        else:
            query_type = "OTHER"
    
        return {
            "is_valid": len(issues) == 0,
            "issues": issues,
            "query_type": query_type,
            "is_read_only": _is_read_only_query(query),
        }
Behavior3/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions that 'analyze' executes the query for runtime stats, which adds useful context about potential side-effects. However, it does not cover other behavioral traits like permissions needed, rate limits, or what happens with invalid SQL, leaving gaps in transparency.

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 appropriately sized and front-loaded, starting with the core purpose followed by parameter and return details. Every sentence adds value, but the structure could be slightly more streamlined by integrating the 'Args' and 'Returns' sections more seamlessly into the flow.

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 moderate complexity, no annotations, and an output schema present (which covers return values), the description is mostly complete. It explains the tool's purpose, parameters, and returns adequately, though it could benefit from more behavioral context (e.g., error handling) to be fully comprehensive.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description adds significant meaning beyond the input schema, which has 0% description coverage. It explains that 'sql' is the 'SQL query to explain' and 'analyze' determines if the query is executed for runtime stats, clarifying the purpose and effect of each parameter. This compensates well for the low schema coverage, though it could detail format constraints for 'sql'.

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 tool's purpose with a specific verb ('Get') and resource ('execution plan for a query'), distinguishing it from siblings like execute_query (which runs queries) or validate_query (which validates syntax). It precisely defines what the tool does without being vague or tautological.

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

Usage Guidelines3/5

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

The description implies usage for analyzing query performance but does not explicitly state when to use this tool versus alternatives like execute_query or validate_query. It provides some context (getting execution plans) but lacks explicit guidance on exclusions or prerequisites, leaving usage somewhat inferred rather than clearly defined.

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/bpamiri/cockroachdb-mcp'

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