Skip to main content
Glama

execute

Execute write SQL statements (INSERT, UPDATE, DELETE) to modify PostgreSQL database data. Use with caution as this tool directly changes database content.

Instructions

Execute a write SQL statement (INSERT, UPDATE, DELETE).

WARNING: This tool modifies data. Use with caution.
Only available if ALLOW_WRITE_OPERATIONS=true is set.

Args:
    sql: SQL statement to execute
    
Returns:
    Execution result with affected row count

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYes

Implementation Reference

  • The primary handler for the 'execute' tool. Decorated with @mcp.tool() for registration in FastMCP. Performs permission check and calls the underlying PostgresClient.execute_query method.
    @mcp.tool()
    @handle_db_error
    def execute(sql: str) -> dict:
        """Execute a write SQL statement (INSERT, UPDATE, DELETE).
        
        WARNING: This tool modifies data. Use with caution.
        Only available if ALLOW_WRITE_OPERATIONS=true is set.
        
        Args:
            sql: SQL statement to execute
            
        Returns:
            Execution result with affected row count
        """
        settings = get_settings()
        
        if not settings.allow_write_operations:
            return {
                "success": False,
                "error": "Write operations are disabled. Set ALLOW_WRITE_OPERATIONS=true to enable.",
            }
        
        client = get_client()
        result = client.execute_query(sql, allow_write=True)
        
        return {
            "success": True,
            "row_count": result["row_count"],
            "message": result.get("message", "Query executed successfully"),
        }
  • Supporting helper method PostgresClient.execute_query that implements the actual SQL execution logic, including validation, connection management, result formatting, and handling both SELECT and write operations.
    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 and does well by disclosing critical behavioral traits: it's a data-modifying operation ('modifies data'), includes a caution warning, and specifies an environmental prerequisite. It could improve by mentioning transaction behavior or error handling.

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 efficiently structured with purpose first, warnings and prerequisites clearly highlighted, and parameter/return sections separated. Every sentence adds value with no redundancy.

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 write operation with no annotations and no output schema, the description is quite complete—covering purpose, warnings, prerequisites, parameters, and returns. It could be slightly improved by detailing the return format beyond 'affected row count'.

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 description coverage is 0%, but the description compensates by explaining the 'sql' parameter as 'SQL statement to execute' and specifying it must be a write statement (INSERT, UPDATE, DELETE), adding meaningful context beyond the bare schema.

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 verbs ('execute a write SQL statement') and resource types (INSERT, UPDATE, DELETE), and distinguishes it from sibling tools that are primarily read operations like query, describe_table, etc.

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?

Explicit guidance is provided on when to use ('execute a write SQL statement') and when not to use ('Only available if ALLOW_WRITE_OPERATIONS=true is set'), with clear alternatives implied through sibling tool names like 'query' for read operations.

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