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

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
from_thingYes
relation_nameYes
to_thingYes
dataNo
namespaceNo
databaseNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Handler for the 'relate' MCP tool. Validates parameters, resolves DB context, invokes repo_relate helper, and returns structured response including the created relation.
    @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)}")
  • FastMCP decorator registering the 'relate' function as a tool.
    @mcp.tool()
  • Core helper implementing the RELATE query execution via repo_query for creating graph relationships in SurrealDB.
    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,
        )
  • Input/output schema defined via function signature type hints and comprehensive docstring with Args, Returns, and Examples.
    """
    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
    """
Behavior4/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively describes that this creates relationships, stores data on relationships, enables future graph queries, and models many-to-many relationships. It also explains the return structure and includes error handling information. The main gap is lack of information about permissions, rate limits, or idempotency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections (purpose, bullet points, args, returns, examples, note). While comprehensive, it's appropriately sized for a complex tool with 6 parameters. The front-loaded purpose statement is excellent, though some redundancy exists between the bullet points and later content.

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 tool's complexity (6 parameters, graph operations), no annotations, and an output schema that only defines structure without semantics, the description provides excellent completeness. It covers purpose, parameters with examples, return values with examples, and even includes query syntax for future use. The combination of structured sections and practical examples makes it highly complete.

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 explanations. Each parameter is clearly defined with format examples (e.g., 'table:id'), the optional nature of 'data', 'namespace', and 'database' is explained, and concrete examples show how parameters work together. This adds significant value beyond the bare schema.

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 specific action ('Create a graph relation'), identifies the resource ('between two records in SurrealDB'), and distinguishes from siblings like create/insert/update by focusing on graph relationships rather than general record operations. The bullet points further clarify the purpose and benefits.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context for when to use this tool ('Create a graph relation between two records'), and the examples demonstrate typical use cases. However, it doesn't explicitly state when NOT to use it or mention alternatives among the sibling tools for similar operations.

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