create
Add new records to SurrealDB tables with auto-generated IDs, timestamps, and schema validation. Specify table name and field data to create structured database entries.
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"}
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
| Name | Required | Description | Default |
|---|---|---|---|
| data | Yes | ||
| table | Yes |
Implementation Reference
- surreal_mcp/server.py:225-292 (handler)Primary handler function for the 'create' MCP tool. Decorated with @mcp.tool() for registration, validates inputs, calls repo_create helper, and returns formatted 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)}")
- Supporting repo_create function that implements the core database insertion logic, adds timestamps, parses RecordIDs, and handles the SurrealDB connection.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")