Skip to main content
Glama

Graph Prune

graph_prune
Destructive

Remove entities and edges below decay thresholds, including orphaned nodes past max age. Preview before destructive execution.

Instructions

Remove entities and edges that have decayed below threshold. DESTRUCTIVE — always preview first. Requires user confirmation before execute mode.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
modeNopreview (default) or executepreview
node_thresholdNoPrune nodes below this confidence (default: 0.1)
edge_thresholdNoPrune edges below this weight (default: 0.05)
include_orphansNoAlso prune orphaned nodes (default: true)
max_age_daysNoMax age for orphan pruning (default: 30)

Implementation Reference

  • The `prune()` method on Neo4jClient that executes the actual graph pruning logic. It finds nodes below confidence threshold, orphan nodes past max age, and edges below weight threshold. In preview mode it returns what would be deleted; in execute mode it deletes edges then nodes.
    async prune(
      tenantId: string,
      mode: "preview" | "execute" = "preview",
      options: {
        node_threshold?: number;
        edge_threshold?: number;
        include_orphans?: boolean;
        max_age_days?: number;
      } = {},
    ): Promise<{
      mode: string;
      nodes_pruned: number;
      edges_pruned: number;
      details: Array<{ action: string; id?: string; type?: string; from?: string; to?: string }>;
    }> {
      const config = getConfig();
      const nodeThreshold = options.node_threshold ?? config.decay.prune_node_threshold;
      const edgeThreshold = options.edge_threshold ?? config.decay.prune_edge_threshold;
      const includeOrphans = options.include_orphans ?? true;
      const maxAgeDays = options.max_age_days ?? config.decay.prune_orphan_days;
    
      // Find pruneable nodes (tenant-scoped)
      const nodeRows = await this.run(
        `
        MATCH (n:Entity {tenant_id: $tenantId})
        WHERE n.confidence < $nodeThreshold
        OPTIONAL MATCH (n)-[r]-(other:Entity {tenant_id: $tenantId})
        WITH n, labels(n) AS labels, max(r.weight) AS maxEdge
        WHERE maxEdge IS NULL OR maxEdge < $edgeThreshold
        RETURN n.id AS id, n.name AS name,
               [l IN labels WHERE l <> 'Entity'][0] AS type,
               n.confidence AS confidence
        `,
        { tenantId, nodeThreshold, edgeThreshold },
      );
    
      // Find orphans if requested
      let orphanRows: Row[] = [];
      if (includeOrphans) {
        orphanRows = await this.run(
          `
          MATCH (n:Entity {tenant_id: $tenantId})
          WHERE NOT (n)-[]-()
            AND n.last_seen < datetime() - duration({days: $maxAgeDays})
            AND n.confidence >= $nodeThreshold
          RETURN n.id AS id, n.name AS name,
                 [l IN labels(n) WHERE l <> 'Entity'][0] AS type,
                 n.confidence AS confidence
          `,
          { tenantId, maxAgeDays, nodeThreshold },
        );
      }
    
      // Find pruneable edges (both endpoints in tenant)
      const edgeRows = await this.run(
        `
        MATCH (a:Entity {tenant_id: $tenantId})-[r]->(b:Entity {tenant_id: $tenantId})
        WHERE r.weight < $edgeThreshold
        RETURN a.id AS fromId, b.id AS toId, type(r) AS relType, r.weight AS weight
        `,
        { tenantId, edgeThreshold },
      );
    
      const allNodeRows = [...nodeRows, ...orphanRows];
    
      if (mode === "preview") {
        const details: Array<{ action: string; id?: string; type?: string; from?: string; to?: string }> = [];
        for (const row of allNodeRows) {
          details.push({ action: "would_delete_node", id: String(row["id"]), type: String(row["type"]) });
        }
        for (const row of edgeRows) {
          details.push({ action: "would_delete_edge", from: String(row["fromId"]), to: String(row["toId"]), type: String(row["relType"]) });
        }
        return { mode: "preview", nodes_pruned: allNodeRows.length, edges_pruned: edgeRows.length, details };
      }
    
      // Execute mode — actually delete (tenant-scoped)
      const details: Array<{ action: string; id?: string; type?: string; from?: string; to?: string }> = [];
    
      // Delete edges first
      const edgeDeleteRows = await this.run(
        `
        MATCH (a:Entity {tenant_id: $tenantId})-[r]->(b:Entity {tenant_id: $tenantId})
        WHERE r.weight < $edgeThreshold
        DELETE r
        RETURN count(r) AS deleted
        `,
        { tenantId, edgeThreshold },
      );
    
      // Delete nodes (tenant-scoped)
      const nodeIds = allNodeRows.map((r) => String(r["id"]));
      let nodesDeleted = 0;
      if (nodeIds.length > 0) {
        const nodeDeleteRows = await this.run(
          `
          MATCH (n:Entity {tenant_id: $tenantId})
          WHERE n.id IN $nodeIds
          DETACH DELETE n
          RETURN count(n) AS deleted
          `,
          { tenantId, nodeIds },
        );
        nodesDeleted = Number(nodeDeleteRows[0]?.["deleted"] ?? 0);
      }
    
      const edgesDeleted = Number(edgeDeleteRows[0]?.["deleted"] ?? 0);
    
      return { mode: "executed", nodes_pruned: nodesDeleted, edges_pruned: edgesDeleted, details };
    }
  • Input schema for the graph_prune tool: mode (preview/execute), node_threshold, edge_threshold, include_orphans, max_age_days.
      "Remove entities and edges that have decayed below threshold. DESTRUCTIVE — always preview first. Requires user confirmation before execute mode.",
    inputSchema: {
      mode: z.enum(["preview", "execute"]).optional().default("preview").describe("preview (default) or execute"),
      node_threshold: z.number().optional().default(0.1).describe("Prune nodes below this confidence (default: 0.1)"),
      edge_threshold: z.number().optional().default(0.05).describe("Prune edges below this weight (default: 0.05)"),
      include_orphans: z.boolean().optional().default(true).describe("Also prune orphaned nodes (default: true)"),
      max_age_days: z.number().optional().default(30).describe("Max age for orphan pruning (default: 30)"),
    },
  • Registration of the graph_prune tool on the MCP server, including its description and annotations (destructiveHint: true).
    // ─── Tool: graph_prune ───
    
    server.registerTool("graph_prune", {
      title: "Graph Prune",
      description:
        "Remove entities and edges that have decayed below threshold. DESTRUCTIVE — always preview first. Requires user confirmation before execute mode.",
      inputSchema: {
        mode: z.enum(["preview", "execute"]).optional().default("preview").describe("preview (default) or execute"),
        node_threshold: z.number().optional().default(0.1).describe("Prune nodes below this confidence (default: 0.1)"),
        edge_threshold: z.number().optional().default(0.05).describe("Prune edges below this weight (default: 0.05)"),
        include_orphans: z.boolean().optional().default(true).describe("Also prune orphaned nodes (default: true)"),
        max_age_days: z.number().optional().default(30).describe("Max age for orphan pruning (default: 30)"),
      },
      annotations: { destructiveHint: true },
    }, async (args) => {
      try {
        const result = await client.prune(currentTenant(), args.mode ?? "preview", {
          node_threshold: args.node_threshold,
          edge_threshold: args.edge_threshold,
          include_orphans: args.include_orphans,
          max_age_days: args.max_age_days,
        });
        return toolResult(result);
      } catch (err) {
        return toolError(`graph_prune failed: ${err instanceof Error ? err.message : String(err)}`);
      }
    });
  • Default config values for pruning: prune_node_threshold=0.1, prune_edge_threshold=0.05, prune_orphan_days=30.
    decay: {
      rates: {
        Person: 0.998,
        Project: 0.995,
        Preference: 0.999,
        Concept: 0.999,
        Decision: 0.997,
        Fact: 0.996,
        Event: 0.993,
        Object: 0.996,
      },
      edge_rate: 0.997,
      prune_node_threshold: 0.1,
      prune_edge_threshold: 0.05,
      prune_orphan_days: 30,
  • Handler for graph_prune tool: delegates to client.prune() with passed arguments and returns result.
    }, async (args) => {
      try {
        const result = await client.prune(currentTenant(), args.mode ?? "preview", {
          node_threshold: args.node_threshold,
          edge_threshold: args.edge_threshold,
          include_orphans: args.include_orphans,
          max_age_days: args.max_age_days,
        });
        return toolResult(result);
      } catch (err) {
        return toolError(`graph_prune failed: ${err instanceof Error ? err.message : String(err)}`);
      }
    });
Behavior4/5

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

Annotations include destructiveHint: true. The description adds behavioral context beyond the annotation: 'DESTRUCTIVE — always preview first. Requires user confirmation before execute mode.' This informs the agent of safe usage.

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?

Two sentences, no wasted words. First sentence states core action, second sentence adds critical warnings. Front-loaded and efficient.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given 5 parameters with full schema coverage and no output schema, the description adequately explains the tool's purpose and safety requirements. Could mention irreversibility beyond destructive hint, but still strong.

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

Parameters3/5

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

Input schema has 100% coverage with clear descriptions for each parameter. The description adds minimal extra meaning beyond summarizing the action. Baseline 3 is appropriate.

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 verb 'remove' and the resource 'entities and edges that have decayed below threshold'. It is specific and distinguishes from siblings like graph_delete and graph_decay.

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 guidance: 'always preview first' and 'Requires user confirmation before execute mode'. It warns about destructiveness but does not mention alternatives or when not to use.

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