Skip to main content
Glama

Graph Unmerge

graph_unmerge
Destructive

Correct entity resolution errors by splitting a falsely merged entity into two. Move specified edges to the new entity while logging the reason.

Instructions

Split a falsely merged entity back into two separate entities, redistributing specified edges. Use when entity resolution made a mistake (e.g. merged 'Anna' and 'Anne'). The original entity keeps every edge not listed in edges_to_move; the new entity gets the listed edges plus a fresh embedding stub (re-derive with graph_reembed). Logged to the audit trail with reason. Returns the IDs of both entities.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
entity_idYesThe merged entity ID to split
new_entity_nameYesName for the split-off entity
new_entity_typeYesType label for the split-off entity
edges_to_moveYesEdges to move to the new entity
reasonYesWhy splitting (logged in audit)

Implementation Reference

  • Registration of the 'graph_unmerge' tool with server.registerTool(...). Defines inputSchema, description, and annotations. Handler calls client.unmerge(...) then logs to audit file.
    // ─── Tool: graph_unmerge ───
    
    server.registerTool("graph_unmerge", {
      title: "Graph Unmerge",
      description:
        "Split a falsely merged entity back into two separate entities, redistributing specified edges. Use when entity resolution made a mistake (e.g. merged 'Anna' and 'Anne'). The original entity keeps every edge not listed in `edges_to_move`; the new entity gets the listed edges plus a fresh embedding stub (re-derive with graph_reembed). Logged to the audit trail with `reason`. Returns the IDs of both entities.",
      inputSchema: {
        entity_id: z.string().describe("The merged entity ID to split"),
        new_entity_name: z.string().describe("Name for the split-off entity"),
        new_entity_type: z.string().describe("Type label for the split-off entity"),
        edges_to_move: z.array(z.object({
          other_entity_id: z.string().describe("Entity on the other end of the edge"),
          relation_type: z.string().describe("Relationship type (e.g. WORKS_ON)"),
          direction: z.enum(["in", "out"]).describe("Direction relative to the entity being split"),
        })).describe("Edges to move to the new entity"),
        reason: z.string().describe("Why splitting (logged in audit)"),
      },
      annotations: { destructiveHint: true },
    }, async (args) => {
      try {
        const result = await client.unmerge(
          currentTenant(),
          args.entity_id,
          args.new_entity_name,
          args.new_entity_type as EntityType,
          args.edges_to_move.map((e) => ({
            ...e,
            relation_type: e.relation_type as RelationshipType,
          })),
          args.reason,
        );
    
        // Log to merge audit
        try {
          const auditDir = join(GRAPH_MEMORY_HOME, "logs");
          mkdirSync(auditDir, { recursive: true });
          const auditPath = join(auditDir, "merge-audit.jsonl");
          const entry = JSON.stringify({
            action: "unmerge",
            timestamp: new Date().toISOString(),
            ...result,
            reason: args.reason,
          });
          writeFileSync(auditPath, entry + "\n", { flag: "a" });
        } catch { /* audit logging is best-effort */ }
    
        return toolResult({ ...result, audit_logged: true });
      } catch (err) {
        return toolError(`graph_unmerge failed: ${err instanceof Error ? err.message : String(err)}`);
      }
    });
  • Handler function for graph_unmerge. Calls client.unmerge(...) with currentTenant(), entity_id, new_entity_name, new_entity_type, edges_to_move, and reason. Writes an audit entry to logs/merge-audit.jsonl on success.
    }, async (args) => {
      try {
        const result = await client.unmerge(
          currentTenant(),
          args.entity_id,
          args.new_entity_name,
          args.new_entity_type as EntityType,
          args.edges_to_move.map((e) => ({
            ...e,
            relation_type: e.relation_type as RelationshipType,
          })),
          args.reason,
        );
    
        // Log to merge audit
        try {
          const auditDir = join(GRAPH_MEMORY_HOME, "logs");
          mkdirSync(auditDir, { recursive: true });
          const auditPath = join(auditDir, "merge-audit.jsonl");
          const entry = JSON.stringify({
            action: "unmerge",
            timestamp: new Date().toISOString(),
            ...result,
            reason: args.reason,
          });
          writeFileSync(auditPath, entry + "\n", { flag: "a" });
        } catch { /* audit logging is best-effort */ }
    
        return toolResult({ ...result, audit_logged: true });
      } catch (err) {
        return toolError(`graph_unmerge failed: ${err instanceof Error ? err.message : String(err)}`);
      }
    });
  • Input schema for graph_unmerge: entity_id (string), new_entity_name (string), new_entity_type (string), edges_to_move (array of {other_entity_id, relation_type, direction: 'in'|'out'}), reason (string).
    inputSchema: {
      entity_id: z.string().describe("The merged entity ID to split"),
      new_entity_name: z.string().describe("Name for the split-off entity"),
      new_entity_type: z.string().describe("Type label for the split-off entity"),
      edges_to_move: z.array(z.object({
        other_entity_id: z.string().describe("Entity on the other end of the edge"),
        relation_type: z.string().describe("Relationship type (e.g. WORKS_ON)"),
        direction: z.enum(["in", "out"]).describe("Direction relative to the entity being split"),
      })).describe("Edges to move to the new entity"),
      reason: z.string().describe("Why splitting (logged in audit)"),
    },
  • Neo4jClient.unmerge() method: creates a new entity node in the same tenant, moves specified edges (outgoing and incoming) from original to new entity by re-creating then deleting the old ones, and returns the original entity's remaining edge count and the new entity's details.
    async unmerge(
      tenantId: string,
      entityId: string,
      newEntityName: string,
      newEntityType: EntityType,
      edgesToMove: Array<{ other_entity_id: string; relation_type: RelationshipType; direction: "in" | "out" }>,
      reason: string,
    ): Promise<{
      original: { id: string; remaining_edges: number };
      new_entity: { id: string; name: string; moved_edges: number };
    }> {
      const newId = newEntityName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
      const now = new Date().toISOString();
    
      // Create the new entity in the same tenant
      await this.run(
        `
        CREATE (n:Entity:\`${newEntityType}\` {
          tenant_id: $tenantId,
          id: $newId,
          name: $newEntityName,
          confidence: 0.5,
          times_mentioned: 1,
          first_seen: datetime($now),
          last_seen: datetime($now)
        })
        `,
        { tenantId, newId, newEntityName, now },
      );
    
      // Move specified edges (all participants must be in the same tenant)
      let movedCount = 0;
      for (const edge of edgesToMove) {
        if (edge.direction === "out") {
          const rows = await this.run(
            `
            MATCH (original:Entity {tenant_id: $tenantId, id: $entityId})-[r:\`${edge.relation_type}\`]->(other:Entity {tenant_id: $tenantId, id: $otherId})
            MATCH (newNode:Entity {tenant_id: $tenantId, id: $newId})
            WITH r, newNode, other, properties(r) AS props
            CREATE (newNode)-[newR:\`${edge.relation_type}\`]->(other)
            SET newR = props
            DELETE r
            RETURN count(newR) AS moved
            `,
            { tenantId, entityId, otherId: edge.other_entity_id, newId },
          );
          movedCount += Number(rows[0]?.["moved"] ?? 0);
        } else {
          const rows = await this.run(
            `
            MATCH (other:Entity {tenant_id: $tenantId, id: $otherId})-[r:\`${edge.relation_type}\`]->(original:Entity {tenant_id: $tenantId, id: $entityId})
            MATCH (newNode:Entity {tenant_id: $tenantId, id: $newId})
            WITH r, newNode, other, properties(r) AS props
            CREATE (other)-[newR:\`${edge.relation_type}\`]->(newNode)
            SET newR = props
            DELETE r
            RETURN count(newR) AS moved
            `,
            { tenantId, entityId, otherId: edge.other_entity_id, newId },
          );
          movedCount += Number(rows[0]?.["moved"] ?? 0);
        }
      }
    
      // Count remaining edges on original (tenant-scoped)
      const remainingRows = await this.run(
        `MATCH (n:Entity {tenant_id: $tenantId, id: $entityId})-[r]-() RETURN count(r) AS remaining`,
        { tenantId, entityId },
      );
      const remainingEdges = Number(remainingRows[0]?.["remaining"] ?? 0);
    
      return {
        original: { id: entityId, remaining_edges: remainingEdges },
        new_entity: { id: newId, name: newEntityName, moved_edges: movedCount },
      };
    }
Behavior4/5

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

Beyond the destructiveHint annotation, the description discloses that edges not in edges_to_move stay with the original entity, the new entity gets a fresh embedding stub requiring reembed, and the operation is logged to the audit trail with the reason. No contradictions with annotations.

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?

Four concise sentences, each adding value. Front-loaded with purpose, followed by usage, behavioral details, and return value. No redundant or unnecessary text.

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 has 5 required parameters, no output schema, and destructive behavior, the description covers essential aspects: when to use, what happens to edges and embeddings, audit logging, and return value (IDs). It is complete for agent selection and invocation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 100% schema description coverage, the description adds meaningful context: explains that the original entity keeps edges not in edges_to_move, and the new entity gets listed edges plus an embedding stub. This enhances understanding beyond the schema's field descriptions.

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: 'Split a falsely merged entity back into two separate entities, redistributing specified edges.' The verb 'split' and resource 'falsely merged entity' are specific, and it distinguishes itself from sibling graph_merge.

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?

Provides explicit when-to-use guidance: 'Use when entity resolution made a mistake (e.g. merged 'Anna' and 'Anne').' While it doesn't explicitly state when not to use or mention alternatives, the context is clear enough.

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/stevepridemore/graph-memory'

If you have feedback or need assistance with the MCP directory API, please join our Discord server