Skip to main content
Glama

get_top_queries

Identify slow or resource-intensive PostgreSQL queries using pg_stat_statements data to optimize database performance and troubleshoot bottlenecks.

Instructions

Reports the slowest or most resource-intensive queries using data from the 'pg_stat_statements' extension.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sort_byNoRanking criteria: 'total_time' for total execution time or 'mean_time' for mean execution time per call, or 'resources' for resource-intensive queriesresources
limitNoNumber of queries to return when ranking based on mean_time or total_time

Implementation Reference

  • Tool handler for get_top_queries which parses inputs and dispatches to the TopQueriesCalc class.
    @mcp.tool(
        name="get_top_queries",
        description=f"Reports the slowest or most resource-intensive queries using data from the '{PG_STAT_STATEMENTS}' extension.",
    )
    async def get_top_queries(
        sort_by: str = Field(
            description="Ranking criteria: 'total_time' for total execution time or 'mean_time' for mean execution time per call, or 'resources' "
            "for resource-intensive queries",
            default="resources",
        ),
        limit: int = Field(description="Number of queries to return when ranking based on mean_time or total_time", default=10),
    ) -> ResponseType:
        try:
            sql_driver = await get_sql_driver()
            top_queries_tool = TopQueriesCalc(sql_driver=sql_driver)
    
            if sort_by == "resources":
                result = await top_queries_tool.get_top_resource_queries()
                return format_text_response(result)
            elif sort_by == "mean_time" or sort_by == "total_time":
                # Map the sort_by values to what get_top_queries_by_time expects
                result = await top_queries_tool.get_top_queries_by_time(limit=limit, sort_by="mean" if sort_by == "mean_time" else "total")
            else:
                return format_error_response("Invalid sort criteria. Please use 'resources' or 'mean_time' or 'total_time'.")
            return format_text_response(result)
  • The core logic implementation for retrieving top queries based on time (mean or total).
    async def get_top_queries_by_time(self, limit: int = 10, sort_by: Literal["total", "mean"] = "mean") -> str:
        """Reports the slowest SQL queries based on execution time.
    
        Args:
            limit: Number of slow queries to return
            sort_by: Sort criteria - 'total' for total execution time or
                'mean' for mean execution time per call (default)
    
        Returns:
            A string with the top queries or installation instructions
        """
        try:
            logger.debug(f"Getting top queries by time. limit={limit}, sort_by={sort_by}")
            extension_status = await check_extension(
                self.sql_driver,
                PG_STAT_STATEMENTS,
                include_messages=False,
            )
    
            if not extension_status.is_installed:
                logger.warning(f"Extension {PG_STAT_STATEMENTS} is not installed")
                # Return installation instructions if the extension is not installed
                return install_pg_stat_statements_message
    
            # Check PostgreSQL version to determine column names
            pg_version = await get_postgres_version(self.sql_driver)
            logger.debug(f"PostgreSQL version: {pg_version}")
    
            # Column names changed in PostgreSQL 13
            if pg_version >= 13:
                # PostgreSQL 13 and newer
                total_time_col = "total_exec_time"
                mean_time_col = "mean_exec_time"
            else:
                # PostgreSQL 12 and older
                total_time_col = "total_time"
                mean_time_col = "mean_time"
    
            logger.debug(f"Using time columns: total={total_time_col}, mean={mean_time_col}")
    
            # Determine which column to sort by based on sort_by parameter and version
            order_by_column = total_time_col if sort_by == "total" else mean_time_col

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv0.3.0

TDQS

B3.4/5.0
Behavior3/5

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

With no annotations, the description must disclose behavioral traits. It mentions reliance on the pg_stat_statements extension, which is a key dependency, but does not state whether the operation is read-only, requires special permissions, or has side effects. The term 'reports' implies read, but more detail would improve transparency.

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 a single sentence that conveys the core purpose without redundancy. It is appropriately concise and front-loaded, wasting no words.

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

Completeness2/5

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

Given no output schema, the description should explain what the tool returns (e.g., list of queries with metrics). It omits this, leaving the agent uncertain about output format. It also does not clarify what 'resource-intensive' means (e.g., which metrics). The description is insufficient for a tool with 2 parameters and no output schema.

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 baseline is 3. The tool description does not add any information about parameters beyond what the schema already provides. The schema itself is clear, but the description misses the opportunity to explain how limit and sort_by interact or give examples.

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 reports slowest or most resource-intensive queries using pg_stat_statements, which distinguishes it from siblings like analyze_query_indexes or execute_sql. The verb 'reports' and resource 'queries' with specific scope make the purpose unambiguous.

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

Usage Guidelines2/5

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

No guidance on when to use this tool versus siblings. The description implies usage for top queries but does not explicitly state when not to use it or which alternative to choose (e.g., analyze_query_indexes for index analysis). The agent must infer context from the tool name alone.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.