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

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.
        """

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