Skip to main content
Glama
cloudthinker-ai

Postgres MCP Pro Plus

analyze_db_health

Analyze PostgreSQL database health by checking indexes, connections, vacuum status, sequences, replication, buffer cache, and constraints to identify performance issues and maintenance needs.

Instructions

Analyzes database health. Here are the available health checks:

  • index - checks for invalid, duplicate, and bloated indexes

  • connection - checks the number of connection and their utilization

  • vacuum - checks vacuum health for transaction id wraparound

  • sequence - checks sequences at risk of exceeding their maximum value

  • replication - checks replication health including lag and slots

  • buffer - checks for buffer cache hit rates for indexes and tables

  • constraint - checks for invalid constraints

  • all - runs all checks You can optionally specify a single health check or a comma-separated list of health checks. The default is 'all' checks.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
health_typeNoOptional. Valid values are: all, buffer, connection, constraint, index, replication, sequence, vacuum.all

Implementation Reference

  • The MCP tool handler and registration for 'analyze_db_health'. This function executes the tool logic by instantiating DatabaseHealthTool and invoking its health method.
    @mcp.tool(
        description="Analyzes database health. Here are the available health checks:\n"
        "- index - checks for invalid, duplicate, and bloated indexes\n"
        "- connection - checks the number of connection and their utilization\n"
        "- vacuum - checks vacuum health for transaction id wraparound\n"
        "- sequence - checks sequences at risk of exceeding their maximum value\n"
        "- replication - checks replication health including lag and slots\n"
        "- buffer - checks for buffer cache hit rates for indexes and tables\n"
        "- constraint - checks for invalid constraints\n"
        "- all - runs all checks\n"
        "You can optionally specify a single health check or a comma-separated list of health checks. The default is 'all' checks."
    )
    async def analyze_db_health(
        health_type: str = Field(
            description=f"Optional. Valid values are: {', '.join(sorted([t.value for t in HealthType]))}.",
            default="all",
        ),
    ) -> ResponseType:
        """Analyze database health for specified components.
    
        Args:
            health_type: Comma-separated list of health check types to perform.
                        Valid values: index, connection, vacuum, sequence, replication, buffer, constraint, all
        """
        health_tool = DatabaseHealthTool(await get_sql_driver())
        result = await health_tool.health(health_type=health_type)
        return format_text_response(result)
  • Enum defining the valid health_type parameter values, used for input validation in the tool's Pydantic Field.
    class HealthType(str, Enum):
        INDEX = "index"
        CONNECTION = "connection"
        VACUUM = "vacuum"
        SEQUENCE = "sequence"
        REPLICATION = "replication"
        BUFFER = "buffer"
        CONSTRAINT = "constraint"
        ALL = "all"
  • Core helper class implementing the database health checks. The health() method performs the specified checks using specialized calculator classes and formats the results.
    class DatabaseHealthTool:
        """Tool for analyzing database health metrics."""
    
        def __init__(self, sql_driver):
            self.sql_driver = sql_driver
    
        async def health(self, health_type: str) -> str:
            """Run database health checks and return compact, labeled results."""
            try:
    
                def compact(label: str, text: str) -> str:
                    # Join lines, strip bullets and excess spaces
                    lines = [ln.strip().lstrip("- •") for ln in text.splitlines() if ln.strip()]
                    return f"{label}: " + ("; ".join(lines) if lines else "(none)")
    
                try:
                    health_types = {HealthType(x.strip()) for x in health_type.split(",")}
                except ValueError:
                    return f"Invalid health types: '{health_type}'. Valid: " + ", ".join(sorted([t.value for t in HealthType]))
    
                if HealthType.ALL in health_types:
                    health_types = [t.value for t in HealthType if t != HealthType.ALL]
    
                out: list[str] = []
    
                if HealthType.INDEX in health_types:
                    index_health = IndexHealthCalc(self.sql_driver)
                    out.append(compact("index.invalid", await index_health.invalid_index_check()))
                    out.append(compact("index.duplicate", await index_health.duplicate_index_check()))
                    out.append(compact("index.bloat", await index_health.index_bloat()))
                    out.append(compact("index.unused", await index_health.unused_indexes()))
    
                if HealthType.CONNECTION in health_types:
                    connection_health = ConnectionHealthCalc(self.sql_driver)
                    out.append(compact("connection", await connection_health.connection_health_check()))
    
                if HealthType.VACUUM in health_types:
                    vacuum_health = VacuumHealthCalc(self.sql_driver)
                    out.append(compact("vacuum.txid", await vacuum_health.transaction_id_danger_check()))
    
                if HealthType.SEQUENCE in health_types:
                    sequence_health = SequenceHealthCalc(self.sql_driver)
                    out.append(compact("sequence", await sequence_health.sequence_danger_check()))
    
                if HealthType.REPLICATION in health_types:
                    replication_health = ReplicationCalc(self.sql_driver)
                    out.append(compact("replication", await replication_health.replication_health_check()))
    
                if HealthType.BUFFER in health_types:
                    buffer_health = BufferHealthCalc(self.sql_driver)
                    out.append(compact("buffer.index_hit", await buffer_health.index_hit_rate()))
                    out.append(compact("buffer.table_hit", await buffer_health.table_hit_rate()))
    
                if HealthType.CONSTRAINT in health_types:
                    constraint_health = ConstraintHealthCalc(self.sql_driver)
                    out.append(compact("constraint", await constraint_health.invalid_constraints_check()))
    
                return "\n".join([line for line in out if line]) if out else "No health checks performed"
            except Exception as e:
                logger.error(f"Error calculating database health: {e}", exc_info=True)
                return f"Error calculating database health: {e}"
Behavior2/5

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

No annotations are provided, so the description carries the full burden. It describes what health checks are available and how to specify them, but it doesn't disclose behavioral traits such as whether this is a read-only operation, if it requires specific permissions, potential performance impact, rate limits, or what the output format looks like. This is a significant gap for a tool with no annotation coverage.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded with the main purpose, followed by a bulleted list of checks and usage notes. Every sentence earns its place by adding necessary information, though it could be slightly more streamlined by integrating the bullet points into prose.

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

Completeness3/5

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

Given no annotations and no output schema, the description is incomplete for a tool that performs health analysis. It covers the parameter well but lacks details on behavioral aspects (e.g., safety, permissions) and output format, which are crucial for an AI agent to use it correctly. The complexity of health checks warrants more context than provided.

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?

The input schema has 100% description coverage, so the baseline is 3. The description adds value by providing a detailed list of health check categories (e.g., 'index - checks for invalid, duplicate, and bloated indexes'), which gives semantic meaning beyond the schema's enum-like list. It also clarifies that multiple checks can be specified as a comma-separated list, which isn't explicitly stated in the schema.

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?

The description clearly states the tool 'Analyzes database health' and lists specific health check categories (index, connection, vacuum, etc.), providing a specific verb+resource. However, it doesn't explicitly differentiate from sibling tools like 'analyze_query_indexes' or 'analyze_vacuum_requirements', which appear to be more specialized versions of these checks.

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?

The description implies usage by listing available health checks and stating the default is 'all' checks, but it doesn't explicitly say when to use this tool versus alternatives like the sibling tools. No exclusions or prerequisites are mentioned, leaving usage context somewhat implied rather than clearly defined.

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/cloudthinker-ai/postgres-mcp-pro-plus'

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