Skip to main content
Glama

query

Execute SQL SELECT queries to retrieve data from PostgreSQL databases. This read-only tool returns query results with rows, columns, and metadata for database analysis.

Instructions

Execute a SQL query against the PostgreSQL database.

This tool is READ-ONLY by default. Use the 'execute' tool for write operations.

Args:
    sql: SQL query to execute (SELECT statements only)
    
Returns:
    Query results with rows, columns, and metadata

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYes

Implementation Reference

  • The handler function for the 'query' MCP tool. It executes read-only SQL queries via PostgresClient.execute_query, returning results as a dictionary with rows, count, columns, and truncation status. The @mcp.tool() decorator registers it as the 'query' tool.
    @mcp.tool()
    @handle_db_error
    def query(sql: str) -> dict:
        """Execute a SQL query against the PostgreSQL database.
        
        This tool is READ-ONLY by default. Use the 'execute' tool for write operations.
        
        Args:
            sql: SQL query to execute (SELECT statements only)
            
        Returns:
            Query results with rows, columns, and metadata
        """
        client = get_client()
        settings = get_settings()
        
        result = client.execute_query(sql, allow_write=False, max_rows=settings.max_rows)
        
        return {
            "rows": result["rows"],
            "row_count": result["row_count"],
            "columns": result["columns"],
            "truncated": result.get("truncated", False),
        }
  • Core helper method in PostgresClient that performs the actual query execution, validation, and result fetching. Called by the 'query' tool handler.
    def execute_query(
        self,
        query: str,
        params: Optional[tuple] = None,
        allow_write: bool = False,
        max_rows: Optional[int] = None,
    ) -> dict[str, Any]:
        """Execute a SQL query.
        
        Args:
            query: SQL query string
            params: Optional query parameters
            allow_write: Whether to allow write operations
            max_rows: Maximum rows to return (None uses settings default)
            
        Returns:
            Dict with results, row_count, columns
        """
        # Validate query
        validated_query = validate_query(query, allow_write=allow_write)
        
        max_rows = max_rows or self.settings.max_rows
        
        with self.get_connection() as conn:
            cursor = conn.cursor()
            
            try:
                cursor.execute(validated_query, params)
                
                # Check if it's a SELECT query
                is_select = validated_query.strip().upper().startswith("SELECT")
                
                if is_select:
                    rows = cursor.fetchmany(max_rows + 1)
                    truncated = len(rows) > max_rows
                    if truncated:
                        rows = rows[:max_rows]
                    
                    columns = [desc[0] for desc in cursor.description] if cursor.description else []
                    
                    return {
                        "success": True,
                        "rows": [dict(row) for row in rows],
                        "row_count": len(rows),
                        "columns": columns,
                        "truncated": truncated,
                    }
                else:
                    conn.commit()
                    return {
                        "success": True,
                        "rows": [],
                        "row_count": cursor.rowcount,
                        "columns": [],
                        "message": f"{cursor.rowcount} rows affected",
                    }
            except psycopg2.Error as e:
                conn.rollback()
                raise PostgresClientError(f"Query failed: {e}") from e
            finally:
                cursor.close()
Behavior4/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively communicates that the tool is read-only ('READ-ONLY by default'), specifies the type of SQL allowed ('SELECT statements only'), and describes the return format ('rows, columns, and metadata'). However, it doesn't mention potential limitations like query timeout, result size limits, or authentication requirements.

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 perfectly structured and concise: a clear purpose statement, important behavioral context, and parameter/return documentation in separate labeled sections. Every sentence adds value with zero wasted words, making it easy to scan and understand quickly.

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?

For a single-parameter read-only query tool with no annotations or output schema, the description provides excellent context: purpose, usage guidelines, behavioral constraints, parameter meaning, and return format. The main gap is lack of output schema documentation, but the description compensates well by describing return values. Slightly more detail on potential limitations would make it complete.

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?

With 0% schema description coverage for the single parameter, the description compensates by explaining the 'sql' parameter meaning ('SQL query to execute') and adding the critical constraint 'SELECT statements only' that isn't in the schema. This provides essential semantic context beyond the bare schema, though it could specify format expectations or 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's purpose with specific verb ('Execute') and resource ('SQL query against the PostgreSQL database'), distinguishing it from sibling tools like 'execute' for write operations and 'explain_query' for analysis. It precisely defines what the tool does without being vague or tautological.

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

Usage Guidelines5/5

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

The description provides explicit guidance on when to use this tool vs alternatives: 'READ-ONLY by default' and 'Use the 'execute' tool for write operations.' It clearly distinguishes between read (SELECT) and write operations, naming the specific alternative tool for different use cases.

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