Skip to main content
Glama
bpamiri

CockroachDB MCP Server

by bpamiri

execute_query

Execute SQL queries on CockroachDB clusters to retrieve data, perform CRUD operations, and monitor database performance with configurable safety controls.

Instructions

Execute a SQL query.

Args:
    sql: SQL statement to execute.
    max_rows: Maximum rows to return (default: from config).

Returns:
    Query results with columns and rows.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYes
max_rowsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • MCP tool registration via @mcp.tool() decorator for the 'execute_query' tool. This is the primary handler invoked by the MCP server, which delegates to the query module.
    @mcp.tool()
    async def execute_query(sql: str, max_rows: int | None = None) -> dict[str, Any]:
        """Execute a SQL query.
    
        Args:
            sql: SQL statement to execute.
            max_rows: Maximum rows to return (default: from config).
    
        Returns:
            Query results with columns and rows.
        """
        try:
            return await query.execute_query(sql, max_rows)
        except Exception as e:
            return {"status": "error", "error": str(e)}
  • Main handler logic for executing queries: performs validation (blocked commands, read-only mode) before calling the connection manager.
    async def execute_query(
        query: str,
        max_rows: int | None = None,
    ) -> dict[str, Any]:
        """Execute a SQL query.
    
        Args:
            query: SQL query to execute.
            max_rows: Maximum rows to return.
    
        Returns:
            Query results.
        """
        # Validate first
        validation = await validate_query(query)
        if not validation["is_valid"]:
            return {
                "status": "error",
                "error": "Query validation failed",
                "issues": validation["issues"],
            }
    
        return await connection_manager.execute_query(query, max_rows=max_rows)
  • Low-level helper that executes the SQL query using psycopg AsyncConnection, handles SELECT/non-SELECT, row limits, and formatting results.
    async def execute_query(
        self,
        query: str,
        params: tuple[Any, ...] | None = None,
        max_rows: int | None = None,
    ) -> dict[str, Any]:
        """Execute a query and return results.
    
        Args:
            query: SQL query to execute.
            params: Query parameters.
            max_rows: Maximum rows to return.
    
        Returns:
            Query results.
        """
        conn = await self.ensure_connected()
    
        effective_max_rows = max_rows if max_rows is not None else settings.max_rows
    
        try:
            async with conn.cursor() as cur:
                if params:
                    await cur.execute(query, params)
                else:
                    await cur.execute(query)
    
                # Check if query returns results
                if cur.description is None:
                    # Non-SELECT query (INSERT, UPDATE, DELETE, etc.)
                    return {
                        "status": "success",
                        "rows_affected": cur.rowcount,
                        "message": f"{cur.rowcount} row(s) affected",
                    }
    
                # Fetch results with limit
                rows = await cur.fetchmany(effective_max_rows)
                total_fetched = len(rows)
    
                # Check if there are more rows
                has_more = False
                if total_fetched == effective_max_rows:
                    extra = await cur.fetchone()
                    has_more = extra is not None
    
                # Get column names
                columns = [desc.name for desc in cur.description]
    
                return {
                    "status": "success",
                    "columns": columns,
                    "rows": rows,
                    "row_count": total_fetched,
                    "has_more": has_more,
                    "max_rows": effective_max_rows,
                }
        except Exception as e:
            return {"status": "error", "error": str(e)}
  • Input validation schema/logic: checks for blocked commands, read-only mode compatibility, determines query type, and provides validation feedback.
    async def validate_query(query: str) -> dict[str, Any]:
        """Validate a SQL query without executing it.
    
        Args:
            query: SQL query to validate.
    
        Returns:
            Validation result with is_valid and any issues.
        """
        issues: list[str] = []
    
        # Check for empty query
        if not query or not query.strip():
            return {
                "is_valid": False,
                "issues": ["Query is empty"],
                "query_type": None,
            }
    
        # Check for blocked commands
        is_blocked, blocked_cmd = _is_blocked_command(query)
        if is_blocked:
            issues.append(f"Blocked command: {blocked_cmd}")
    
        # Check read-only mode
        if settings.read_only and not _is_read_only_query(query):
            issues.append("Server is in read-only mode; only SELECT/SHOW/EXPLAIN allowed")
    
        # Determine query type
        query_upper = query.strip().upper()
        if query_upper.startswith("SELECT") or query_upper.startswith("WITH"):
            query_type = "SELECT"
        elif query_upper.startswith("INSERT"):
            query_type = "INSERT"
        elif query_upper.startswith("UPDATE"):
            query_type = "UPDATE"
        elif query_upper.startswith("DELETE"):
            query_type = "DELETE"
        elif query_upper.startswith("SHOW"):
            query_type = "SHOW"
        elif query_upper.startswith("EXPLAIN"):
            query_type = "EXPLAIN"
        else:
            query_type = "OTHER"
    
        return {
            "is_valid": len(issues) == 0,
            "issues": issues,
            "query_type": query_type,
            "is_read_only": _is_read_only_query(query),
        }
Behavior2/5

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

No annotations are provided, so the description carries full burden. It mentions 'default: from config' for max_rows, which adds some behavioral context, but doesn't disclose critical traits like whether queries are read-only, require specific permissions, have timeout limits, or affect database state. For a SQL execution tool with zero annotation coverage, this is inadequate.

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?

Perfectly concise with three sentences: purpose statement, parameter explanations, and return value description. Each sentence earns its place. The structure is front-loaded with the core purpose first, followed by details.

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?

The description covers basic purpose and parameters adequately. With an output schema present, it doesn't need to detail return values. However, for a SQL execution tool with many transactional siblings and no annotations, it should address behavioral aspects like read-only vs. write operations, transaction context, or error handling.

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, the description compensates well by explaining both parameters: 'sql: SQL statement to execute' and 'max_rows: Maximum rows to return (default: from config)'. This adds meaningful semantics beyond the bare schema. However, it doesn't specify SQL dialect or max_rows constraints.

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 'Execute a SQL query' - a specific verb (execute) and resource (SQL query). It distinguishes from siblings like 'explain_query' or 'validate_query' by focusing on execution rather than analysis. However, it doesn't explicitly differentiate from 'read_rows' which might also retrieve data.

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?

No guidance is provided on when to use this tool versus alternatives. With many sibling tools for database operations (begin_transaction, insert_row, update_row, etc.), the description doesn't indicate whether this is for read-only queries, DML operations, or both. No prerequisites or exclusions are mentioned.

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/bpamiri/cockroachdb-mcp'

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