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

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)}")

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