Skip to main content
Glama
bpamiri

CockroachDB MCP Server

by bpamiri

upsert_row

Insert new rows or update existing ones in CockroachDB tables using UPSERT operations, handling conflicts with specified columns and returning results as needed.

Instructions

Insert or update a row (UPSERT).

Args:
    table: Table name (schema.table or just table).
    data: Column names and values.
    conflict_columns: Columns to check for conflicts (usually primary key).
    update_columns: Columns to update on conflict (default: all except conflict columns).
    returning: Columns to return.

Returns:
    Upsert result.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
tableYes
dataYes
conflict_columnsYes
update_columnsNo
returningNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • MCP tool handler and registration for upsert_row. Defines input schema via annotations and docstring. Delegates to helper in crud module.
    @mcp.tool()
    async def upsert_row(
        table: str,
        data: dict[str, Any],
        conflict_columns: list[str],
        update_columns: list[str] | None = None,
        returning: list[str] | None = None,
    ) -> dict[str, Any]:
        """Insert or update a row (UPSERT).
    
        Args:
            table: Table name (schema.table or just table).
            data: Column names and values.
            conflict_columns: Columns to check for conflicts (usually primary key).
            update_columns: Columns to update on conflict (default: all except conflict columns).
            returning: Columns to return.
    
        Returns:
            Upsert result.
        """
        try:
            return await crud.upsert_row(table, data, conflict_columns, update_columns, returning)
        except Exception as e:
            return {"status": "error", "error": str(e)}
  • Supporting utility function containing the core logic for executing the UPSERT operation on CockroachDB, including validation, query building, and execution.
    async def upsert_row(
        table: str,
        data: dict[str, Any],
        conflict_columns: list[str],
        update_columns: list[str] | None = None,
        returning: list[str] | None = None,
    ) -> dict[str, Any]:
        """Insert or update a row (UPSERT).
    
        Args:
            table: Table name (schema.table or just table).
            data: Column names and values.
            conflict_columns: Columns to check for conflicts (usually primary key).
            update_columns: Columns to update on conflict (default: all except conflict columns).
            returning: Columns to return.
    
        Returns:
            Upsert result.
        """
        # Check read-only mode
        if settings.read_only:
            return {"status": "error", "error": "Server is in read-only mode"}
    
        # Validate table name
        valid, error = _validate_table_name(table)
        if not valid:
            return {"status": "error", "error": error}
    
        if not data:
            return {"status": "error", "error": "No data provided"}
    
        if not conflict_columns:
            return {"status": "error", "error": "No conflict columns specified"}
    
        schema, table_name = _parse_table_name(table)
    
        # Validate all column names
        all_columns = list(data.keys()) + conflict_columns + (update_columns or []) + (returning or [])
        for col in all_columns:
            if not re.match(r"^[\w]+$", col):
                return {"status": "error", "error": f"Invalid column name: {col}"}
    
        # Determine columns to update
        if update_columns is None:
            update_columns = [c for c in data.keys() if c not in conflict_columns]
    
        if not update_columns:
            return {"status": "error", "error": "No columns to update on conflict"}
    
        # Build UPSERT query
        columns = list(data.keys())
        placeholders = ", ".join(["%s"] * len(columns))
        col_list = ", ".join(columns)
        values = list(data.values())
    
        conflict_list = ", ".join(conflict_columns)
        update_set = ", ".join([f"{col} = EXCLUDED.{col}" for col in update_columns])
    
        query = f"""
            INSERT INTO {schema}.{table_name} ({col_list})
            VALUES ({placeholders})
            ON CONFLICT ({conflict_list}) DO UPDATE SET {update_set}
        """
    
        # Add RETURNING clause
        if returning:
            query += f" RETURNING {', '.join(returning)}"
    
        conn = await connection_manager.ensure_connected()
    
        try:
            async with conn.cursor() as cur:
                await cur.execute(query, tuple(values))
    
                if returning:
                    row = await cur.fetchone()
                    return {
                        "status": "success",
                        "table": f"{schema}.{table_name}",
                        "action": "upserted",
                        "returning": row,
                    }
                else:
                    return {
                        "status": "success",
                        "table": f"{schema}.{table_name}",
                        "action": "upserted",
                        "rows_affected": cur.rowcount,
                    }
        except Exception as e:
            return {"status": "error", "error": str(e)}
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 'Insert or update' implies mutation, it doesn't specify permissions needed, whether the operation is atomic, what happens on partial conflicts, or error conditions. The description mentions what parameters do but lacks operational context about the upsert behavior.

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 a clear purpose statement followed by organized parameter explanations. Every sentence serves a purpose: the first defines the operation, and the subsequent sections document parameters and returns without redundancy.

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?

For a mutation tool with 5 parameters, no annotations, but with an output schema, the description covers parameters well but lacks behavioral context. The presence of an output schema means the description doesn't need to explain return values, but it should provide more operational guidance for a complex upsert operation.

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 all 5 parameters in the Args section. It clarifies the purpose of each parameter (table name, column data, conflict detection, update behavior, and return values), adding 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 'Insert or update a row (UPSERT)' which specifies the verb (insert/update) and resource (row). It distinguishes from siblings like insert_row and update_row by combining both operations, though it doesn't explicitly contrast with them in the description text itself.

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 like insert_row or update_row. There's no mention of prerequisites, typical use cases, or scenarios where upsert is preferred over separate insert/update 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/bpamiri/cockroachdb-mcp'

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