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
Behavior3/5

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

No annotations provided, so full burden on description. Discloses data source (pg_stat_statements extension) which implies requirements. Missing: safety profile (read-only vs destructive), performance cost of running this report, or behavior when extension is unavailable.

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?

Single well-formed sentence, front-loaded with action. Zero waste. Appropriate length for the tool's complexity.

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?

Adequate for a 2-parameter reporting tool with 100% schema coverage. Mentions data source and ranking criteria. Lacking output schema, could benefit from noting if results include query text, call counts, or just identifiers, but acceptable scope.

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?

Schema coverage is 100% with complete param descriptions. Description adds crucial domain context that these are PostgreSQL queries from pg_stat_statements, which helps interpret the 'total_time', 'mean_time', and 'resources' sort options. Elevates above baseline 3.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

Clear verb 'Reports' with specific resource 'queries' and data source 'pg_stat_statements'. Identifies the scope as slowest/resource-intensive queries. Lacks explicit differentiation from siblings like 'explain_query' (which analyzes specific queries) or 'analyze_query_indexes'.

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?

Implies prerequisite by mentioning dependency on 'pg_stat_statements' extension. However, lacks explicit when-to-use guidance versus siblings ('explain_query' for specific query analysis vs this for top-N discovery) or when-not-to-use warnings.

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/moecodeshere/mcptrial'

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