Skip to main content
Glama
isdaniel

PostgreSQL-Performance-Tuner-Mcp

explain_with_indexes

Read-onlyIdempotent

Analyze PostgreSQL query performance with proposed indexes before implementation. Compare execution plans to determine if new indexes would improve performance without creating them.

Instructions

Run EXPLAIN on a query, optionally with hypothetical indexes.

This tool allows you to see how a query would perform with proposed indexes WITHOUT actually creating them. Requires HypoPG extension for hypothetical testing.

Use this to:

  • Compare execution plans with and without specific indexes

  • Test if a proposed index would be used

  • Estimate the performance impact of new indexes

Returns both the original and hypothetical execution plans for comparison.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesThe SQL query to explain
hypothetical_indexesNoList of hypothetical indexes to test
analyzeNoWhether to use EXPLAIN ANALYZE (executes the query)

Implementation Reference

  • The main handler function that executes the tool. It validates input, runs EXPLAIN on the query, optionally creates hypothetical indexes using HypoPG, compares execution plans, calculates estimated improvement, identifies used indexes, and cleans up hypothetical indexes.
    async def run_tool(self, arguments: dict[str, Any]) -> Sequence[TextContent]:
        try:
            self.validate_required_args(arguments, ["query"])
    
            query = arguments["query"]
            hypothetical_indexes = arguments.get("hypothetical_indexes", [])
            analyze = arguments.get("analyze", False)
    
            # Get the original execution plan
            explain_opts = "ANALYZE, " if analyze else ""
            original_explain = f"EXPLAIN ({explain_opts}FORMAT JSON) {query}"
            original_result = await self.sql_driver.execute_query(original_explain)
            original_plan = self._extract_plan(original_result)
    
            output = {
                "query": query,
                "original_plan": original_plan,
                "original_cost": self._extract_cost(original_plan)
            }
    
            # Test with hypothetical indexes if provided
            if hypothetical_indexes:
                hypopg_status = await self.hypopg_service.check_status()
    
                if not hypopg_status.is_installed:
                    output["error"] = (
                        "HypoPG extension is not available. "
                        "Install it with: CREATE EXTENSION hypopg;"
                    )
                    return self.format_json_result(output)
    
                # Create hypothetical indexes
                created_indexes = []
                try:
                    for idx_spec in hypothetical_indexes:
                        hypo_index = await self.hypopg_service.create_index(
                            table=idx_spec["table"],
                            columns=idx_spec["columns"],
                            using=idx_spec.get("index_type", "btree"),
                        )
                        created_indexes.append({
                            **idx_spec,
                            "index_name": hypo_index.index_name,
                            "index_oid": hypo_index.indexrelid,
                            "estimated_size": hypo_index.estimated_size
                        })
    
                    # Get the plan with hypothetical indexes
                    hypo_result = await self.sql_driver.execute_query(original_explain)
                    hypo_plan = self._extract_plan(hypo_result)
    
                    output["hypothetical_indexes"] = created_indexes
                    output["plan_with_indexes"] = hypo_plan
                    output["cost_with_indexes"] = self._extract_cost(hypo_plan)
    
                    # Calculate improvement
                    original_cost = output["original_cost"]
                    new_cost = output["cost_with_indexes"]
                    if original_cost > 0:
                        improvement = ((original_cost - new_cost) / original_cost) * 100
                        output["estimated_improvement_percent"] = round(improvement, 2)
    
                    # Check which hypothetical indexes were used
                    output["indexes_used"] = self._find_used_indexes(hypo_plan, created_indexes)
    
                finally:
                    # Clean up hypothetical indexes
                    await self.hypopg_service.reset()
    
            return self.format_json_result(output)
    
        except Exception as e:
            return self.format_error(e)
  • Defines the tool's input schema, including the required 'query' parameter, optional 'hypothetical_indexes' array specifying table, columns, index_type, unique, and 'analyze' boolean.
    def get_tool_definition(self) -> Tool:
        return Tool(
            name=self.name,
            description=self.description,
            inputSchema={
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "The SQL query to explain"
                    },
                    "hypothetical_indexes": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "table": {
                                    "type": "string",
                                    "description": "Table name"
                                },
                                "columns": {
                                    "type": "array",
                                    "items": {"type": "string"},
                                    "description": "Columns for the index"
                                },
                                "index_type": {
                                    "type": "string",
                                    "enum": ["btree", "hash", "gin", "gist", "brin"],
                                    "default": "btree"
                                },
                                "unique": {
                                    "type": "boolean",
                                    "default": False
                                }
                            },
                            "required": ["table", "columns"]
                        },
                        "description": "List of hypothetical indexes to test"
                    },
                    "analyze": {
                        "type": "boolean",
                        "description": "Whether to use EXPLAIN ANALYZE (executes the query)",
                        "default": False
                    }
                },
                "required": ["query"]
            },
            annotations=self.get_annotations()
        )
  • Registers the ExplainQueryToolHandler instance with the global tool_handlers dictionary via add_tool_handler in the register_all_tools function.
    add_tool_handler(ExplainQueryToolHandler(driver, hypopg_service))
  • Helper method to extract the execution plan JSON from the EXPLAIN query result.
    def _extract_plan(self, result: list[dict]) -> dict:
        """Extract the execution plan from EXPLAIN result."""
        if not result:
            return {}
    
        plan_data = result[0].get("QUERY PLAN", result[0])
        if isinstance(plan_data, str):
            plan_data = json.loads(plan_data)
    
        if isinstance(plan_data, list) and len(plan_data) > 0:
            return plan_data[0]
        return plan_data
  • Helper method to traverse the execution plan and identify which hypothetical indexes were actually used in the query plan.
    def _find_used_indexes(
        self,
        plan: dict,
        created_indexes: list[dict]
    ) -> list[dict]:
        """Find which hypothetical indexes were used in the plan."""
        used = []
        index_names = {idx["index_name"] for idx in created_indexes if "index_name" in idx}
    
        def check_node(node: dict):
            if not isinstance(node, dict):
                return
    
            node_type = node.get("Node Type", "")
            if "Index" in node_type:
                idx_name = node.get("Index Name", "")
                if any(name in idx_name for name in index_names):
                    used.append({
                        "index_name": idx_name,
                        "scan_type": node_type,
                        "startup_cost": node.get("Startup Cost"),
                        "total_cost": node.get("Total Cost")
                    })
    
            for child in node.get("Plans", []):
                check_node(child)
    
        check_node(plan.get("Plan", plan))
        return used
Behavior4/5

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

The description adds valuable behavioral context beyond what annotations provide. While annotations indicate read-only, non-destructive, and idempotent operations, the description clarifies that this tool 'requires HypoPG extension for hypothetical testing' and that it 'returns both the original and hypothetical execution plans for comparison.' This provides important implementation details and output behavior that annotations don't cover.

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 structured and concise - it starts with the core purpose, explains the unique value proposition, provides clear usage scenarios in bullet points, and ends with what the tool returns. Every sentence adds value with zero wasted words, and it's appropriately front-loaded with the most important 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?

For a tool with rich annotations (readOnlyHint, idempotentHint, destructiveHint all specified) and complete schema coverage, the description provides excellent context about the tool's unique capabilities and constraints. The only minor gap is the lack of output schema, but the description does specify what the tool returns ('both the original and hypothetical execution plans'), which partially compensates.

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 documents all parameters thoroughly. The description doesn't add significant parameter semantics beyond what's in the schema, though it does provide context about the 'hypothetical_indexes' parameter's purpose ('to test without actually creating them'). This meets the baseline expectation when schema coverage is complete.

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 specific verbs ('Run EXPLAIN on a query') and resources ('hypothetical indexes'), distinguishing it from siblings like analyze_query or get_index_recommendations. It explicitly mentions the unique capability of testing indexes without creating them, which sets it apart from other analysis tools.

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 ('to compare execution plans', 'test if a proposed index would be used', 'estimate performance impact'), and it implicitly distinguishes from alternatives by mentioning the HypoPG extension requirement. The sibling tools list shows clear alternatives like analyze_query (without hypothetical testing) and manage_hypothetical_indexes (which likely creates actual indexes).

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/isdaniel/pgtuner-mcp'

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