Skip to main content
Glama

update

Replace all fields of a SurrealDB record with new data while preserving ID and timestamps. Use for complete record updates rather than partial modifications.

Instructions

Update a specific record with new data, completely replacing its content.

This tool performs a full update, replacing all fields (except ID and timestamps) with the provided data. For partial updates that only modify specific fields, use 'merge' or 'patch' instead.

Args: thing: The full record ID to update in format "table:id" (e.g., "user:john", "product:laptop-123") data: Complete new data for the record. All existing fields will be replaced except: - The record ID (cannot be changed) - The 'created' timestamp (preserved from original) - The 'updated' timestamp (automatically set to current time) namespace: Optional SurrealDB namespace override. If not provided, uses SURREAL_NAMESPACE env var. database: Optional SurrealDB database override. If not provided, uses SURREAL_DATABASE env var.

Returns: A dictionary containing: - success: Boolean indicating if update was successful - data: The updated record with all new values - error: Error message if update failed (only present on failure)

Examples: >>> await update("user:john", {"name": "John Smith", "email": "john.smith@example.com", "age": 31}) { "success": true, "data": {"id": "user:john", "name": "John Smith", "email": "john.smith@example.com", "age": 31, "updated": "2024-01-01T10:00:00Z"} }

Warning: This replaces ALL fields. If you only want to update specific fields, use 'merge' instead.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
thingYes
dataYes
namespaceNo
databaseNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The primary MCP 'update' tool handler. Validates input, resolves namespace/database, extracts table and ID from 'thing', calls repo_update helper, and returns formatted success response with updated record.
    @mcp.tool()
    async def update(
        thing: str,
        data: Dict[str, Any],
        namespace: Optional[str] = None,
        database: Optional[str] = None,
    ) -> Dict[str, Any]:
        """
        Update a specific record with new data, completely replacing its content.
    
        This tool performs a full update, replacing all fields (except ID and timestamps) with the provided data.
        For partial updates that only modify specific fields, use 'merge' or 'patch' instead.
    
        Args:
            thing: The full record ID to update in format "table:id" (e.g., "user:john", "product:laptop-123")
            data: Complete new data for the record. All existing fields will be replaced except:
                - The record ID (cannot be changed)
                - The 'created' timestamp (preserved from original)
                - The 'updated' timestamp (automatically set to current time)
            namespace: Optional SurrealDB namespace override. If not provided, uses SURREAL_NAMESPACE env var.
            database: Optional SurrealDB database override. If not provided, uses SURREAL_DATABASE env var.
    
        Returns:
            A dictionary containing:
            - success: Boolean indicating if update was successful
            - data: The updated record with all new values
            - error: Error message if update failed (only present on failure)
    
        Examples:
            >>> await update("user:john", {"name": "John Smith", "email": "john.smith@example.com", "age": 31})
            {
                "success": true,
                "data": {"id": "user:john", "name": "John Smith", "email": "john.smith@example.com", "age": 31, "updated": "2024-01-01T10:00:00Z"}
            }
    
        Warning: This replaces ALL fields. If you only want to update specific fields, use 'merge' instead.
        """
        try:
            ns, db = resolve_namespace_database(namespace, database)
    
            # Validate thing format
            if ":" not in thing:
                raise ValueError(f"Invalid record ID format: {thing}. Must be 'table:id'")
    
            # Extract table and id
            table, record_id = thing.split(":", 1)
    
            logger.info(f"Updating record {thing}")
            result = await repo_update(table, record_id, data, namespace=ns, database=db)
    
            # repo_update returns a list, get the first item
            updated_record = result[0] if result else {}
    
            return {
                "success": True,
                "data": updated_record
            }
        except Exception as e:
            logger.error(f"Update failed for {thing}: {str(e)}")
            raise Exception(f"Failed to update {thing}: {str(e)}")
  • Database helper function that constructs and executes the SurrealQL UPDATE MERGE query to update the record, adds updated timestamp, handles RecordID parsing, and processes results.
    async def repo_update(
        table: str,
        id: str,
        data: Dict[str, Any],
        namespace: Optional[str] = None,
        database: Optional[str] = None,
    ) -> List[Dict[str, Any]]:
        """Update an existing record by table and id.
    
        Args:
            table: The table name
            id: The record ID
            data: The data to update
            namespace: Optional namespace override (uses env var if not provided)
            database: Optional database override (uses env var if not provided)
    
        Returns:
            The updated record(s)
        """
        # If id already contains the table name, use it as is
        try:
            if isinstance(id, RecordID) or (":" in id and id.startswith(f"{table}:")):
                record_id = id
            else:
                record_id = f"{table}:{id}"
    
            data["updated"] = datetime.now(timezone.utc)
            query = f"UPDATE {record_id} MERGE $data;"
            result = await repo_query(query, {"data": data}, namespace=namespace, database=database)
            return parse_record_ids(result)
        except Exception as e:
            raise RuntimeError(f"Failed to update record: {str(e)}")
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 an excellent job disclosing behavioral traits. It explains the destructive nature ('completely replacing its content'), specifies what fields are preserved/excluded (ID, timestamps), describes the automatic timestamp update, mentions environment variable fallbacks, and documents the return structure. It doesn't mention authentication or rate limits, but covers most critical behavioral aspects.

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, examples, warning) and front-loads the most important information. While comprehensive, it could be slightly more concise as some information is repeated (e.g., the warning about using 'merge' for partial updates appears twice).

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given this is a mutation tool with no annotations, 4 parameters, 0% schema coverage, but with an output schema, the description provides complete context. It covers purpose, usage guidelines, parameter semantics, behavioral details, return values, and includes examples. The output schema existence means the description doesn't need to explain return structure in detail, which it acknowledges by summarizing rather than fully specifying.

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, the description fully compensates by providing detailed semantic explanations for all parameters. It explains the 'thing' parameter format with examples, clarifies that 'data' must contain 'complete new data', and describes the optional 'namespace' and 'database' parameters with their environment variable fallback behavior.

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 ('update a specific record', 'completely replacing its content') and distinguishes it from siblings like 'merge' and 'patch'. It explicitly identifies the resource as a 'record' and specifies it's a full replacement operation.

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 versus alternatives: 'For partial updates that only modify specific fields, use 'merge' or 'patch' instead.' It also includes a warning section reinforcing this distinction and names specific sibling tools.

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/lfnovo/surreal-mcp'

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