Skip to main content
Glama

explain_query

Analyze SQL query performance by generating execution plans with cost estimates to optimize PostgreSQL database operations.

Instructions

Get the execution plan for a SQL query (EXPLAIN).

Args:
    sql: SQL query to explain
    analyze: If true, actually runs the query to get real execution stats
             (EXPLAIN ANALYZE). Use with caution on slow queries.
    
Returns:
    Execution plan in JSON format with cost estimates

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYes
analyzeNo

Implementation Reference

  • MCP tool handler for 'explain_query', registered via @mcp.tool() decorator. Delegates to PostgresClient's explain_query method.
    @mcp.tool()
    @handle_db_error
    def explain_query(sql: str, analyze: bool = False) -> dict:
        """Get the execution plan for a SQL query (EXPLAIN).
        
        Args:
            sql: SQL query to explain
            analyze: If true, actually runs the query to get real execution stats
                     (EXPLAIN ANALYZE). Use with caution on slow queries.
            
        Returns:
            Execution plan in JSON format with cost estimates
        """
        client = get_client()
        return client.explain_query(sql, analyze=analyze)
  • Core implementation of the explain_query functionality in PostgresClient class. Constructs and executes an EXPLAIN (FORMAT JSON) query, optionally with ANALYZE.
    def explain_query(self, query: str, analyze: bool = False) -> dict[str, Any]:
        """Get EXPLAIN plan for a query.
        
        Args:
            query: SQL query to explain
            analyze: Whether to actually run the query (EXPLAIN ANALYZE)
            
        Returns:
            Dict with execution plan
        """
        # Only allow EXPLAIN on SELECT queries
        validated_query = validate_query(query, allow_write=False)
        
        explain_cmd = "EXPLAIN (FORMAT JSON"
        if analyze:
            explain_cmd += ", ANALYZE, BUFFERS"
        explain_cmd += f") {validated_query}"
        
        with self.get_cursor() as cursor:
            cursor.execute(explain_cmd)
            result = cursor.fetchone()
            
            if result:
                plan = list(result.values())[0]
                return {
                    "success": True,
                    "plan": plan,
                }
            return {"success": False, "error": "No plan returned"}
Behavior4/5

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

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: the tool performs a read operation (EXPLAIN), warns about performance implications of the 'analyze' parameter, and specifies the output format ('JSON format with cost estimates'). However, it lacks details on permissions, rate limits, or error handling.

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 well-structured with clear sections (Args, Returns), uses bullet-like formatting for parameters, and every sentence adds value. It is front-loaded with the core purpose and efficiently conveys necessary details without redundancy.

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 (2 parameters, no output schema, no annotations), the description is mostly complete. It covers purpose, parameters, and output format, but lacks information on prerequisites (e.g., database connection), error cases, or example usage, which would enhance completeness.

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

Parameters5/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% coverage. It explains that 'sql' is the 'SQL query to explain' and clarifies that 'analyze' runs the query for real stats with a caution note. This fully compensates for the schema's lack of descriptions.

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 specific action ('Get the execution plan for a SQL query') and resource ('SQL query'), using the technical term 'EXPLAIN' to distinguish it from siblings like 'execute' or 'query'. It precisely defines the tool's function without ambiguity.

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

Usage Guidelines4/5

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

The description provides clear context on when to use the 'analyze' parameter ('Use with caution on slow queries'), but does not explicitly differentiate when to use this tool versus alternatives like 'execute' or 'query'. It implies usage for query optimization without naming specific sibling tools.

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/JaviMaligno/postgres-mcp'

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