Skip to content
Conduit

mcp server

allan-mcp-memory-code

🧠 Knowledge Graph Memory for AI Coding Agents & Openclaw - Full offline mode with Docker. Integrates with Claude, Cline, Cursor, Windsurf, and more. Auto-extracts entities & relationships. No API key

never00miss/allan-mcp-memory-codecommunitylistedunreviewednot running here yet

Set up

Runs on your computer. Pick your agent and operating system.

Before you start

  • Node.js 20 or newer
~/Library/Application Support/Claude/claude_desktop_config.json
{
  "mcpServers": {
    "allan-mcp-memory-code": {
      "command": "npx",
      "args": [
        "-y",
        "allan-mcp-memory-code"
      ]
    }
  }
}

same format Cursor, GitHub Copilot CLI, Junie, JetBrains AI Assistant, Augment (Auggie CLI), Factory Droid, Kiro, Devin CLI +12

Values in angle brackets are placeholders. Restart Claude Desktop after editing its config.Claude Desktop docs

README

synced Oct 14, 2026

Allan MCP Memory Code

🧠 Persistent knowledge graph memory for AI coding assistants (Claude, Cline, Cursor, Windsurf). Runs 100% offline with Docker. Auto-extracts entities & relationships from conversations.

Features

  • Full Offline Mode - No API keys required, runs entirely on local hardware
  • Cloud Mode - Use OpenRouter/OpenAI for low-resource machines (~$0.50/month)
  • Auto-extract entities + relationships from text
  • Hybrid search (text + vector) for nodes and facts
  • All-in-one Docker setup (FalkorDB + Ollama + LLM + Embedding)
  • Integrates with Claude, Cline, Kilo Code, Cursor, Windsurf, and more

Quick Start (Offline)

No API keys required! Everything runs locally.

# Clone the repository
git clone https://github.com/never00miss/allan-mcp-memory-code.git
cd allan-mcp-memory-code

# Start all services (FalkorDB + Ollama + Models)
docker compose up -d

# First run downloads ~5GB of models (5-15 min depending on internet)
# Wait until models are ready:
docker compose logs ollama-init -f

# When you see "All models ready!", the service is available at:
# http://localhost:19089

That's it! Now integrate with your AI coding assistant below.


Quick Start (Cloud - OpenRouter)

Lightweight setup! Only FalkorDB runs locally, LLM/Embedding via cloud.

# Clone the repository
git clone https://github.com/never00miss/allan-mcp-memory-code.git
cd allan-mcp-memory-code

# Start only FalkorDB (graph database)
docker compose up falkordb -d

# Configure cloud API
cp .env.example .env

Edit .env for OpenRouter:

# LLM (OpenRouter)
LLM_API_URL=https://openrouter.ai/api/v1
LLM_API_KEY=sk-or-v1-your-key-here
LLM_MODEL=qwen/qwen-2.5-7b-instruct

# Embedding (OpenRouter or local Ollama)
EMBEDDER_API_URL=https://openrouter.ai/api/v1
EMBEDDER_API_KEY=sk-or-v1-your-key-here
EMBEDDER_MODEL=openai/text-embedding-3-small

# FalkorDB
FALKORDB_URI=redis://localhost:6380
# Install and run
npm install
npm start

# Health check
curl http://localhost:19089/v1/health

OpenRouter Cost Estimate (1 Hour Coding Session)

ActivityRequestsTokens/ReqTotal TokensCost
Entity extraction~20~500~10,000~$0.002
Embedding generation~50~100~5,000~$0.0001
Search queries~30~200~6,000~$0.001
Total per hour~100-~21,000~$0.003

Monthly estimate (8hr/day, 20 days): ~$0.50

πŸ’‘ Tip: Use qwen/qwen-2.5-7b-instruct ($0.00018/1K tokens) - extremely cheap and reliable for entity extraction.

Recommended Cloud Models

ProviderModelCost/1K tokensNotes
OpenRouterqwen/qwen-2.5-7b-instruct$0.00018Best value
OpenRoutergoogle/gemma-3-4b-it$0.00010Cheapest
OpenRouteropenai/gpt-4o-mini$0.00015High quality
OpenAIgpt-4o-mini$0.00015Direct API

Integration

Claude Code (MCP Server) ⭐ Recommended

Use MCP tools directly in Claude Code - shows up in /mcp command.

Important: Always use claude mcp add to configure the MCP server. Do NOT manually edit ~/.claude/settings.json or ~/.claude/mcp.json for MCP config. Claude Code reads MCP settings from ~/.claude.json (managed by the CLI), not from those files. Editing the wrong file will cause "Connection closed" errors.


Step 1: Prerequisites

# Start FalkorDB
docker compose up falkordb -d

# Install & build allan-memory
cd allan-mcp-memory-code
npm install
npm run build
npm link

Step 2: Setup Claude Code Config

Copy the ready-made config files from extensions/:

# Copy hooks + CLAUDE.md
cp -r extensions/.claude ~/.claude
chmod +x ~/.claude/hooks/observe-read.sh ~/.claude/hooks/observe-edit.sh

Then edit the hook scripts β€” replace the placeholder env vars with your actual values:

Cloud (OpenRouter)Local (Ollama)
LLM_API_URL=https://openrouter.ai/api/v1LLM_API_URL=http://localhost:11435/v1
LLM_API_KEY=sk-or-v1-your-key-hereLLM_API_KEY=ollama
LLM_MODEL=qwen/qwen-2.5-7b-instructLLM_MODEL=qwen2.5:7b-instruct
EMBEDDER_API_URL=https://openrouter.ai/api/v1EMBEDDER_API_URL=http://localhost:11435/v1
EMBEDDER_API_KEY=sk-or-v1-your-key-hereEMBEDDER_API_KEY=ollama
EMBEDDER_MODEL=openai/text-embedding-3-smallEMBEDDER_MODEL=nomic-embed-text

Add the hooks section to ~/.claude/settings.json:

{
  "hooks": {
    "UserPromptSubmit": [
      {
        "description": "Inject project-specific context",
        "hooks": [
          {
            "type": "command",
            "command": "echo 'see allan-memory too and always do remember save'"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Read",
        "hooks": [
          {
            "type": "command",
            "command": "/Users/YOUR_USER/.claude/hooks/observe-read.sh",
            "timeout": 30
          }
        ]
      },
      {
        "matcher": "Edit|Write|MultiEdit",
        "hooks": [
          {
            "type": "command",
            "command": "/Users/YOUR_USER/.claude/hooks/observe-edit.sh",
            "timeout": 60
          }
        ]
      }
    ]
  }
}

Replace /Users/YOUR_USER with your actual home directory path.

The UserPromptSubmit hook prepends a short reminder to every prompt so the assistant keeps using recall / remember instead of falling back to raw file search. It runs locally β€” no network calls, no secrets.

Step 3: Add MCP Server

Local (Ollama):

claude mcp add allan-memory \
  -e FALKORDB_URI=redis://localhost:6380 \
  -e LLM_API_URL=http://localhost:11435/v1 \
  -e LLM_API_KEY=ollama \
  -e LLM_MODEL=qwen2.5:7b-instruct \
  -e EMBEDDER_API_URL=http://localhost:11435/v1 \
  -e EMBEDDER_API_KEY=ollama \
  -e EMBEDDER_MODEL=nomic-embed-text \
  -- node /full/path/to/allan-mcp-memory-code/dist/mcp-server.js

Cloud (OpenRouter):

claude mcp add allan-memory \
  -e FALKORDB_URI=redis://localhost:6380 \
  -e FALKORDB_GRAPH_NAME=allan_memory \
  -e LLM_API_URL=https://openrouter.ai/api/v1 \
  -e LLM_API_KEY=sk-or-v1-your-key-here \
  -e LLM_MODEL=qwen/qwen-2.5-7b-instruct \
  -e EMBEDDER_API_URL=https://openrouter.ai/api/v1 \
  -e EMBEDDER_API_KEY=sk-or-v1-your-key-here \
  -e EMBEDDER_MODEL=openai/text-embedding-3-small \
  -- node /full/path/to/allan-mcp-memory-code/dist/mcp-server.js

Hybrid (Local LLM + Cloud Embedding):

claude mcp add allan-memory \
  -e FALKORDB_URI=redis://localhost:6380 \
  -e LLM_API_URL=http://localhost:11435/v1 \
  -e LLM_API_KEY=ollama \
  -e LLM_MODEL=qwen2.5:7b-instruct \
  -e EMBEDDER_API_URL=https://openrouter.ai/api/v1 \
  -e EMBEDDER_API_KEY=sk-or-v1-your-key-here \
  -e EMBEDDER_MODEL=openai/text-embedding-3-small \
  -- node /full/path/to/allan-mcp-memory-code/dist/mcp-server.js

Replace /full/path/to/allan-mcp-memory-code with your actual path. The path must point to dist/mcp-server.js, not lib/mcp-server.js.

Remove MCP:

claude mcp remove allan-memory

Step 4: Verify

  1. Restart VS Code completely (Cmd+Q, not just reload window)
  2. Type /mcp in Claude Code chat
  3. You should see allan-memory with 6 tools

Troubleshooting:

IssueSolution
"Connection closed" errorYou likely edited ~/.claude/settings.json manually. Run claude mcp remove allan-memory then re-add with claude mcp add
"SyntaxError: Cannot use import"Path points to lib/ instead of dist/. Use dist/mcp-server.js
MCP shows but tools don't workFalkorDB not running. Start it: docker compose up falkordb -d
MCP not showing in /mcpRun claude mcp list to verify it's registered

Available MCP Tools

ToolDescription
register_projectRegister project root for path resolution and freshness
rememberStore a memory with structured fields (type, scope, content)
recallSearch stored memory; returns compact text lines with staleness inline
relateFind relationships between entities
listEnumerate stored entities by type
refreshRe-extract entities from a file (use when recall marks a hit STALE)

recall returns text, not JSON β€” one block per hit:

2 hits Β· my-app

func  AuthService.login  src/services/auth.js:45-89  3h
  login(email, pass) β†’ User|null | validates creds, calls hashPass()

file  src/config.js  2d  STALE β†’ refresh({file_path:"src/config.js"})
  purpose: env config loader | exports: loadConfig()

Each block is type scope [file[:lines]] age [marker] with the summary indented below. The bare duration is how long ago the memory was written. No marker means fresh. STALE β†’ prints the exact refresh() call that clears it; GONE means the source file no longer exists. Memories with no source_file are never marked stale β€” they have nothing to go stale against.

Unscoped queries that span projects are split under ── project-name ── headings, so every hit carries the project it belongs to.

add_memory, search_nodes, and search_facts are gone. They were unadvertised since v2, and add_memory's episode extraction shredded single facts into one note per identifier (one per npm dependency, one per exported name), which is what filled stores with entries like react-router-dom β€” "A library for client-side routing in React applications."

Use remember β€” it writes exactly one entity β€” and recall / relate to read.


Claude Code (HTTP/curl Alternative)

If MCP doesn't work, use HTTP API with curl commands.

Step 1: Allow curl Commands

Add to ~/.claude/settings.json:

{
  "permissions": {
    "allow": [
      "Bash(curl*)",
      "Bash(curl -s*)",
      "Bash(curl -X POST http://localhost:19089*)",
      "Bash(curl http://localhost:19089*)"
    ],
    "deny": []
  }
}

Step 2: Add Instructions to CLAUDE.md

Copy the ready-made instructions from extensions/.claude/CLAUDE.md to ~/.claude/CLAUDE.md:

cp extensions/.claude/CLAUDE.md ~/.claude/CLAUDE.md

If you have an existing ~/.claude/CLAUDE.md, append the content manually.

Step 3: Restart Claude Code

After editing settings, restart Claude Code completely for changes to take effect.


Prompt Tips for Auto-Triggering

To make Claude use memory tools automatically, use these phrases:

Phrase in PromptTriggers
"Check your memory first..."recall before answering
"What do you remember about...?"recall
"Remember this for later..."remember
"Search your knowledge of..."recall
"What patterns have you seen in...?"relate
"Store this insight..."remember
"Before answering, check if..."recall

Example Prompts:

"Check your memory first, then explain the authentication flow"

"What do you remember about the database schema?"

"Remember this: the API uses JWT tokens with 24h expiry"

"Search your knowledge of error handling patterns in this codebase"

Troubleshooting

IssueSolution
MCP not showing in /mcpVerify path is absolute, restart VS Code
Popup for curl commandsAdd "Bash(curl*)" to permissions.allow
Server errorsEnsure Docker is running: docker compose ps

OpenClaw

Allan Memory integrates with OpenClaw as a skill.

Option 1: Install Skill from GitHub

openclaw skills install git:never00miss/allan-mcp-memory-code@main --as allan-memory

Option 2: Copy Skill Locally

Copy the openclaw-skill/SKILL.md file to your OpenClaw skills directory:

mkdir -p ~/.openclaw/skills/allan-memory
cp openclaw-skill/SKILL.md ~/.openclaw/skills/allan-memory/SKILL.md

Configure MCP Server

Add to ~/.openclaw/openclaw.json:

{
  "skills": {
    "entries": {
      "allan-memory": {
        "enabled": true,
        "env": {
          "FALKORDB_URI": "redis://localhost:6380"
        }
      }
    }
  },
  "mcpServers": {
    "allan-memory": {
      "command": "node",
      "args": ["/path/to/allan-mcp-memory-code/dist/mcp-server.js"],
      "env": {
        "FALKORDB_URI": "redis://localhost:6380",
        "LLM_API_URL": "https://openrouter.ai/api/v1",
        "LLM_API_KEY": "your-openrouter-key",
        "LLM_MODEL": "qwen/qwen-2.5-7b-instruct",
        "EMBEDDING_API_URL": "https://openrouter.ai/api/v1",
        "EMBEDDING_API_KEY": "your-openrouter-key",
        "EMBEDDING_MODEL": "openai/text-embedding-3-small"
      }
    }
  }
}

Available Tools in OpenClaw

Once configured, you can use these tools in OpenClaw:

  • add_memory - Store knowledge (files, functions, patterns)
  • search_nodes - Find entities by semantic search
  • search_facts - Find relationships between entities
  • check_freshness - Verify stored knowledge isn't stale
  • regenerate_file - Update knowledge after file edits
  • get_episodes - List recent memory entries
  • delete_episode - Remove stale entries

See openclaw-skill/SKILL.md for detailed usage instructions.


Cline (VS Code)

Step 1: Add MCP Server

Add to Cline MCP settings (cline_mcp_settings.json):

Local (Ollama):

{
  "mcpServers": {
    "allan-memory": {
      "command": "node",
      "args": ["/path/to/allan-mcp-memory-code/dist/mcp-server.js"],
      "env": {
        "FALKORDB_URI": "redis://localhost:6380",
        "LLM_API_URL": "http://localhost:11435/v1",
        "LLM_API_KEY": "ollama",
        "LLM_MODEL": "qwen2.5:7b-instruct",
        "EMBEDDER_API_URL": "http://localhost:11435/v1",
        "EMBEDDER_API_KEY": "ollama",
        "EMBEDDER_MODEL": "nomic-embed-text"
      }
    }
  }
}

Cloud (OpenRouter):

{
  "mcpServers": {
    "allan-memory": {
      "command": "node",
      "args": ["/path/to/allan-mcp-memory-code/dist/mcp-server.js"],
      "env": {
        "FALKORDB_URI": "redis://localhost:6380",
        "LLM_API_URL": "https://openrouter.ai/api/v1",
        "LLM_API_KEY": "sk-or-v1-your-key-here",
        "LLM_MODEL": "qwen/qwen-2.5-7b-instruct",
        "EMBEDDER_API_URL": "https://openrouter.ai/api/v1",
        "EMBEDDER_API_KEY": "sk-or-v1-your-key-here",
        "EMBEDDER_MODEL": "openai/text-embedding-3-small"
      }
    }
  }
}

Step 2: Add Custom Instructions

Go to Cline Settings β†’ Custom Instructions and add the content from extensions/.claude/CLAUDE.md.

Or copy it directly:

cat extensions/.claude/CLAUDE.md

Kilo Code

Step 1: Add MCP Server

Add to Kilo Code MCP settings:

Local (Ollama):

{
  "servers": {
    "allan-memory": {
      "type": "stdio",
      "command": "node",
      "args": ["/path/to/allan-mcp-memory-code/dist/mcp-server.js"],
      "env": {
        "FALKORDB_URI": "redis://localhost:6380",
        "LLM_API_URL": "http://localhost:11435/v1",
        "LLM_API_KEY": "ollama",
        "LLM_MODEL": "qwen2.5:7b-instruct",
        "EMBEDDER_API_URL": "http://localhost:11435/v1",
        "EMBEDDER_API_KEY": "ollama",
        "EMBEDDER_MODEL": "nomic-embed-text"
      }
    }
  }
}

Cloud (OpenRouter):

{
  "servers": {
    "allan-memory": {
      "type": "stdio",
      "command": "node",
      "args": ["/path/to/allan-mcp-memory-code/dist/mcp-server.js"],
      "env": {
        "FALKORDB_URI": "redis://localhost:6380",
        "LLM_API_URL": "https://openrouter.ai/api/v1",
        "LLM_API_KEY": "sk-or-v1-your-key-here",
        "LLM_MODEL": "qwen/qwen-2.5-7b-instruct",
        "EMBEDDER_API_URL": "https://openrouter.ai/api/v1",
        "EMBEDDER_API_KEY": "sk-or-v1-your-key-here",
        "EMBEDDER_MODEL": "openai/text-embedding-3-small"
      }
    }
  }
}

Step 2: Add Custom Instructions

Go to Kilo Code Settings β†’ Custom Instructions and add the content from extensions/.claude/CLAUDE.md.

Or copy it directly:

cat extensions/.claude/CLAUDE.md

Windsurf (Codeium)

Step 1: Add MCP Server

Add to Windsurf MCP settings (~/.codeium/windsurf/mcp_config.json):

Local (Ollama):

{
  "mcpServers": {
    "allan-memory": {
      "command": "node",
      "args": ["/path/to/allan-mcp-memory-code/dist/mcp-server.js"],
      "env": {
        "FALKORDB_URI": "redis://localhost:6380",
        "LLM_API_URL": "http://localhost:11435/v1",
        "LLM_API_KEY": "ollama",
        "LLM_MODEL": "qwen2.5:7b-instruct",
        "EMBEDDER_API_URL": "http://localhost:11435/v1",
        "EMBEDDER_API_KEY": "ollama",
        "EMBEDDER_MODEL": "nomic-embed-text"
      }
    }
  }
}

Cloud (OpenRouter):

{
  "mcpServers": {
    "allan-memory": {
      "command": "node",
      "args": ["/path/to/allan-mcp-memory-code/dist/mcp-server.js"],
      "env": {
        "FALKORDB_URI": "redis://localhost:6380",
        "LLM_API_URL": "https://openrouter.ai/api/v1",
        "LLM_API_KEY": "sk-or-v1-your-key-here",
        "LLM_MODEL": "qwen/qwen-2.5-7b-instruct",
        "EMBEDDER_API_URL": "https://openrouter.ai/api/v1",
        "EMBEDDER_API_KEY": "sk-or-v1-your-key-here",
        "EMBEDDER_MODEL": "openai/text-embedding-3-small"
      }
    }
  }
}

Step 2: Add Global AI Rules

Go to Windsurf Settings β†’ AI Rules β†’ Global AI Rules and add the content from extensions/.claude/CLAUDE.md.

Or copy it directly:

cat extensions/.claude/CLAUDE.md

Cursor

Create .cursorrules in your project root with the content from extensions/.claude/CLAUDE.md.

Or copy it directly:

cp extensions/.claude/CLAUDE.md .cursorrules

Continue.dev

Step 1: Add Context Provider

Add to ~/.continue/config.json:

{
  "contextProviders": [
    {
      "name": "http",
      "params": {
        "url": "http://localhost:19089/v1/memory/search/nodes",
        "method": "POST",
        "headers": { "Content-Type": "application/json" },
        "body": { "query": "{{{ input }}}", "limit": 5 },
        "title": "Allan Memory"
      }
    }
  ]
}

Step 2: Add System Message

Add to ~/.continue/config.json under models[].systemMessage:

Use the system instructions from extensions/.claude/CLAUDE.md, adapting the tool commands to use the HTTP API (curl) instead of MCP tools.


GitHub Copilot

Create .github/copilot-instructions.md using the instructions from extensions/.claude/CLAUDE.md, adapting the tool commands to use the HTTP API (curl) instead of MCP tools.


Generic HTTP API

ActionMethodEndpointBody
StorePOST/v1/memory{"name":"...","episode_body":"...","group_id":"..."}
Search EntitiesPOST/v1/memory/search/nodes{"query":"...","limit":10}
Search RelationsPOST/v1/memory/search/facts{"query":"...","limit":10}
List EpisodesGET/v1/memory/episodes?group_id=...-
Health CheckGET/v1/health-

Exposed Ports

PortService
19089Allan Memory API
6380FalkorDB (Redis protocol)
3001FalkorDB Web UI
11435Ollama API

Hardware Requirements

Minimum

ComponentRequirement
RAM16GB
Storage15GB free
CPU4+ cores

Model Sizes

ModelDownloadRAM Usage
nomic-embed-text~270MB~500MB
qwen2.5:7b-instruct~4.7GB~6GB
Total~5GB~6.5GB

Tested Platforms

PlatformPerformance
MacBook Pro M2 16GBβœ… Smooth (~10 tok/s)
MacBook Pro M1 16GBβœ… Good (~8 tok/s)
Linux + RTX 3060βœ… Fast (~25 tok/s)
Linux + RTX 4090βœ… Very fast (~40 tok/s)

Environment Variables

VariableDefaultDescription
PORT19089Service port
LLM_API_URLhttp://localhost:11435/v1LLM endpoint
LLM_MODELqwen2.5:7b-instructLLM model for MCP tools (recall, relate, etc.)
EMBEDDER_API_URLhttp://localhost:11435/v1Embedding endpoint
EMBEDDER_MODELnomic-embed-textEmbedding model
FALKORDB_URIredis://localhost:6380FalkorDB connection
OBSERVE_LLMtrueEnable LLM extraction for observe hooks (set false for regex-only)
OBSERVE_LLM_MODEL(same as LLM_MODEL)Cheaper model for observe hooks (e.g. deepseek/deepseek-v4-flash)
HASH_CACHE_LIMIT3000Max file hashes to track for skip-if-unchanged
ALLAN_MEMORY_DEBOUNCE_SECONDS60Observe hook debounce β€” wait this long after last read/edit before extracting
ALLAN_MEMORY_DEBOUNCE_DIR/tmp/allan-memory-debounceWhere the debounce state markers are stored

Observe Hook Hash Cache

Observe hooks use a content hash cache (~/.allan-memory/hashes.json) to skip reprocessing unchanged files:

  • observe-read: computes MD5 of file content, skips if hash matches a previous run
  • observe-edit: always processes (file was edited), updates hash so next read skips
  • Cache is capped at HASH_CACHE_LIMIT entries (default 3000), evicts oldest when full

Observe Hook Debouncing (Async)

The shipped observe-read.sh / observe-edit.sh hooks are non-blocking β€” they record a marker and exit in ~150ms, then a backgrounded worker waits ALLAN_MEMORY_DEBOUNCE_SECONDS (default 60s) before invoking the CLI.

If the same file is touched again within the debounce window, the older worker bails and only the newest one runs. Net effect:

edit foo.js β†’ edit foo.js β†’ edit foo.js   (within 60s)
                                       └─► one extraction, 60s after the last edit

This avoids piling up LLM calls when the assistant edits the same file repeatedly. Set ALLAN_MEMORY_DEBOUNCE_SECONDS=0 to disable (still async).

Observe Hook LLM Models

The observe hooks (triggered on every file read/edit) can use a separate, cheaper model than your main MCP tools:

ProviderModelInput/1MOutput/1MNotes
OpenRouterdeepseek/deepseek-v4-flash$0.10$0.20Best quality/price
OpenRouterdeepseek/deepseek-v4-flash:free$0.00$0.00Free tier
OpenRoutergoogle/gemma-4-31b-it:free$0.00$0.00Free tier, strong code
OpenRouterqwen/qwen3.5-9b$0.04$0.15Very cheap
Ollamaqwen2.5:7b-instructFreeFreeLocal, ~8 tok/s on M2
Ollamaqwen2.5:3b-instructFreeFreeFastest local option
Ollamagemma3:4bFreeFreeGood for extraction
Disabled(set OBSERVE_LLM=false)--Regex-only, instant

Tip: For observe hooks, you only need simple JSON extraction β€” a small/cheap model works great. Your main LLM_MODEL handles the complex MCP tool calls.


Use Cases & Benchmark

Quick Summary

ScenarioQueriesToken SavingsCost Savings
Single Function Query1-7%-7%
Repeated Queries (Same File)574%74%
Cross-File Queries578%78%
Full Codebase Exploration1088%88%
Long Coding Session2094%94%

Break-even: 2 queries β€” MCP pays for itself after just 2 queries about the same code.

Live MCP Performance

Measured on localhost with FalkorDB + OpenRouter (qwen/qwen-2.5-7b-instruct):

OperationTimeNotes
add_memory17msEpisode storage (LLM extraction is async)
search_nodes765msHybrid search (text + vector + embeddings)
search_facts410msRelationship search
check_freshness358msStaleness detection

Detailed Scenario Comparison

1. Single Function Query

1 query about one function β€” MCP has slight overhead

MetricWithout MCPWith MCPSavings
Input Tokens3,4003,650-7.4%
File Reads110 saved
Est. Cost (Claude 3.5)$0.0177$0.0185-4.2%

2. Repeated Queries (Same File)

5 queries about the same file β€” MCP wins big

MetricWithout MCPWith MCPSavings
Input Tokens17,0004,45073.8%
File Reads514 saved
Memory Cache Hits04-
Est. Cost (Claude 3.5)$0.0885$0.050842.5%

3. Cross-File Queries

5 queries across 4 different files

MetricWithout MCPWith MCPSavings
Input Tokens86,00019,30077.6%
File Reads20416 saved
Memory Cache Hits04-
Est. Cost (Claude 3.5)$0.2955$0.095467.7%

4. Full Codebase Exploration

10 queries exploring entire codebase (6 files)

MetricWithout MCPWith MCPSavings
Input Tokens248,00028,60088.5%
File Reads60654 saved
Memory Cache Hits09-
Est. Cost (Claude 3.5)$0.8190$0.160880.4%

5. Long Coding Session

Simulates 1-hour session with 20 queries

MetricWithout MCPWith MCPSavings
Input Tokens496,00030,60093.8%
File Reads1206114 saved
Memory Cache Hits019-
Est. Cost (Claude 3.5)$1.6380$0.241885.2%

Break-Even Analysis

Query 1: MCP has slight overhead (storing knowledge)
  Without MCP: ~3,200 tokens (read file)
  With MCP:    ~3,350 tokens (read + store)
  Result: MCP slightly more expensive

Query 2: MCP wins
  Without MCP: ~3,200 tokens (read file again)
  With MCP:    ~100 tokens (search_nodes hit)
  Cumulative:  6,400 vs 3,450 tokens

Query 3+: MCP advantage compounds
  Each additional query saves ~3,100 tokens

When to Use MCP

ScenarioRecommendationExpected Savings
Single one-off question❌ Skip MCP-
2-5 related questionsβœ… Use MCP50-80%
Long coding session (1hr+)βœ… Use MCP80-95%
Large codebase (50+ files)βœ… Use MCP90%+
Team with shared memoryβœ… Use MCP95%+

Run Benchmark Yourself

cd allan-mcp-memory-code
node benchmark.js

Freshness Checking

When code changes, stored memories become stale. Use check_freshness to detect this.

How It Works

1. AI calls check_freshness({ query, group_id, max_age_hours })
                              β”‚
                              β–Ό
2. Generate query embedding via Ollama/OpenRouter
                              β”‚
                              β–Ό
3. Hybrid search in FalkorDB (text + vector)
                              β”‚
                              β–Ό
4. For each result, calculate age:
   - age = now - created_at
   - status = age < max_age_hours ? FRESH : STALE
                              β”‚
                              β–Ό
5. Return formatted results:
   
   ---
   Found 3 memories: 2 FRESH, 1 STALE (threshold: 24h)
   login [FUNCTION] FRESH 2h ago | src/auth.js
   validateToken [FUNCTION] FRESH 5h ago | src/auth.js  
   hashPassword [FUNCTION] STALE 3d ago | src/crypto.js
                              β”‚
                              β–Ό
6. AI decides:
   - FRESH β†’ Trust memory, use directly
   - STALE β†’ Re-read file, update with add_memory

MCP Tool Usage

// Check freshness before using cached knowledge
check_freshness({
  query: "auth functions",
  group_id: "my-project",
  max_age_hours: 24  // optional, default 24
})

HTTP API Usage

curl -X POST http://localhost:19089/v1/memory/check-freshness \
  -H "Content-Type: application/json" \
  -d '{"query":"auth functions","group_id":"my-project","max_age_hours":24}'

Best Practice Workflow

1. search_nodes("function X")
2. Results found?
   β”œβ”€ Yes β†’ check_freshness("function X")
   β”‚        β”œβ”€ FRESH β†’ Use memory βœ“
   β”‚        └─ STALE β†’ regenerate_file(file_path) OR re-read β†’ add_memory
   └─ No β†’ Read file β†’ add_memory (create)

File Regeneration

After editing a file, use regenerate_file to automatically update the knowledge graph.

How It Works

1. AI calls regenerate_file({ file_path, project_root, group_id })
                              β”‚
                              β–Ό
2. MCP reads file content from disk
                              β”‚
                              β–Ό
3. Check .gitignore / .dockerignore (skip if matched)
                              β”‚
                              β–Ό
4. LLM extracts structured entities:
   - File: purpose, exports, dependencies
   - Functions: name, line numbers, signature, description
                              β”‚
                              β–Ό
5. Sync with knowledge graph:
   - CREATE new entities for new functions
   - UPDATE existing entities if changed
   - DELETE entities for removed functions
                              β”‚
                              β–Ό
6. Return summary:
   {
     "file_path": "src/auth.js",
     "status": "success",
     "created": ["func:project:src/auth.js:10-45@login"],
     "updated": ["file:project:src/auth.js"],
     "deleted": ["func:project:src/auth.js:80-100@oldFunc"]
   }

MCP Tool Usage

// After editing a file, regenerate its entities
regenerate_file({
  file_path: "src/auth/login.js",      // relative or absolute
  project_root: "/path/to/project",    // project root directory
  group_id: "my-project"               // required
})

HTTP API Usage

curl -X POST http://localhost:19089/v1/memory/regenerate-file \
  -H "Content-Type: application/json" \
  -d '{"file_path":"src/auth.js","project_root":"/path/to/project","group_id":"my-project"}'

Ignored Files

Respects .gitignore and .dockerignore patterns, plus:

  • node_modules/
  • .git/
  • dist/, build/
  • *.min.js, *.map
  • package-lock.json, yarn.lock

Local Development

# Start dependencies only
docker compose up falkordb ollama ollama-init -d

# Run locally
cp .env.example .env
npm install
npm run build   # Compile lib/ β†’ dist/ (Babel transpilation)
npm run dev     # Dev server with nodemon (auto-transpiles via @babel/register)
npm start       # Production (runs transpiled dist/)

Note: The lib/ source uses ES module import syntax. Always run npm run build before npm start. The dev script handles transpilation on-the-fly via @babel/register.


Architecture

lib/
β”œβ”€β”€ index.js                # Entry point
β”œβ”€β”€ domain/                 # Entities + Repository Interfaces
β”œβ”€β”€ application/use_cases/  # Business logic
β”œβ”€β”€ interface/              # Controllers, Routes, Repositories
└── infrastructure/         # Gateways (FalkorDB, LLM, Embedder)

License

GNU AGPL-3.0 β€” you may use, modify, and redistribute this software, but any redistribution or network/SaaS deployment must release the complete corresponding source (including your modifications) under the same license.

↑↓ navigate openesc close