Skip to main content
Glama

relate

Create graph relationships between records in SurrealDB to model connections like follows, likes, or purchases with optional relationship data.

Instructions

Create a graph relation (edge) between two records in SurrealDB.

This tool creates relationships in SurrealDB's graph structure, allowing you to:

  • Connect records with named relationships

  • Store data on the relationship itself

  • Build complex graph queries later

  • Model many-to-many relationships efficiently

Args: from_thing: The source record ID in format "table:id" (e.g., "user:john") relation_name: The name of the relation/edge table (e.g., "likes", "follows", "purchased") to_thing: The destination record ID in format "table:id" (e.g., "product:laptop-123") data: Optional dictionary containing data to store on the relation itself. Examples: - {"rating": 5, "review": "Great product!"} - {"quantity": 2, "price": 99.99} - {"since": "2024-01-01", "type": "friend"}

Returns: A dictionary containing: - success: Boolean indicating if relation was created successfully - data: The created relation record(s) - relation_id: The ID of the created relation - error: Error message if creation failed (only present on failure)

Examples: >>> await relate("user:john", "likes", "product:laptop-123", {"rating": 5}) { "success": true, "data": [{"id": "likes:xyz", "in": "user:john", "out": "product:laptop-123", "rating": 5}], "relation_id": "likes:xyz" }

>>> await relate("user:alice", "follows", "user:bob") { "success": true, "data": [{"id": "follows:abc", "in": "user:alice", "out": "user:bob"}], "relation_id": "follows:abc" }

Note: You can query these relations later using graph syntax: SELECT * FROM user:john->likes->product SELECT * FROM user:alice->follows->user

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dataNo
from_thingYes
relation_nameYes
to_thingYes

Implementation Reference

  • The @mcp.tool()-decorated async function that serves as the main handler for the 'relate' MCP tool. It handles input validation, resolves database context, calls the repo_relate helper, formats the response, and includes comprehensive documentation defining the tool schema.
    @mcp.tool() async def relate( from_thing: str, relation_name: str, to_thing: str, data: Optional[Dict[str, Any]] = None, namespace: Optional[str] = None, database: Optional[str] = None, ) -> Dict[str, Any]: """ Create a graph relation (edge) between two records in SurrealDB. This tool creates relationships in SurrealDB's graph structure, allowing you to: - Connect records with named relationships - Store data on the relationship itself - Build complex graph queries later - Model many-to-many relationships efficiently Args: from_thing: The source record ID in format "table:id" (e.g., "user:john") relation_name: The name of the relation/edge table (e.g., "likes", "follows", "purchased") to_thing: The destination record ID in format "table:id" (e.g., "product:laptop-123") data: Optional dictionary containing data to store on the relation itself. Examples: - {"rating": 5, "review": "Great product!"} - {"quantity": 2, "price": 99.99} - {"since": "2024-01-01", "type": "friend"} 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 relation was created successfully - data: The created relation record(s) - relation_id: The ID of the created relation - error: Error message if creation failed (only present on failure) Examples: >>> await relate("user:john", "likes", "product:laptop-123", {"rating": 5}) { "success": true, "data": [{"id": "likes:xyz", "in": "user:john", "out": "product:laptop-123", "rating": 5}], "relation_id": "likes:xyz" } >>> await relate("user:alice", "follows", "user:bob") { "success": true, "data": [{"id": "follows:abc", "in": "user:alice", "out": "user:bob"}], "relation_id": "follows:abc" } Note: You can query these relations later using graph syntax: SELECT * FROM user:john->likes->product SELECT * FROM user:alice->follows->user """ try: ns, db = resolve_namespace_database(namespace, database) # Validate thing formats if ":" not in from_thing: raise ValueError(f"Invalid source record ID format: {from_thing}. Must be 'table:id'") if ":" not in to_thing: raise ValueError(f"Invalid destination record ID format: {to_thing}. Must be 'table:id'") if not relation_name: raise ValueError("Relation name is required") logger.info(f"Creating relation: {from_thing} -> {relation_name} -> {to_thing}") # Create the relation result = await repo_relate( from_thing, relation_name, to_thing, data or {}, namespace=ns, database=db ) # Extract relation ID if available relation_id = "" if result and isinstance(result, list) and len(result) > 0: first_result = result[0] if isinstance(first_result, dict) and "id" in first_result: relation_id = first_result["id"] return { "success": True, "data": result, "relation_id": relation_id } except Exception as e: logger.error(f"Failed to create relation {from_thing}->{relation_name}->{to_thing}: {str(e)}") raise Exception(f"Failed to create relation: {str(e)}")
  • Supporting database function repo_relate that constructs and executes the SurrealQL RELATE query to create the graph relationship edge between source and target records.
    async def repo_relate( source: str, relationship: str, target: str, data: Optional[Dict[str, Any]] = None, namespace: Optional[str] = None, database: Optional[str] = None, ) -> List[Dict[str, Any]]: """Create a relationship between two records with optional data. Args: source: The source record ID relationship: The relationship/edge name target: The target record ID data: Optional data to store on the relationship namespace: Optional namespace override (uses env var if not provided) database: Optional database override (uses env var if not provided) Returns: The created relationship records """ if data is None: data = {} query = f"RELATE {source}->{relationship}->{target} CONTENT $data;" return await repo_query( query, {"data": data}, namespace=namespace, database=database, )

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