Skip to main content
Glama

create

Add new records to SurrealDB tables with automatic ID generation, timestamp management, and schema validation.

Instructions

Create a new record in a SurrealDB table with the specified data.

This tool creates a new record with an auto-generated ID. The system will automatically:

  • Generate a unique ID for the record

  • Add created/updated timestamps

  • Validate the data against any defined schema

Args: table: The name of the table to create the record in (e.g., "user", "product") data: A dictionary containing the field values for the new record. Examples: - {"name": "Alice", "email": "alice@example.com", "age": 30} - {"title": "Laptop", "price": 999.99, "category": "electronics"} 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 creation was successful - data: The created record including its generated ID and timestamps - id: The ID of the newly created record (convenience field) - error: Error message if creation failed (only present on failure)

Examples: >>> await create("user", {"name": "Alice", "email": "alice@example.com"}) { "success": true, "data": {"id": "user:ulid", "name": "Alice", "email": "alice@example.com", "created": "2024-01-01T10:00:00Z"}, "id": "user:ulid" }

Note: If you need to specify a custom ID, use the 'upsert' 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 'create' MCP tool. Resolves DB context, validates inputs, invokes repo_create helper, processes result, and returns standardized response.
    @mcp.tool()
    async def create(
        table: str,
        data: Dict[str, Any],
        namespace: Optional[str] = None,
        database: Optional[str] = None,
    ) -> Dict[str, Any]:
        """
        Create a new record in a SurrealDB table with the specified data.
    
        This tool creates a new record with an auto-generated ID. The system will automatically:
        - Generate a unique ID for the record
        - Add created/updated timestamps
        - Validate the data against any defined schema
    
        Args:
            table: The name of the table to create the record in (e.g., "user", "product")
            data: A dictionary containing the field values for the new record. Examples:
                - {"name": "Alice", "email": "alice@example.com", "age": 30}
                - {"title": "Laptop", "price": 999.99, "category": "electronics"}
            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 creation was successful
            - data: The created record including its generated ID and timestamps
            - id: The ID of the newly created record (convenience field)
            - error: Error message if creation failed (only present on failure)
    
        Examples:
            >>> await create("user", {"name": "Alice", "email": "alice@example.com"})
            {
                "success": true,
                "data": {"id": "user:ulid", "name": "Alice", "email": "alice@example.com", "created": "2024-01-01T10:00:00Z"},
                "id": "user:ulid"
            }
    
        Note: If you need to specify a custom ID, use the 'upsert' tool instead.
        """
        try:
            ns, db = resolve_namespace_database(namespace, database)
    
            # Validate table name
            if not table or not table.strip():
                raise ValueError("Table name cannot be empty")
    
            logger.info(f"Creating record in table {table}")
            result = await repo_create(table, data, namespace=ns, database=db)
    
            # repo_create returns a list with one element
            if isinstance(result, list) and len(result) > 0:
                record = result[0]
            else:
                record = result
    
            # Extract the ID for convenience
            record_id = record.get("id", "") if isinstance(record, dict) else ""
    
            return {
                "success": True,
                "data": record,
                "id": record_id
            }
        except Exception as e:
            logger.error(f"Create failed for table {table}: {str(e)}")
            raise Exception(f"Failed to create record in {table}: {str(e)}")
  • The @mcp.tool() decorator registers the 'create' function as an MCP tool with the name 'create' (inferred from function name).
    @mcp.tool()
  • Core database helper that executes the SurrealDB 'insert' operation for creating records, adds timestamps, handles RecordID parsing, and manages connections.
    async def repo_create(
        table: str,
        data: Dict[str, Any],
        namespace: Optional[str] = None,
        database: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Create a new record in the specified table.
    
        Args:
            table: The table to create the record in
            data: The record data
            namespace: Optional namespace override (uses env var if not provided)
            database: Optional database override (uses env var if not provided)
    
        Returns:
            The created record
        """
        # Remove 'id' attribute if it exists in data
        data.pop("id", None)
        data["created"] = datetime.now(timezone.utc)
        data["updated"] = datetime.now(timezone.utc)
        try:
            async with db_connection(namespace, database) as connection:
                return parse_record_ids(await connection.insert(table, data))
        except Exception as e:
            logger.exception(e)
            raise RuntimeError("Failed to create record")
  • Function signature with type hints defines input schema (table: str, data: Dict[str, Any], optional ns/db). Extensive docstring details args, returns, examples, serving as effective schema documentation.
    async def create(
        table: str,
        data: Dict[str, Any],
        namespace: Optional[str] = None,
        database: Optional[str] = None,
    ) -> Dict[str, Any]:
        """
        Create a new record in a SurrealDB table with the specified data.
    
        This tool creates a new record with an auto-generated ID. The system will automatically:
        - Generate a unique ID for the record
        - Add created/updated timestamps
        - Validate the data against any defined schema
    
        Args:
            table: The name of the table to create the record in (e.g., "user", "product")
            data: A dictionary containing the field values for the new record. Examples:
                - {"name": "Alice", "email": "alice@example.com", "age": 30}
                - {"title": "Laptop", "price": 999.99, "category": "electronics"}
            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 creation was successful
            - data: The created record including its generated ID and timestamps
            - id: The ID of the newly created record (convenience field)
            - error: Error message if creation failed (only present on failure)
    
        Examples:
            >>> await create("user", {"name": "Alice", "email": "alice@example.com"})
            {
                "success": true,
                "data": {"id": "user:ulid", "name": "Alice", "email": "alice@example.com", "created": "2024-01-01T10:00:00Z"},
                "id": "user:ulid"
            }
    
        Note: If you need to specify a custom ID, use the 'upsert' tool instead.
        """
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 by disclosing key behaviors: auto-generated ID, automatic timestamp addition, schema validation, and fallback to environment variables for namespace/database. It doesn't mention error handling specifics or rate limits, but covers most critical aspects.

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 with clear sections (purpose, system behavior, args, returns, examples, note). Every sentence adds value - no redundancy. The information is front-loaded with the core purpose first, followed by supporting details.

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 4 parameters with 0% schema coverage and no annotations, the description provides comprehensive coverage: purpose, usage guidelines, parameter details with examples, return format, and sibling differentiation. The output schema exists, so return values don't need explanation in the description.

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?

Schema description coverage is 0%, so the description must fully compensate. It provides detailed parameter explanations with examples for 'data', clarifies optional vs. required parameters, explains default behaviors for namespace/database, and gives concrete examples of valid inputs.

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: 'Create a new record in a SurrealDB table with the specified data.' It specifies the verb ('create'), resource ('record in a SurrealDB table'), and distinguishes from siblings by mentioning auto-generated ID and pointing to 'upsert' for custom IDs.

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 alternatives: 'If you need to specify a custom ID, use the 'upsert' tool instead.' It also clarifies the default behavior (auto-generated ID) and when to use optional parameters (namespace/database overrides).

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