Skip to main content
Glama

update

Replace all fields in a SurrealDB record with new data while preserving the record ID and creation timestamp. 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)

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
dataYes
thingYes

Implementation Reference

  • The primary handler for the 'update' MCP tool. Decorated with @mcp.tool() for registration, includes input validation, database resolution, calls the repo_update helper, and formats the standardized response.
    @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)}")
  • Supporting helper function repo_update that constructs the SurrealQL UPDATE MERGE query, adds updated timestamp, executes via repo_query, and parses RecordIDs.
    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)}")
  • Detailed input parameters, arguments description, return format, and examples defining the tool's schema and usage in the docstring.
    """ 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. """
  • Helper function to resolve namespace and database from tool parameters or environment variables, used by the update handler and other tools.
    def resolve_namespace_database( namespace: Optional[str] = None, database: Optional[str] = None, ) -> Tuple[Optional[str], Optional[str]]: """ Resolve namespace and database values from parameters or environment variables. Args: namespace: Optional namespace parameter from tool call database: Optional database parameter from tool call Returns: Tuple of (resolved_namespace, resolved_database). Both will be None if using default pooled connection, or both will be strings if using override connection. Raises: ValueError: If namespace/database cannot be determined from either source """ # Get values from env vars as fallback env_namespace = os.environ.get("SURREAL_NAMESPACE") env_database = os.environ.get("SURREAL_DATABASE") # Resolve final values final_namespace = namespace if namespace is not None else env_namespace final_database = database if database is not None else env_database # If both are from env vars (or both params are None), use pooled connection if namespace is None and database is None and env_namespace and env_database: return None, None # Signal to use pooled connection # If either param is provided, we need both values resolved if final_namespace is None or final_database is None: missing = [] if final_namespace is None: missing.append("namespace") if final_database is None: missing.append("database") raise ValueError( f"Missing required database configuration: {', '.join(missing)}. " "Either set SURREAL_NAMESPACE/SURREAL_DATABASE environment variables " "or provide namespace/database parameters in the tool call." ) return final_namespace, final_database

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