Skip to main content
Glama
bpamiri

CockroachDB MCP Server

by bpamiri

read_rows

Retrieve data from CockroachDB tables using flexible query parameters including WHERE clauses, column selection, ordering, and row limits.

Instructions

Read rows from a table.

Args:
    table: Table name (schema.table or just table).
    id_value: Primary key value for single row lookup.
    id_column: Name of the ID column (default: 'id').
    where: WHERE clause (without 'WHERE').
    columns: List of columns to return (default: all).
    order_by: ORDER BY clause (without 'ORDER BY').
    limit: Maximum rows to return.

Returns:
    Query results.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
tableYes
id_valueNo
id_columnNoid
whereNo
columnsNo
order_byNo
limitNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Core handler function that implements the read_rows tool logic: validates input, builds dynamic SELECT query with WHERE, ORDER BY, LIMIT, executes it using connection_manager, and returns results.
    async def read_rows(
        table: str,
        id_value: str | int | None = None,
        id_column: str = "id",
        where: str | None = None,
        columns: list[str] | None = None,
        order_by: str | None = None,
        limit: int | None = None,
    ) -> dict[str, Any]:
        """Read rows from a table.
    
        Args:
            table: Table name (schema.table or just table).
            id_value: Primary key value for single row lookup.
            id_column: Name of the ID column (default: 'id').
            where: WHERE clause (without 'WHERE').
            columns: List of columns to return (default: all).
            order_by: ORDER BY clause (without 'ORDER BY').
            limit: Maximum rows to return.
    
        Returns:
            Query results.
        """
        # Validate table name
        valid, error = _validate_table_name(table)
        if not valid:
            return {"status": "error", "error": error}
    
        schema, table_name = _parse_table_name(table)
    
        # Build column list
        if columns:
            # Validate column names
            for col in columns:
                if not re.match(r"^[\w]+$", col):
                    return {"status": "error", "error": f"Invalid column name: {col}"}
            col_list = ", ".join(columns)
        else:
            col_list = "*"
    
        # Build query
        query = f"SELECT {col_list} FROM {schema}.{table_name}"
    
        # Add WHERE clause
        params: list[Any] = []
        if id_value is not None:
            query += f" WHERE {id_column} = %s"
            params.append(id_value)
        elif where:
            query += f" WHERE {where}"
    
        # Add ORDER BY
        if order_by:
            query += f" ORDER BY {order_by}"
    
        # Add LIMIT
        effective_limit = limit if limit is not None else settings.max_rows
        query += f" LIMIT {effective_limit}"
    
        conn = await connection_manager.ensure_connected()
    
        try:
            async with conn.cursor() as cur:
                if params:
                    await cur.execute(query, tuple(params))
                else:
                    await cur.execute(query)
    
                rows = await cur.fetchall()
                columns_returned = [desc.name for desc in cur.description] if cur.description else []
    
            return {
                "status": "success",
                "table": f"{schema}.{table_name}",
                "columns": columns_returned,
                "rows": rows,
                "row_count": len(rows),
                "limit": effective_limit,
            }
        except Exception as e:
            return {"status": "error", "error": str(e)}
  • MCP tool registration using @mcp.tool() decorator. This is the entry point handler for the 'read_rows' tool, which delegates execution to the core logic in crud.read_rows.
    @mcp.tool()
    async def read_rows(
        table: str,
        id_value: str | int | None = None,
        id_column: str = "id",
        where: str | None = None,
        columns: list[str] | None = None,
        order_by: str | None = None,
        limit: int | None = None,
    ) -> dict[str, Any]:
        """Read rows from a table.
    
        Args:
            table: Table name (schema.table or just table).
            id_value: Primary key value for single row lookup.
            id_column: Name of the ID column (default: 'id').
            where: WHERE clause (without 'WHERE').
            columns: List of columns to return (default: all).
            order_by: ORDER BY clause (without 'ORDER BY').
            limit: Maximum rows to return.
    
        Returns:
            Query results.
        """
        try:
            return await crud.read_rows(table, id_value, id_column, where, columns, order_by, limit)
        except Exception as e:
            return {"status": "error", "error": str(e)}
  • Helper function to validate the table name format used in read_rows.
    def _validate_table_name(table: str) -> tuple[bool, str | None]:
        """Validate table name format.
    
        Args:
            table: Table name to validate.
    
        Returns:
            Tuple of (is_valid, error_message).
        """
        # Allow schema.table format
        if not re.match(r"^[\w]+\.[\w]+$|^[\w]+$", table):
            return False, "Invalid table name format"
        return True, None
  • Helper function to parse table name into schema and table parts, defaulting schema to 'public'.
    def _parse_table_name(table: str) -> tuple[str, str]:
        """Parse table name into schema and table.
    
        Args:
            table: Table name (schema.table or just table).
    
        Returns:
            Tuple of (schema, table_name).
        """
        if "." in table:
            schema, table_name = table.rsplit(".", 1)
        else:
            schema = "public"
            table_name = table
        return schema, table_name
  • Input/output schema defined by function signature and docstring in the registered MCP tool.
    async def read_rows(
        table: str,
        id_value: str | int | None = None,
        id_column: str = "id",
        where: str | None = None,
        columns: list[str] | None = None,
        order_by: str | None = None,
        limit: int | None = None,
    ) -> dict[str, Any]:
        """Read rows from a table.
    
        Args:
            table: Table name (schema.table or just table).
            id_value: Primary key value for single row lookup.
            id_column: Name of the ID column (default: 'id').
            where: WHERE clause (without 'WHERE').
            columns: List of columns to return (default: all).
            order_by: ORDER BY clause (without 'ORDER BY').
            limit: Maximum rows to return.
    
        Returns:
            Query results.
        """
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. While 'Read' implies a read-only operation, it doesn't explicitly state safety, permissions required, whether it's transactional, performance characteristics, or error behavior. The description mentions what parameters exist but not how they interact (e.g., 'id_value' vs 'where' usage). For a 7-parameter 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.

Conciseness4/5

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

The description is well-structured with clear sections (purpose, args, returns) and uses bullet-like formatting. Every sentence earns its place by explaining parameters or returns. It could be slightly more front-loaded by mentioning key capabilities earlier, but overall it's efficient with minimal waste.

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?

Given the tool's complexity (7 parameters, database operations) and lack of annotations, the description does well by documenting all parameters and mentioning returns. However, with an output schema present, the 'Returns: Query results' is redundant. For a read operation with many siblings, more guidance on when to use this versus 'execute_query' would improve completeness.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage (titles like 'Table', 'Id Value' provide minimal semantics), the description compensates fully by explaining each parameter's purpose and syntax. It clarifies 'table' format, 'id_value' for single row lookup, default values, and that 'where' and 'order_by' clauses should exclude the SQL keywords. This adds significant value beyond the bare 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 'Read rows from a table' - a specific verb ('Read') and resource ('rows from a table'). It distinguishes itself from siblings like 'describe_table', 'list_tables', or 'execute_query' by focusing specifically on row retrieval rather than metadata or arbitrary queries. However, it doesn't explicitly differentiate from 'execute_query' which could also read rows, so it's not a perfect 5.

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. With siblings like 'execute_query' (for arbitrary SQL) and 'describe_table' (for metadata), there's no indication whether this tool is preferred for simple row retrieval, when to use it versus 'execute_query', or any prerequisites. The agent must infer usage from the parameter structure alone.

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