Skip to main content
Glama

insert

Insert multiple records into a SurrealDB table in a single bulk operation. Optimized for efficient data insertion with auto-generated IDs, timestamps, and schema validation.

Instructions

Insert multiple records into a table in a single operation.

This tool is optimized for bulk inserts when you need to create many records at once. It's more efficient than calling 'create' multiple times. Each record will get:

  • An auto-generated unique ID

  • Automatic created/updated timestamps

  • Schema validation (if defined)

Args: table: The name of the table to insert records into (e.g., "user", "product") data: Array of dictionaries, each representing a record to insert. Example: [ {"name": "Alice", "email": "alice@example.com"}, {"name": "Bob", "email": "bob@example.com"}, {"name": "Charlie", "email": "charlie@example.com"} ] 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 insertion was successful - data: Array of all inserted records with their generated IDs - count: Number of records successfully inserted - error: Error message if insertion failed (only present on failure)

Examples: >>> await insert("user", [ ... {"name": "Alice", "role": "admin"}, ... {"name": "Bob", "role": "user"} ... ]) { "success": true, "data": [ {"id": "user:ulid1", "name": "Alice", "role": "admin", "created": "..."}, {"id": "user:ulid2", "name": "Bob", "role": "user", "created": "..."} ], "count": 2 }

Note: For single record creation, use the 'create' tool instead.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
tableYes
dataYes
namespaceNo
databaseNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The primary handler for the 'insert' tool. This FastMCP-decorated async function handles input validation, namespace resolution, timestamp addition, delegates to repo_insert helper, and formats the response.
    @mcp.tool()
    async def insert(
        table: str,
        data: List[Dict[str, Any]],
        namespace: Optional[str] = None,
        database: Optional[str] = None,
    ) -> Dict[str, Any]:
        """
        Insert multiple records into a table in a single operation.
    
        This tool is optimized for bulk inserts when you need to create many records at once.
        It's more efficient than calling 'create' multiple times. Each record will get:
        - An auto-generated unique ID
        - Automatic created/updated timestamps
        - Schema validation (if defined)
    
        Args:
            table: The name of the table to insert records into (e.g., "user", "product")
            data: Array of dictionaries, each representing a record to insert. Example:
                [
                    {"name": "Alice", "email": "alice@example.com"},
                    {"name": "Bob", "email": "bob@example.com"},
                    {"name": "Charlie", "email": "charlie@example.com"}
                ]
            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 insertion was successful
            - data: Array of all inserted records with their generated IDs
            - count: Number of records successfully inserted
            - error: Error message if insertion failed (only present on failure)
    
        Examples:
            >>> await insert("user", [
            ...     {"name": "Alice", "role": "admin"},
            ...     {"name": "Bob", "role": "user"}
            ... ])
            {
                "success": true,
                "data": [
                    {"id": "user:ulid1", "name": "Alice", "role": "admin", "created": "..."},
                    {"id": "user:ulid2", "name": "Bob", "role": "user", "created": "..."}
                ],
                "count": 2
            }
    
        Note: For single record creation, use the 'create' tool instead.
        """
        try:
            ns, db = resolve_namespace_database(namespace, database)
    
            if not data or not isinstance(data, list):
                raise ValueError("Data must be a non-empty array of records")
    
            logger.info(f"Inserting {len(data)} records into table {table}")
    
            # Add timestamps to each record
            from datetime import datetime, timezone
            now = datetime.now(timezone.utc)
            for record in data:
                record["created"] = record.get("created", now)
                record["updated"] = record.get("updated", now)
    
            result = await repo_insert(table, data, namespace=ns, database=db)
    
            # Ensure result is a list
            if not isinstance(result, list):
                result = [result] if result else []
    
            return {
                "success": True,
                "data": result,
                "count": len(result)
            }
        except Exception as e:
            logger.error(f"Insert failed for table {table}: {str(e)}")
            raise Exception(f"Failed to insert records into {table}: {str(e)}")
  • Supporting function repo_insert that executes the bulk INSERT operation on the SurrealDB connection, handles RecordID parsing, and manages duplicate errors.
    async def repo_insert(
        table: str,
        data: List[Dict[str, Any]],
        ignore_duplicates: bool = False,
        namespace: Optional[str] = None,
        database: Optional[str] = None,
    ) -> List[Dict[str, Any]]:
        """Insert multiple records into a table.
    
        Args:
            table: The table to insert into
            data: List of records to insert
            ignore_duplicates: Whether to ignore duplicate key errors
            namespace: Optional namespace override (uses env var if not provided)
            database: Optional database override (uses env var if not provided)
    
        Returns:
            The inserted records
        """
        try:
            async with db_connection(namespace, database) as connection:
                return parse_record_ids(await connection.insert(table, data))
        except Exception as e:
            if ignore_duplicates and "already contains" in str(e):
                return []
            logger.exception(e)
            raise RuntimeError("Failed to create record")
  • Utility helper to recursively convert SurrealDB RecordID objects to strings in query results, used by repo_insert.
    def parse_record_ids(obj: Any) -> Any:
        """Recursively parse and convert RecordIDs into strings."""
        if isinstance(obj, dict):
            return {k: parse_record_ids(v) for k, v in obj.items()}
        elif isinstance(obj, list):
            return [parse_record_ids(item) for item in obj]
        elif isinstance(obj, RecordID):
            return str(obj)
        return obj
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden and does well. It discloses behavioral traits: bulk operation optimization, automatic ID generation, timestamp handling, schema validation, and fallback behavior for namespace/database parameters. It doesn't mention error handling specifics beyond the return structure, but covers most key behaviors for a write operation.

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 well-structured and appropriately sized. It starts with the core purpose, then provides optimization context, behavioral details, parameter explanations with examples, return format, usage example, and finally sibling tool guidance. Every section adds value with no wasted sentences, and information is front-loaded effectively.

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 complexity of a bulk insert operation with 4 parameters, no annotations, but with an output schema, the description is complete. It covers purpose, usage guidelines, behavioral traits, parameter semantics with examples, return format explanation, and sibling tool differentiation. The output schema existence means the description doesn't need to detail return structure, which it acknowledges while still explaining key aspects.

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 semantics. It explains each parameter's purpose, provides examples for the 'data' array, and clarifies default behavior for optional parameters. The description adds substantial meaning beyond what the bare schema provides, making parameter usage clear.

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: 'Insert multiple records into a table in a single operation.' It specifies the verb ('insert'), resource ('records into a table'), and scope ('multiple records in a single operation'). It also distinguishes from sibling 'create' tool in the Note section, making it specific and differentiated.

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: 'optimized for bulk inserts when you need to create many records at once' and 'more efficient than calling 'create' multiple times.' It also explicitly states when not to use it: 'For single record creation, use the 'create' tool instead.' This gives clear alternatives and context for tool selection.

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