Skip to main content
Glama

consolidate_memories

Merge similar memories using AI to resolve conflicts and create consolidated notes. Supports dry-run preview or direct application modes for memory cluster management.

Instructions

Consolidate similar memories using LLM-driven merging (NOT YET IMPLEMENTED).

This tool will use an LLM to intelligently merge similar memories,
resolve conflicts, and create consolidated notes. Currently returns
a placeholder message.

Args:
    cluster_id: Cluster ID to consolidate.
    mode: Operation mode - "dry_run" or "apply".

Returns:
    Consolidation results (when implemented).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
cluster_idYes
modeNodry_run

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The main handler function for the 'consolidate_memories' tool, decorated with @mcp.tool() which handles both implementation and registration. Includes input validation, auto-detection clustering, preview, apply, and link modes for memory consolidation.
    @mcp.tool()
    def consolidate_memories(
        cluster_id: str | None = None,
        mode: str = "preview",
        auto_detect: bool = False,
        cohesion_threshold: float = 0.75,
    ) -> dict[str, Any]:
        """
        Consolidate similar memories using algorithmic merging or linking.
    
        This tool handles clusters in three ways:
        1. MERGE (mode="apply"): Combine memories into one (high cohesion ≥0.75)
        2. LINK (mode="link"): Create 'related' relations without merging (medium cohesion 0.40-0.75)
        3. PREVIEW (mode="preview"): Show what would happen without making changes
    
        Merging intelligently:
        - Combines content (preserving unique information)
        - Merges tags and entities (union)
        - Calculates appropriate strength based on cohesion
        - Preserves earliest created_at and latest last_used timestamps
    
        Linking creates bidirectional 'related' relations to form knowledge graph connections.
    
        Modes:
        - "preview": Generate merge preview without making changes
        - "apply": Execute the consolidation/merge (requires cluster_id or auto_detect)
        - "link": Create relations between cluster members without merging
    
        Args:
            cluster_id: Specific cluster ID to act on (valid UUID, required unless auto_detect=True).
            mode: Operation mode - "preview", "apply", or "link".
            auto_detect: If True, automatically find high-cohesion clusters.
            cohesion_threshold: Minimum cohesion for auto-detection (0.0-1.0, default: 0.75).
    
        Returns:
            Consolidation/linking preview or execution results.
    
        Raises:
            ValueError: If cluster_id is invalid or cohesion_threshold is out of range.
        """
        # Input validation
        if cluster_id is not None:
            cluster_id = validate_uuid(cluster_id, "cluster_id")
    
        cohesion_threshold = validate_score(cohesion_threshold, "cohesion_threshold")
    
        if mode not in ("preview", "apply", "link"):
            raise ValueError(f"mode must be 'preview', 'apply', or 'link', got: {mode}")
    
        # Auto-detect mode: find clusters worth consolidating
        if auto_detect:
            memories = db.list_memories(status=MemoryStatus.ACTIVE)
    
            # Create cluster config
            cluster_config = ClusterConfig(
                strategy="similarity",
                threshold=cohesion_threshold,
                max_cluster_size=12,
                min_cluster_size=2,
                use_embeddings=True,
            )
    
            clusters = cluster_memories_simple(memories, cluster_config)
    
            # Filter to high-cohesion clusters worth consolidating
            candidates = [c for c in clusters if c.cohesion >= cohesion_threshold]
    
            if mode == "preview":
                # Show top candidates
                previews = []
                for cluster in candidates[:5]:  # Top 5 candidates
                    preview = generate_consolidation_preview(cluster)
                    previews.append(preview)
    
                return {
                    "success": True,
                    "mode": "auto_detect_preview",
                    "candidates_found": len(candidates),
                    "showing": len(previews),
                    "previews": previews,
                    "message": f"Found {len(candidates)} clusters ready for consolidation",
                }
            elif mode == "apply":
                # Apply consolidation to all candidates
                results = []
                for cluster in candidates:
                    result = execute_consolidation(cluster, db, centroid_embedding=cluster.centroid)
                    results.append(result)
    
                total_saved = sum(r.get("space_saved", 0) for r in results)
    
                return {
                    "success": True,
                    "mode": "auto_detect_apply",
                    "consolidated_clusters": len(results),
                    "total_memories_saved": total_saved,
                    "results": results,
                    "message": f"Consolidated {len(results)} clusters, saved {total_saved} memory slots",
                }
            else:  # mode == "link"
                # Link all candidates without merging
                results = []
                for cluster in candidates:
                    result = link_cluster_memories(cluster, db)
                    results.append(result)
    
                total_relations = sum(r.get("relations_created", 0) for r in results)
    
                return {
                    "success": True,
                    "mode": "auto_detect_link",
                    "linked_clusters": len(results),
                    "total_relations_created": total_relations,
                    "results": results,
                    "message": f"Linked {len(results)} clusters with {total_relations} relations",
                }
    
        # Specific cluster mode
        if not cluster_id:
            return {
                "success": False,
                "error": "cluster_id is required when auto_detect is False",
                "hint": "Use auto_detect=True to find clusters automatically",
            }
    
        # Find the cluster (need to re-cluster to get the cluster object)
        memories = db.list_memories(status=MemoryStatus.ACTIVE)
        cluster_config = ClusterConfig(
            strategy="similarity",
            threshold=0.75,
            max_cluster_size=12,
            min_cluster_size=2,
            use_embeddings=True,
        )
    
        clusters = cluster_memories_simple(memories, cluster_config)
        target_cluster = next((c for c in clusters if c.id == cluster_id), None)
    
        if not target_cluster:
            return {
                "success": False,
                "error": f"Cluster {cluster_id} not found",
                "hint": "Cluster IDs change on each run. Use auto_detect or get fresh cluster IDs from cluster_memories tool",
            }
    
        if mode == "preview":
            preview = generate_consolidation_preview(target_cluster)
            return {
                "success": True,
                "mode": "preview",
                **preview,
            }
    
        elif mode == "apply":
            result = execute_consolidation(
                target_cluster, db, centroid_embedding=target_cluster.centroid
            )
            return {
                "success": True,
                "mode": "apply",
                **result,
            }
    
        elif mode == "link":
            result = link_cluster_memories(target_cluster, db)
            return {
                "success": True,
                "mode": "link",
                **result,
            }
    
        else:
            return {
                "success": False,
                "error": f"Unknown mode: {mode}",
                "valid_modes": ["preview", "apply", "link"],
            }
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: the tool is not yet implemented (returns placeholder), uses LLM-driven merging, and resolves conflicts. However, it doesn't cover important aspects like permissions needed, rate limits, or error handling, leaving gaps for a mutation tool.

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 and appropriately sized. It front-loads the purpose, includes implementation status, and lists parameters clearly. Every sentence adds value, though the placeholder note could be slightly more concise.

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

Completeness3/5

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

Given the tool has an output schema (returns are documented elsewhere) and 2 parameters with 0% schema coverage, the description is moderately complete. It covers purpose, status, and parameters but lacks details on behavioral aspects like permissions or error handling, which are important for a mutation tool with no annotations.

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?

Schema description coverage is 0%, so the description must compensate. It explains 'cluster_id' as 'Cluster ID to consolidate' and 'mode' with options 'dry_run' or 'apply,' adding meaningful context beyond the bare schema. However, it doesn't detail what a 'Cluster ID' represents or the implications of each mode, leaving some ambiguity.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/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: 'Consolidate similar memories using LLM-driven merging.' It specifies the verb (consolidate), resource (memories), and method (LLM-driven merging). However, it doesn't explicitly differentiate from sibling tools like 'cluster_memories' or 'promote_memory,' which prevents a perfect score.

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

Usage Guidelines2/5

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

The description provides minimal usage guidance. It mentions the tool is 'NOT YET IMPLEMENTED' and currently returns a placeholder, which is useful context. However, it lacks explicit guidance on when to use this tool versus alternatives like 'cluster_memories' or 'promote_memory,' and doesn't specify prerequisites or exclusions.

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/prefrontal-systems/mnemex'

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