Claude Code loses everything after /compact. Previous decisions, insights, technical findings, and conversation context vanish. Long sessions hit the context window limit and critical information gets pushed out. Every new session starts from scratch.
MemCP solves this. It gives Claude a persistent external memory — a place to store, organize, and retrieve knowledge across sessions without consuming context window tokens.
A persistent memory MCP server for Claude Code - Recursive Language Model integration for Claude Code inspired by MIT CSAIL paper
ดาว
17
เครื่องมือ
—
อัปไทม์
—
Problem
How MemCP Solves It
Context lost after /compact
Auto-save hooks force Claude to persist insights before compact
Session boundaries erase knowledge
Insights persist in SQLite across all sessions
Large documents fill context window
Content stays on disk as named variables; Claude loads only what it needs
No way to connect related knowledge
MAGMA 4-graph links insights via semantic, temporal, causal, and entity edges
Search is limited to current session
Tiered search (keyword → BM25 → semantic → hybrid) across all stored content
MemCP implements the RLM framework (Recursive Language Model, arXiv:2512.24601) — an active exploration model where content stays on disk and Claude decides what to load, rather than passive RAG retrieval.
Architecture
graph TB
CC[Claude Code] -->|MCP Protocol| S[MemCP Server<br/>FastMCP]
S --> M[Memory<br/>24 tools]
S --> G[MAGMA Graph<br/>SQLite]
S --> SR[Search<br/>5 tiers]
S --> C[Context Store<br/>Filesystem]
G -->|4 edge types| E1[Semantic]
G --> E2[Temporal]
G --> E3[Causal]
G --> E4[Entity]
SA[Sub-Agents] -->|MCP| S
SA --> A1[Analyzer]
SA --> A2[Mapper x N]
SA --> A3[Synthesizer]
H[Hooks] -->|PreCompact| CC
H -->|Reminders| CC
Interactive installer — step-by-step setup with bash scripts/install.sh
Docker support — single-command containerized deployment
Zero-config — works out of the box with sensible defaults
Available MCP Tools
MemCP exposes 24 MCP tools organized into 8 categories. For full documentation with parameters, examples, and tips, see docs/TOOLS.md.
Core Memory (5 tools)
Tool
Description
memcp_ping
Health check — returns server status and memory statistics
memcp_remember
Save an insight to persistent memory (decisions, facts, preferences, findings)
memcp_recall
Retrieve insights from memory with query, category, importance, and token budget filters
memcp_forget
Remove an insight from memory by ID
memcp_status
Current memory statistics — insight count, categories, importance distribution
Context Management (8 tools)
Tool
Description
memcp_load_context
Store content as a named context variable on disk (from text or file path)
memcp_inspect_context
Inspect a stored context — metadata and preview without loading full content
memcp_get_context
Read a stored context's content or a specific line range
memcp_chunk_context
Split a stored context into navigable numbered chunks (6 strategies: auto, lines, paragraphs, headings, chars, regex)
memcp_peek_chunk
Read a specific chunk from a chunked context
memcp_filter_context
Filter context content by regex pattern — returns only matching (or non-matching) lines
memcp_list_contexts
List all stored context variables
memcp_clear_context
Delete a stored context and its chunks
Search (1 tool)
Tool
Description
memcp_search
Search across memory insights and context chunks — auto-selects best available method (hybrid → BM25 → keyword)
Graph Memory (2 tools)
Tool
Description
memcp_related
Traverse graph from an insight — find connected knowledge via semantic, temporal, causal, or entity edges
memcp_graph_stats
Graph statistics — node count, edge counts by type, top entities
Cognitive Memory (3 tools)
Tool
Description
memcp_reinforce
Provide feedback on an insight — mark as helpful or misleading, affects ranking
memcp_consolidation_preview
Preview groups of similar insights that could be merged (dry-run)
memcp_consolidate
Merge a group of similar insights into one — unions tags, keeps best importance
Retention Lifecycle (3 tools)
Tool
Description
memcp_retention_preview
Preview what would be archived or purged (dry-run, no changes)
memcp_retention_run
Execute retention — archive old items, optionally purge past retention period
memcp_restore
Restore an archived context or insight back to active
Multi-Project & Session (2 tools)
Tool
Description
memcp_projects
List all projects with insight, context, and session counts
memcp_sessions
List sessions, optionally filtered by project
Benchmarks
MemCP includes a benchmark suite that measures the token efficiency advantage of persistent memory over context-window-only operation. The suite compares Native mode (all knowledge in the context window) against RLM mode (knowledge stored externally, loaded on demand via MCP tools).
Token Efficiency
Scenario
Native
RLM
Advantage
Reload 50 insights
896 tokens
167 tokens
5.4x less
Reload 500 insights
9,380 tokens
462 tokens
20.3x less
Analyse 5K-token doc
5,077 tokens
231 tokens
22.0x less
Analyse 50K-token doc
50,460 tokens
231 tokens
218.4x less
Cross-reference knowledge
1,861 tokens
172 tokens
10.8x less
Context Rot Resistance
Event
Native
RLM
After /compact
~5% retained
100% retained
After 3 compactions
~2% retained
100% retained
Cross-session recall
0%
92%
Context Window Management
Scenario
Native
RLM
10 simultaneous docs — window utilisation
93.6%
1.0%
Documents manageable (128K window)
13
50
Turns before first eviction
early
100+
Methodology note: The native baseline models worst-case context window loading. Real Claude Code also uses built-in tools for on-demand retrieval. See the full benchmark report for methodology notes, caveats, and all 40 comparisons.
Before installing MemCP, ensure you have the following on your machine:
Requirement
Version
Check Command
Python
3.10 or higher
python3 --version
pip
Latest recommended
pip --version
Git
Any recent version
git --version
Claude Code CLI
Latest
claude --version
Claude Code CLI is required for MCP server registration, hooks, and sub-agent deployment. Install it from Anthropic's documentation.
Optional (for Docker installation):
Requirement
Version
Check Command
Docker
20.10+
docker --version
Docker Compose
2.0+ (optional)
docker compose version
Installation
Quick Install (Recommended)
git clone https://github.com/mohamedali-may/memcp.git
cd memcp
make setup
The interactive installer will:
Check Python version, pip, Claude CLI
Ask your preferred install method (dev/pip/Docker)
Let you choose optional features (search, semantic, fuzzy, cache)
Install MemCP and verify the import
Register the MCP server with Claude Code
Deploy 4 RLM sub-agents to ~/.claude/agents/ (user-level, available across all projects)
Merge auto-save hooks into ~/.claude/settings.json (preserves existing settings)
Deploy CLAUDE.md to your project (session instructions for Claude Code)
Docker
# Build and run
docker build -t memcp .
claude mcp add memcp -- docker run --rm -i \
-v ~/.memcp:/data -e MEMCP_DATA_DIR=/data memcp
Or with docker-compose:
docker-compose up -d
claude mcp add memcp -- docker run --rm -i \
-v ~/.memcp:/data -e MEMCP_DATA_DIR=/data memcp
Manual Installation
If you prefer not to use the interactive installer:
# 1. Install in a venv
make dev # All extras (search, fuzzy, semantic, cache, …)
source .venv/bin/activate
# Or pick specific extras:
# pip install -e ".[dev]" # Dev tools only (pytest, ruff)
# pip install -e ".[dev,search,fuzzy]" # + BM25 + typo tolerance
# pip install -e ".[dev,semantic,cache]" # + vector embeddings + caching
# 2. Register with Claude Code
claude mcp add memcp -s user -- .venv/bin/python -m memcp
# 3. Deploy sub-agents (user-level, available across all projects)
mkdir -p ~/.claude/agents
cp agents/memcp-*.md ~/.claude/agents/
# 4. Merge hooks into global Claude Code settings
# If ~/.claude/settings.json doesn't exist or is empty:
cp hooks/snippets/settings.json ~/.claude/settings.json
# If it already has content, manually merge the "hooks" key from hooks/snippets/settings.json
# 5. Deploy CLAUDE.md to your project
cp templates/CLAUDE.md ./CLAUDE.md
# 6. Verify — in a Claude Code session, type: memcp_ping()
Uninstall
make teardown
The uninstaller lets you choose what to remove: MCP registration, sub-agents (~/.claude/agents/), hooks (from ~/.claude/settings.json), virtual environment, data directory, or everything.
How It Works
MemCP follows the RLM (Recursive Language Model) framework: content is stored externally as named variables, and Claude actively navigates to what it needs — rather than passively receiving retrieved chunks (RAG).
The Flow
Session Start
│
├─ memcp_recall(importance="critical") ← Load critical rules
├─ memcp_status() ← See memory stats
│
│ ... working ...
│
├─ memcp_remember("Decided to use Redis", ← Save a decision
│ category="decision",
│ importance="high",
│ tags="architecture,cache")
│
│ ... context filling up ...
│
├─ [Hook] "Consider saving context" ← Auto-reminder at 10 turns
│
├─ memcp_load_context("session-notes", ← Store large content on disk
│ content="...")
│
│ ... /compact ...
│
├─ [Hook] "SAVE REQUIRED" ← Blocks until saved
├─ memcp_remember(...) ← Save remaining insights
│
Next Session
│
├─ memcp_recall(importance="critical") ← Everything is still here
└─ memcp_search("Redis decision") ← Full search across sessions
Context-as-Variable (RLM)
Instead of loading a 50K-token document into the prompt:
memcp_load_context("report", file_path="large_report.md")
memcp_inspect_context("report") → type=markdown, 18K tokens, preview
memcp_chunk_context("report", "headings") → 12 chunks created
memcp_peek_chunk("report", 3) → reads only chunk #3 (~1500 tokens)
memcp_filter_context("report", "TODO|FIXME") → matching lines only
Result: ~1500 tokens in context instead of 18,000. A 92% reduction.
Knowledge Graph (MAGMA)
Every memcp_remember() creates a graph node and auto-generates edges:
memcp_remember("Use SQLite for graph", category="decision", tags="db")
│
├── temporal edge → insights created in last 30 min
├── entity edge → other insights mentioning "SQLite"
├── semantic edge → top-3 similar insights by content overlap
└── causal edge → if "because"/"therefore" detected, links to cause
Then memcp_recall("why SQLite?") detects "why" intent and follows causal edges to find the reasoning.
Usage Examples
1. Remember Decisions Across Sessions
memcp_remember(
"Never push directly to main — always use PRs with at least 1 review",
category="decision",
importance="critical",
tags="git,workflow"
)
Next session: memcp_recall(importance="critical") loads this rule automatically.
2. Analyze a Large Codebase File
memcp_load_context("api-module", file_path="src/api/routes.py")
memcp_inspect_context("api-module")
→ python, 2400 lines, ~15K tokens
memcp_chunk_context("api-module", strategy="lines", chunk_size=100)
→ 24 chunks created
memcp_filter_context("api-module", "def\\s+\\w+")
→ all function definitions (50 lines instead of 2400)
memcp_peek_chunk("api-module", 5)
→ read chunk #5 in detail
3. Cross-Reference with Graph Traversal
memcp_remember("Found race condition in file writer", category="finding", tags="bug,concurrency")
memcp_remember("Fixed race condition with flock", category="decision", tags="bug,concurrency")
memcp_related("abc123", edge_type="causal")
→ shows the finding linked to the fix decision
memcp_graph_stats()
→ 42 nodes, 287 edges, top entities: ["file writer", "flock", ...]
4. Map-Reduce with Sub-Agents
For analyzing a large document across multiple chunks in parallel:
Architecture Decision Records — 13 ADRs documenting key technical choices
Development
make dev # Create venv + install all extras + pre-commit
source .venv/bin/activate
make test # Unit tests (core)
make test-all # Unit + benchmark tests
make benchmark # Benchmark suite only
make lint # Lint + format check (CI-equivalent)
make fmt # Auto-fix lint + format
make run # Start the MCP server
make clean # Remove build/cache artifacts
Note:make dev installs all optional extras (search, fuzzy, semantic, cache, vectors, llm, benchmark), so search and semantic tests will run out of the box. If you installed only specific extras, some search-tier tests will be skipped automatically.
Run make or make help to see all available targets.
CI/CD
GitHub Actions runs on every push: lint (ruff) + unit test matrix (Python 3.10/3.11/3.12) + Docker build
All data stored locally (~/.memcp/) — nothing leaves your machine
Secret detection blocks accidental storage of API keys, tokens, private keys, and passwords (8 regex patterns; disable with MEMCP_SECRET_DETECTION=false)
Atomic file writes with fcntl.flock for concurrent access safety
Input validation via safe_name() prevents path traversal
Structured error hierarchy (MemCPError) with consistent error handling across all modules
Config validation catches invalid environment variables at startup
SQLite WAL mode + busy_timeout=5000 for ACID-compliant concurrent operations
No network calls (unless using remote embedding providers)
คัดลอกคอนฟิก stdio สำหรับ Cursor, Claude Desktop, Claude Code หรือ VS Code ได้ในหน้านี้ คอนฟิกนี้ใช้การติดตั้งของผู้เผยแพร่ ไม่ใช่พร็อกซีของ PlugMCP
Memcp ต้องใช้ API key ไหม?
ระเบียนนี้ไม่ได้ระบุตัวแปรสภาพแวดล้อมที่จำเป็น
Memcp ใช้ทรานสปอร์ตแบบใด?
Memcp ทำงานแบบโลคัลผ่าน stdio
Memcp ถูกตรวจสอบล่าสุดเมื่อใด?
ตรวจสอบล่าสุดเมื่อ 2026-10-28 A persistent memory MCP server for Claude Code - Recursive Language Model integration for Claude Code inspired by MIT CSAIL paper