Skip to main content
Glama

table_stats

Retrieve PostgreSQL table statistics including row count, size metrics, and vacuum information to monitor database performance and storage usage.

Instructions

Get statistics for a table (row count, size, bloat).

Args:
    table_name: Name of the table
    schema: Schema name (default: public)
    
Returns:
    Table statistics including row count, sizes, and vacuum info

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
table_nameYes
schemaNopublic

Implementation Reference

  • The primary handler function for the 'table_stats' MCP tool. Decorated with @mcp.tool() for registration and execution. Fetches stats via PostgresClient and formats the response dictionary.
    @mcp.tool()
    @handle_db_error
    def table_stats(table_name: str, schema: str = "public") -> dict:
        """Get statistics for a table (row count, size, bloat).
        
        Args:
            table_name: Name of the table
            schema: Schema name (default: public)
            
        Returns:
            Table statistics including row count, sizes, and vacuum info
        """
        client = get_client()
        stats = client.get_table_stats(table_name, schema)
        
        if not stats:
            return not_found_response("Table", f"{schema}.{table_name}")
        
        return {
            "schema": schema,
            "table_name": table_name,
            "row_count": stats.get("row_count"),
            "row_count_formatted": format_count(stats.get("row_count")),
            "dead_tuples": stats.get("dead_tuples"),
            "total_size": stats.get("total_size"),
            "total_size_formatted": format_bytes(stats.get("total_size")),
            "table_size": stats.get("table_size"),
            "table_size_formatted": format_bytes(stats.get("table_size")),
            "index_size": stats.get("index_size"),
            "index_size_formatted": format_bytes(stats.get("index_size")),
            "last_vacuum": str(stats.get("last_vacuum")) if stats.get("last_vacuum") else None,
            "last_analyze": str(stats.get("last_analyze")) if stats.get("last_analyze") else None,
        }
  • Helper method in PostgresClient that executes the SQL query against pg_stat_user_tables to retrieve raw table statistics, called by the tool handler.
    def get_table_stats(self, table_name: str, schema: str = "public") -> dict[str, Any]:
        """Get table statistics.
        
        Args:
            table_name: Table name
            schema: Schema name
            
        Returns:
            Dict with table statistics
        """
        query = """
            SELECT 
                schemaname,
                relname AS table_name,
                n_live_tup AS row_count,
                n_dead_tup AS dead_tuples,
                last_vacuum,
                last_autovacuum,
                last_analyze,
                last_autoanalyze,
                pg_total_relation_size(schemaname || '.' || relname) AS total_size,
                pg_table_size(schemaname || '.' || relname) AS table_size,
                pg_indexes_size(schemaname || '.' || relname) AS index_size
            FROM pg_stat_user_tables
            WHERE schemaname = %s AND relname = %s
        """
        with self.get_cursor() as cursor:
            cursor.execute(query, (schema, table_name))
            row = cursor.fetchone()
            if row:
                return dict(row)
            return {}
  • Pydantic model defining the structure for TableStats, including a from_row classmethod to parse database rows. Imported in server.py, provides type definitions for table statistics.
    class TableStats(BaseModel):
        """Table statistics."""
        
        schema_name: str
        table_name: str
        row_count: Optional[int] = None
        total_size: Optional[int] = None
        table_size: Optional[int] = None
        index_size: Optional[int] = None
        toast_size: Optional[int] = None
        dead_tuples: Optional[int] = None
        last_vacuum: Optional[str] = None
        last_analyze: Optional[str] = None
        
        @classmethod
        def from_row(cls, row: dict) -> "TableStats":
            return cls(
                schema_name=row.get("schemaname", "public"),
                table_name=row.get("relname", row.get("table_name", "")),
                row_count=row.get("n_live_tup", row.get("row_count")),
                total_size=row.get("total_size"),
                table_size=row.get("table_size"),
                index_size=row.get("index_size"),
                toast_size=row.get("toast_size"),
                dead_tuples=row.get("n_dead_tup"),
                last_vacuum=str(row.get("last_vacuum")) if row.get("last_vacuum") else None,
                last_analyze=str(row.get("last_analyze")) if row.get("last_analyze") else None,
            )
Behavior3/5

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

With no annotations provided, the description carries the full burden. It clearly describes the read-only nature ('Get statistics') and specifies what information is returned, but lacks details on behavioral aspects like error handling, performance implications, or whether it requires specific permissions.

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. It front-loads the core purpose, then clearly lists arguments and returns in separate sections. Every sentence adds value with no redundant information.

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 the tool's moderate complexity (2 parameters, no output schema, no annotations), the description is adequate but has gaps. It covers the purpose and parameters well, but lacks information about return format details (e.g., structure of 'vacuum info') and doesn't address potential limitations or error cases.

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 description adds significant value beyond the input schema, which has 0% description coverage. It explains both parameters: 'table_name' as 'Name of the table' and 'schema' as 'Schema name (default: public)', including the default value. This compensates well for the schema's lack of descriptions.

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's purpose with a specific verb ('Get') and resource ('statistics for a table'), and lists the specific statistics returned (row count, size, bloat). However, it doesn't explicitly differentiate from sibling tools like 'describe_table' or 'list_tables', which might also provide table information.

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?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools like 'describe_table' (which might provide metadata) or 'list_tables' (which might list tables without statistics), leaving the agent to infer usage context.

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/JaviMaligno/postgres-mcp'

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