Skip to main content
Glama

merge

Update specific fields in SurrealDB records using partial data merges. Modify only selected fields while preserving other record data, including nested properties.

Instructions

Merge data into a specific record, updating only the specified fields.

This tool performs a partial update, only modifying the fields provided in the data parameter. All other fields remain unchanged. This is useful when you want to:

  • Update specific fields without affecting others

  • Add new fields to an existing record

  • Modify nested properties without replacing the entire object

Args: thing: The full record ID to merge data into in format "table:id" (e.g., "user:john") data: Dictionary containing only the fields to update. Examples: - {"email": "newemail@example.com"} - updates only email - {"profile": {"bio": "New bio"}} - updates nested field - {"tags": ["python", "mcp"]} - replaces the tags array 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 merge was successful - data: The complete record after merging, with all fields - modified_fields: List of field names that were modified - error: Error message if merge failed (only present on failure)

Examples: >>> await merge("user:john", {"email": "john.new@example.com", "verified": true}) { "success": true, "data": {"id": "user:john", "name": "John Doe", "email": "john.new@example.com", "verified": true, "age": 30}, "modified_fields": ["email", "verified"] }

Note: This is equivalent to the 'patch' tool but uses object merging syntax instead of JSON Patch.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
thingYes
dataYes
namespaceNo
databaseNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The primary handler for the 'merge' MCP tool. It validates input, resolves database context, extracts the table name, calls repo_upsert to perform the SurrealDB MERGE operation, and returns the updated record with modified fields.
    async def merge(
        thing: str,
        data: Dict[str, Any],
        namespace: Optional[str] = None,
        database: Optional[str] = None,
    ) -> Dict[str, Any]:
        """
        Merge data into a specific record, updating only the specified fields.
    
        This tool performs a partial update, only modifying the fields provided in the data parameter.
        All other fields remain unchanged. This is useful when you want to:
        - Update specific fields without affecting others
        - Add new fields to an existing record
        - Modify nested properties without replacing the entire object
    
        Args:
            thing: The full record ID to merge data into in format "table:id" (e.g., "user:john")
            data: Dictionary containing only the fields to update. Examples:
                - {"email": "newemail@example.com"} - updates only email
                - {"profile": {"bio": "New bio"}} - updates nested field
                - {"tags": ["python", "mcp"]} - replaces the tags array
            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 merge was successful
            - data: The complete record after merging, with all fields
            - modified_fields: List of field names that were modified
            - error: Error message if merge failed (only present on failure)
    
        Examples:
            >>> await merge("user:john", {"email": "john.new@example.com", "verified": true})
            {
                "success": true,
                "data": {"id": "user:john", "name": "John Doe", "email": "john.new@example.com", "verified": true, "age": 30},
                "modified_fields": ["email", "verified"]
            }
    
        Note: This is equivalent to the 'patch' tool but uses object merging syntax instead of JSON Patch.
        """
        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'")
    
            logger.info(f"Merging data into {thing}")
    
            # Track which fields we're modifying
            modified_fields = list(data.keys())
    
            # Extract table name for repo_upsert
            table = thing.split(":", 1)[0]
    
            # Use repo_upsert which does a MERGE operation - pass full record ID
            result = await repo_upsert(
                table=table, id=thing, data=data, add_timestamp=True, namespace=ns, database=db
            )
    
            # Get the first result
            merged_record = result[0] if result else {}
    
            return {
                "success": True,
                "data": merged_record,
                "modified_fields": modified_fields
            }
        except Exception as e:
            logger.error(f"Merge failed for {thing}: {str(e)}")
            raise Exception(f"Failed to merge data into {thing}: {str(e)}")
  • Helper function repo_upsert that generates and executes the SurrealQL 'UPSERT <record> MERGE $data' query. This is the core database operation invoked by the merge tool to perform partial updates.
    async def repo_upsert(
        table: str,
        id: Optional[str],
        data: Dict[str, Any],
        add_timestamp: bool = False,
        namespace: Optional[str] = None,
        database: Optional[str] = None,
    ) -> List[Dict[str, Any]]:
        """Create or update a record in the specified table.
    
        Args:
            table: The table name
            id: Optional record ID (if provided, upserts that specific record)
            data: The record data to upsert
            add_timestamp: Whether to add/update the 'updated' timestamp
            namespace: Optional namespace override (uses env var if not provided)
            database: Optional database override (uses env var if not provided)
    
        Returns:
            The upserted record(s)
        """
        data.pop("id", None)
        if add_timestamp:
            data["updated"] = datetime.now(timezone.utc)
        query = f"UPSERT {id if id else table} MERGE $data;"
        return await repo_query(query, {"data": data}, namespace=namespace, database=database)
  • The @mcp.tool() decorator registers the merge function as an MCP tool with FastMCP instance.
    async def merge(
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 of behavioral disclosure. It clearly explains this is a partial update operation that only modifies specified fields while leaving others unchanged. It describes the return structure in detail and mentions the tool's equivalence to 'patch' but with different syntax. However, it doesn't mention authentication requirements, rate limits, or error handling beyond the error field in returns.

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, usage scenarios, Args, Returns, Examples, Note) and front-loads the core functionality. While comprehensive, some sections like the detailed examples and note could be slightly condensed. Every sentence adds value, but the overall length is substantial for a tool description.

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 the tool's complexity (mutation operation with 4 parameters, 0% schema coverage, and sibling tools), the description provides complete context. It explains the partial update behavior, provides detailed parameter semantics, includes a comprehensive return structure, offers practical examples, and positions the tool relative to siblings. The presence of an output schema reduces the need to explain return values, which the description acknowledges by documenting the return structure.

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 parameter explanations. Each parameter (thing, data, namespace, database) is clearly explained with examples, format requirements, and default behavior. The data parameter receives particularly thorough treatment with multiple examples showing different update scenarios.

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 as 'Merge data into a specific record, updating only the specified fields' with the specific verb 'merge' and resource 'record'. It explicitly distinguishes from the sibling 'patch' tool in the note section, stating this uses object merging syntax instead of JSON Patch.

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: 'This is useful when you want to:' followed by three specific scenarios. It also explicitly compares to the 'patch' sibling tool, indicating this is an alternative with different syntax. The examples further illustrate appropriate usage contexts.

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