MegaMemory

repository·main·Indexed 41 days ago

https://github.com/0xk3vin/megamemory

An MCP server that provides coding agents with persistent project understanding via a SQLite-backed knowledge graph. It enables LLMs to record and query high-level concepts, architecture, and design decisions across sessions using tools like `understand`, `create_concept`, and `link`. Version 1.6.2 includes a CLI for installation, a web-based graph explorer, and a dedicated merge engine to handle diverging knowledge databases.

Tokens
13K
Snippets
47
Records
62
Agent score
59%

What's inside MegaMemory

  1. Guidelines for Recording Knowledge

    main

    When saving knowledge to the graph, follow these best practices to maintain a high-quality, useful memory:

    • Prioritize Rationale: Intent and the "why" are more valuable than implementation details.
    • Avoid Duplication: Update existing concepts before creating new ones to keep the graph lean.
    • Be Specific: Avoid vague summaries. Instead of "Handles auth", use "JWT auth with RS256, validated in middleware at src/middleware/auth.ts, refresh tokens in Redis with 7d TTL".
    • Structure: Aim for a maximum of 2 levels of nesting; flat structures are preferred over deep hierarchies.
    • Connectivity: Connect concepts using edges; isolated nodes provide less value than a connected graph.
    • Filter Triviality: Do not record obvious implementation details that are clearly visible in the code.
  2. How the MegaMemory loop works

    main

    MegaMemory operates on a continuous loop of understand → work → update to maintain a persistent knowledge graph of concepts (features, modules, patterns, decisions) rather than just code symbols.

    1. Understand: At the start of a session or before a task, the agent calls list_roots to orient itself or understand (semantic search) / get_concept (exact ID lookup) to retrieve context.
    2. Work: The agent performs the requested coding task.
    3. Update: After the task, the agent calls create_concept or update_concept to record the new knowledge or changes into the SQLite database located at .megamemory/knowledge.db.
  3. Bootstrap a Project Knowledge Graph

    main

    To build a structured knowledge graph for a new project using MegaMemory, follow a systematic process of discovery, concept creation, and linking. This process helps transform raw code and documentation into a navigable graph of architectural patterns, modules, and behaviors.

    Workflow

    1. Audit existing knowledge: Use megamemory:list_roots to check what is already recorded to avoid duplication.
    2. Identify modules: Analyze the file structure (specifically large files) and the README.md to identify top-level systems, features, and subsystems.
    3. Create root concepts: For each major module, use megamemory:create_concept to record a detailed summary. Avoid vague descriptions; include specific parameter names, defaults, file paths, and exact behaviors.
    4. Define sub-components: Create child concepts for key pieces within substantial modules. It is recommended to stay a maximum of 2 levels deep to maintain clarity.
    5. Establish relationships: Use megamemory:link to connect concepts that interact across boundaries. Use meaningful relationship types such as depends_on, calls, connects_to, implements, or configured_by.

    Documentation Guidelines

    • Specificity is critical: Instead of "Handles auth", use "JWT auth with RS256, tokens from /auth/login, validated in middleware, refresh tokens in Redis with 7d TTL".
    • Prioritize importance: Focus on the top 10-15 most important concepts first rather than attempting to document everything at once.
    • Avoid triviality: Do not document things that are obvious from file names alone.
  4. Merge Knowledge Graphs

    main

    Since .megamemory/knowledge.db is a SQLite file, it cannot be merged by Git. MegaMemory provides a dedicated merge engine to handle diverging branches.

    Merging Databases

    Use megamemory merge to combine two databases. Concepts are compared by ID. Identical nodes are deduplicated; conflicting nodes are kept as ::left and ::right variants.

    megamemory merge main.db feature.db --into merged.db
    
    # Using custom labels for branches
    megamemory merge main.db feature.db --into merged.db --left-label main --right-label feature-xyz

    Viewing and Resolving Conflicts

    List conflicts:

    • megamemory conflicts (human-readable summary)
    • megamemory conflicts --json (machine-readable)
    • megamemory conflicts --db <path> (specify database)

    Manual resolution: Resolve a conflict by providing a <merge-group-uuid> and choosing which side to keep:

    megamemory resolve <merge-group-uuid> --keep left
    megamemory resolve <merge-group-uuid> --keep right
    megamemory resolve <merge-group-uuid> --keep both

    AI-assisted resolution: Agents can call list_conflicts and then resolve_conflict to resolve issues based on the current state of the codebase.

    megamemory merge main.db feature.db --into merged.db --left-label main --right-label feature-xyz
    
    megamemory resolve <merge-group-uuid> --keep left
  5. Visualize the Knowledge Graph with Web Explorer

    main

    You can launch a web-based visualizer to inspect your knowledge graph. Nodes are colored by kind and sized by edge count. Dashed edges represent parent-child links, while solid edges represent relationships.

    Use the --port flag to specify a custom port if the default 4321 is occupied.

    megamemory serve
    
    # Custom port
    megamemory serve --port 8080
  6. Configure MegaMemory for specific coding agents

    main

    MegaMemory provides specialized installation targets to automatically configure MCP servers, workflow instructions, and plugins for popular coding environments:

    • opencode: megamemory install --target opencode (Configures MCP, AGENTS.md, skill tools, and bootstrap/save commands).
    • Claude Code: megamemory install --target claudecode (Configures MCP in ~/.claude.json, CLAUDE.md, and commands).
    • Antigravity: megamemory install --target antigravity (Configures workspace-level mcp_config.json).
    • Codex: megamemory install --target codex (Configures MCP in ~/.codex/config.toml and AGENTS.md).

    Manual MCP Configuration: If using a different MCP client, add megamemory as a stdio MCP server. The command is simply megamemory. It uses .megamemory/knowledge.db relative to the working directory unless MEGAMEMORY_DB_PATH is set.

    {
      "megamemory": {
        "type": "local",
        "command": ["megamemory"],
        "enabled": true
      }
    }
  7. Save Session Knowledge to the Knowledge Graph

    main

    To preserve learnings from a session into the megamemory knowledge graph, follow a structured workflow of loading, reflecting, searching, writing, and verifying. This process ensures that design decisions, architectural patterns, and project intents are recorded for future sessions.

    Workflow

    1. Load existing graph: Call megamemory:list_roots to understand the current state and prevent duplicates.
    2. Reflect: Identify new learnings, design decisions, patterns, or architectural changes.
    3. Search for overlap: Use megamemory:understand with relevant queries (e.g., megamemory:understand --query="authentication") to see if existing concepts should be updated instead of duplicated.
    4. Write to the graph: Use the appropriate MCP tool to create, update, link, or remove concepts (see MCP Tool Reference).
    5. Verify: Call megamemory:list_roots again to confirm the changes were applied correctly.
  8. Install MegaMemory

    main

    Install the MegaMemory CLI globally using npm. This requires Node.js >= 18. Note that an embedding model (~23MB) will be downloaded automatically on the first use.

    To set up integration with your specific coding agent or editor, use the install command with the --target flag.

    npm install -g megamemory
    
    # Run the interactive installer
    megamemory install
    
    # Or install for a specific target
    megamemory install --target opencode
  9. Project Knowledge Graph instructions for agents

    main

    When megamemory is installed, the following instructions are appended to agent configuration files (like CLAUDE.md or AGENTS.md) to guide the agent's workflow:

    Project Knowledge Graph

    You have access to a project knowledge graph via the megamemory MCP server and skill tool. You have no implicit memory of this project between sessions, so this graph is your only continuity for concepts, architecture, decisions, and relationships.

    Workflow: understand → work → update

    1. Session start: You must call megamemory with action overview (or megamemory:list_roots directly) before you begin work.
    2. Before each task: You must call megamemory with action query (or megamemory:understand directly) before reading source files for project understanding.
    3. After each task: You must call megamemory with action record to create/update/link concepts for what you built.

    Be specific in summaries: include parameter names, defaults, file locations, and rationale. Keep concepts max 3 levels deep.

  10. Handle knowledge graph merge conflicts

    main

    When merging knowledge from different branches, conflicts may arise.

    • ConflictGroup: A collection of ConflictVersion objects that share the same merge_group identifier.
    • ConflictVersion: Represents a specific version of a node (including its name, kind, summary, and edges) that exists within a merge group.
    • ResolveConflictInput: Used to resolve a conflict by providing the merge_group ID, the final resolved state (summary, why, file_refs), and a reason for the resolution.
    // Example resolution input
    const resolution: ResolveConflictInput = {
      merge_group: "group_abc_123",
      resolved: {
        summary: "The unified summary after merging branches.",
        why: "Merged to reflect combined logic."
      },
      reason: "Manual resolution of conflicting feature descriptions"
    };
  11. Handle and resolve merge conflicts

    main

    When merging knowledge graphs, conflicts may arise where multiple versions of the same concept exist.

    1. Identify Conflicts: Use listConflicts(db) to get a list of ConflictGroups. Each group contains multiple versions of a concept identified by a merge_group.
    2. Resolve Conflicts: Use resolveConflict(db, input) to pick a winner. You provide the merge_group and the resolved content (summary, why, file_refs). The function will keep the base node, apply the new content, rename it back to its original clean ID, and delete the conflicting copies.
    // 1. List conflicts
    const { conflicts } = listConflicts(db);
    
    // 2. Resolve a specific group
    await resolveConflict(db, {
      merge_group: "some-merge-id",
      reason: "Manual resolution of conflicting summaries",
      resolved: {
        summary: "The definitive summary of this concept.",
        why: "Resolved via manual review.",
        file_refs: ["src/main.ts"]
      }
    });
  12. Configure megamemory for Claude Code

    main

    Installing for claudecode performs the following steps:

    1. MCP server config: Updates ~/.claude.json to include the megamemory MCP server using the stdio type.
    2. Global CLAUDE.md: Appends the Project Knowledge Graph instructions to ~/.claude/CLAUDE.md.
    3. Commands: Installs bootstrap-memory.md and save-memory.md into the Claude commands directory.

    Note: You must restart Claude Code after installation to reload the configuration and commands.

    megamemory install --target claudecode