Skip to main content
Glama
isdaniel

PostgreSQL-Performance-Tuner-Mcp

find_unused_indexes

Read-onlyIdempotent

Identify unused, duplicate, and overlapping indexes in PostgreSQL to reduce storage space and improve database performance by removing unnecessary indexes.

Instructions

Find indexes that are not being used or are duplicates.

Note: This tool analyzes only user/client indexes and excludes system catalog indexes (pg_catalog, information_schema, pg_toast). It focuses on your application's custom tables only.

Identifies:

  • Indexes with zero or very few scans since last stats reset

  • Duplicate indexes (same columns in same order)

  • Overlapping indexes (one index is a prefix of another)

Removing unused indexes can:

  • Reduce storage space

  • Speed up INSERT/UPDATE/DELETE operations

  • Reduce vacuum and maintenance overhead

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
schema_nameNoSchema to analyze (default: public)public
min_size_mbNoMinimum index size in MB to include
include_duplicatesNoInclude analysis of duplicate/overlapping indexes

Implementation Reference

  • The main handler function that executes the tool logic: queries pg_stat_user_indexes for unused indexes (0 scans), detects duplicate/overlapping indexes, generates DROP recommendations, and returns JSON summary.
    async def run_tool(self, arguments: dict[str, Any]) -> Sequence[TextContent]:
        try:
            schema_name = arguments.get("schema_name", "public")
            min_size_mb = arguments.get("min_size_mb", 0)
            include_duplicates = arguments.get("include_duplicates", True)
    
            # Query only user indexes, excluding system schemas
            unused_query = """
                SELECT
                    s.schemaname,
                    s.relname as table_name,
                    s.indexrelname as index_name,
                    s.idx_scan as scans,
                    s.idx_tup_read as tuples_read,
                    s.idx_tup_fetch as tuples_fetched,
                    pg_size_pretty(pg_relation_size(s.indexrelid)) as size,
                    pg_relation_size(s.indexrelid) as size_bytes,
                    pg_get_indexdef(s.indexrelid) as definition,
                    t.n_live_tup as table_rows
                FROM pg_stat_user_indexes s
                JOIN pg_stat_user_tables t ON s.relid = t.relid
                WHERE s.schemaname = %s
                  AND s.schemaname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
                  AND pg_relation_size(s.indexrelid) >= %s * 1024 * 1024
                  AND s.indexrelname NOT LIKE '%%_pkey'
                  AND s.idx_scan = 0
                ORDER BY pg_relation_size(s.indexrelid) DESC
            """
    
            unused_results = await self.sql_driver.execute_query(
                unused_query,
                [schema_name, min_size_mb]
            )
    
            output = {
                "schema": schema_name,
                "unused_indexes": unused_results,
                "unused_count": len(unused_results),
                "potential_savings_bytes": sum(
                    r.get("size_bytes", 0) for r in unused_results
                )
            }
    
            # Find duplicate/overlapping indexes (user tables only)
            if include_duplicates:
                duplicate_query = """
                    WITH index_cols AS (
                        SELECT
                            n.nspname as schema_name,
                            t.relname as table_name,
                            i.relname as index_name,
                            pg_get_indexdef(i.oid) as definition,
                            array_agg(a.attname ORDER BY k.n) as columns,
                            pg_relation_size(i.oid) as size_bytes
                        FROM pg_index x
                        JOIN pg_class t ON t.oid = x.indrelid
                        JOIN pg_class i ON i.oid = x.indexrelid
                        JOIN pg_namespace n ON n.oid = t.relnamespace
                        CROSS JOIN unnest(x.indkey) WITH ORDINALITY AS k(attnum, n)
                        JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
                        WHERE n.nspname = %s
                          AND n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
                        GROUP BY n.nspname, t.relname, i.relname, i.oid
                    )
                    SELECT
                        a.table_name,
                        a.index_name as index1,
                        a.columns as columns1,
                        a.definition as definition1,
                        a.size_bytes as size1,
                        b.index_name as index2,
                        b.columns as columns2,
                        b.definition as definition2,
                        b.size_bytes as size2,
                        CASE
                            WHEN a.columns = b.columns THEN 'duplicate'
                            WHEN a.columns[1:array_length(b.columns, 1)] = b.columns THEN 'overlapping'
                            ELSE 'related'
                        END as relationship
                    FROM index_cols a
                    JOIN index_cols b ON a.table_name = b.table_name
                        AND a.index_name < b.index_name
                    WHERE a.columns = b.columns
                       OR a.columns[1:array_length(b.columns, 1)] = b.columns
                """
    
                duplicate_results = await self.sql_driver.execute_query(
                    duplicate_query,
                    [schema_name]
                )
    
                output["duplicate_indexes"] = duplicate_results
                output["duplicate_count"] = len(duplicate_results)
    
            # Generate recommendations
            recommendations = []
    
            for idx in unused_results[:5]:
                size = idx.get("size", "unknown")
                recommendations.append(
                    f"DROP INDEX {schema_name}.{idx['index_name']}; -- {size}, 0 scans"
                )
    
            if include_duplicates:
                for dup in duplicate_results[:5]:
                    if dup["relationship"] == "duplicate":
                        # Recommend dropping the larger one
                        if dup["size1"] > dup["size2"]:
                            recommendations.append(
                                f"DROP INDEX {schema_name}.{dup['index1']}; -- duplicate of {dup['index2']}"
                            )
                        else:
                            recommendations.append(
                                f"DROP INDEX {schema_name}.{dup['index2']}; -- duplicate of {dup['index1']}"
                            )
    
            output["recommendations"] = recommendations
    
            return self.format_json_result(output)
    
        except Exception as e:
            return self.format_error(e)
  • Defines the tool schema including input parameters: schema_name, min_size_mb, include_duplicates.
    def get_tool_definition(self) -> Tool:
        return Tool(
            name=self.name,
            description=self.description,
            inputSchema={
                "type": "object",
                "properties": {
                    "schema_name": {
                        "type": "string",
                        "description": "Schema to analyze (default: public)",
                        "default": "public"
                    },
                    "min_size_mb": {
                        "type": "number",
                        "description": "Minimum index size in MB to include",
                        "default": 0
                    },
                    "include_duplicates": {
                        "type": "boolean",
                        "description": "Include analysis of duplicate/overlapping indexes",
                        "default": True
                    }
                },
                "required": []
            },
            annotations=self.get_annotations()
        )
  • Registers all tool handlers including UnusedIndexesToolHandler(driver) via add_tool_handler in the central register_all_tools function.
    def register_all_tools() -> None:
        """
        Register all available tool handlers.
    
        This function serves as the central registry for all tools.
        New tool handlers should be added here for automatic registration.
        """
        driver = get_sql_driver()
        hypopg_service = HypoPGService(driver)
        index_advisor = IndexAdvisor(driver)
    
        # Performance analysis tools
        add_tool_handler(GetSlowQueriesToolHandler(driver))
        add_tool_handler(AnalyzeQueryToolHandler(driver))
        add_tool_handler(TableStatsToolHandler(driver))
    
        # Index tuning tools
        add_tool_handler(IndexAdvisorToolHandler(index_advisor))
        add_tool_handler(ExplainQueryToolHandler(driver, hypopg_service))
        add_tool_handler(HypoPGToolHandler(hypopg_service))
        add_tool_handler(UnusedIndexesToolHandler(driver))
    
        # Database health tools
        add_tool_handler(DatabaseHealthToolHandler(driver))
        add_tool_handler(ActiveQueriesToolHandler(driver))
        add_tool_handler(WaitEventsToolHandler(driver))
        add_tool_handler(DatabaseSettingsToolHandler(driver))
    
        # Bloat detection tools (using pgstattuple extension)
        add_tool_handler(TableBloatToolHandler(driver))
        add_tool_handler(IndexBloatToolHandler(driver))
        add_tool_handler(DatabaseBloatSummaryToolHandler(driver))
    
        logger.info(f"Registered {len(tool_handlers)} tool handlers")
  • Specific registration line for the UnusedIndexesToolHandler.
    add_tool_handler(UnusedIndexesToolHandler(driver))
Behavior4/5

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

Annotations already indicate read-only, non-destructive, and idempotent behavior, which the description does not contradict. The description adds valuable context beyond annotations: it specifies scope limitations (excludes system catalogs, focuses on custom tables), identifies what gets analyzed (zero/few scans, duplicates, overlaps), and lists benefits of acting on results (storage reduction, speed improvements). However, it lacks details on rate limits or exact output format.

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 and appropriately sized, with a clear purpose statement upfront, followed by a note on scope, a bulleted list of what it identifies, and a bulleted list of benefits. Every sentence adds value without redundancy, and it is front-loaded with the core functionality.

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 (analysis tool with 3 parameters), rich annotations (read-only, idempotent), and no output schema, the description is mostly complete: it covers purpose, scope, what it identifies, and benefits. However, it does not detail the output format or potential limitations (e.g., analysis time, database impact), leaving a minor gap for an agent to fully understand results.

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%, so the schema already documents all parameters (schema_name, min_size_mb, include_duplicates) with descriptions and defaults. The description does not add further meaning or syntax details for these parameters, such as how 'min_size_mb' affects analysis or examples of schema names. Baseline 3 is appropriate as the schema handles parameter documentation adequately.

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 ('find', 'analyzes', 'identifies') and resources ('indexes'), distinguishing it from siblings like 'analyze_index_bloat' or 'get_index_recommendations' by focusing on unused/duplicate detection rather than bloat or recommendations. It explicitly lists what it identifies: indexes with few scans, duplicates, and overlapping indexes.

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 this tool: for analyzing user/client indexes on custom tables, excluding system catalogs. It implicitly suggests usage for performance optimization (e.g., 'Removing unused indexes can...'), but does not explicitly state when not to use it or name specific alternatives among siblings, such as 'analyze_index_bloat' for different analysis types.

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