MCP Hub
Back to servers

context-mem

Validation Failed

Persistent memory for AI agents — 98%+ retrieval recall, 99% token savings, 44 tools

Registry
Stars
10
Forks
3
Updated
Apr 15, 2026
Validated
Apr 17, 2026

Validation Error:

Timeout after 45s

Quick Install

npx -y context-mem

Context Mem — persistent memory for AI agents

Context Mem

Your AI coding assistant forgets everything between sessions. This fixes that.

npm version LongMemEval tests tools license


The Problem

Every time you start a new AI session, your assistant has zero memory of what you built yesterday. The architecture decisions, the bugs you fixed, the preferences you stated — all gone. You spend the first 10 minutes re-explaining context.

The Fix

context-mem runs in the background, captures everything automatically, and retrieves exactly the right context when you need it:

  • Longer sessions without losing context (99% token savings)
  • Instant continuity — new sessions pick up where you left off
  • Automatic — no manual saving, no commands to remember
  • Fully local — your code never leaves your machine
  • Free — no API keys, no subscription, no cloud
npm i context-mem && npx context-mem init

One command. Works with Claude Code, Cursor, Windsurf, VS Code, Cline, and Roo Code.


Retrieval Benchmarks

Tested on 4 academic benchmarks. All scores are session-level retrieval recall (did the correct session appear in top-k?), not end-to-end QA accuracy.

Pure Local (zero API calls, fully free)

BenchmarkRetrieval RecallQuestionsSessions/convMetric
LongMemEval97.8% R@5500~53Session R@5
LoCoMo98.1% R@101,97719-35Session R@10
MemBench98.0% R@5500Hybrid top-5
ConvoMem97.7% R@10250Session R@10

With Optional LLM Reranking (Haiku, ~$1 per 500 queries)

BenchmarkRetrieval Recall
LongMemEval100.0% R@5 (500/500)

vs MemPalace (same methodology — session-level retrieval recall)

BenchmarkContext MemMemPalace
LongMemEval R@597.8%96.6%
LoCoMo R@1098.1%60.3%

Both systems achieve 100% on LME with optional Haiku reranking. MemPalace comparison uses identical methodology (session-level, same datasets).

Benchmark methodology notes
  • Metric: Session-level retrieval recall — a hit is scored if any correct evidence session appears in the top-k results. This is different from end-to-end QA accuracy (retrieve + generate answer + judge), which would be lower for any system.
  • Granularity: Sessions (all dialog turns joined per session). LoCoMo has 19-35 sessions per conversation, so R@10 selects roughly a third of the candidate pool.
  • Ingestion: LoCoMo benchmark appends dataset-provided metadata (session_summary, observation, event_summary) to session documents. The production system does similar enrichment via summarizers and entity extraction.
  • Synonym expansions: Core query-builder includes general synonyms (movie→film, sibling→brother). Benchmark adapter adds ~50 additional domain-specific expansions derived from failure analysis. Core-only results are ~1-2% lower.
  • Benchmark code: Fully open in benchmarks/ — run them yourself with npm run bench.

How It Works

Observation Pipeline

Every tool output flows through the pipeline: privacy screening (9 secret detectors) → parallel extraction (entities, importance, topics) → 14 content summarizerstriple storage (verbatim archive, SQLite summaries, knowledge graph) → adaptive compression over time.

Full coding session (50 tool outputs): 365 KB → 3.2 KB (99% savings).


What it is (and isn't)

context-mem is:

  • A retrieval-first memory system (not a chatbot wrapper)
  • A context compression engine (14 content-aware summarizers)
  • Infrastructure for AI agents (44 MCP tools)

context-mem is not:

  • Chat history storage (it extracts meaning, not raw logs)
  • An LLM wrapper (works without any API keys)
  • A cloud service (fully local SQLite)

Quick Start

npm i context-mem && npx context-mem init

init auto-detects your editor:

EditorWhat gets created
Claude Code.mcp.json + hooks (8 hooks incl. context-triggered injection) + CLAUDE.md
Cursor.cursor/mcp.json + .cursor/rules/context-mem.mdc
Windsurf.windsurf/mcp.json + .windsurf/rules/context-mem.md
VS Code / Copilot.vscode/mcp.json + .github/copilot-instructions.md
Cline.cline/mcp_settings.json + .clinerules/context-mem.md
Roo Code.roo-code/mcp_settings.json + .roo/rules/context-mem.md

Real-World Examples

You: "Why did we choose Postgres?"
  → recall returns the exact verbatim quote from March 15, importance 0.95,
    with the full evidence chain: error → file_read → search → decision

You: "What did Sarah work on last sprint?"
  → browse by person shows 14 observations mentioning Sarah,
    grouped by topic (auth, database, deployment)

You: "Generate a PR description"
  → context-mem story --format pr assembles changes, decisions, resolved
    issues, and test plan from the current session

You: "What are we about to forget?"
  → predict_loss shows 8 entries at risk: low importance, 45+ days old,
    never accessed. Pin the critical ones before they decay.

Search Architecture

Hybrid Parallel Search

BM25 (8 strategies + synonym expansion) and vector search run independently in parallel, then fuse via intent-adaptive weights with IDF-weighted content reranking. Optional LLM judge reranker pushes accuracy to 100%. Fully local by default.


Core Features

CapabilityDescription
Importance ScoringEvery observation scored 0.0–1.0 with 6 significance flags: DECISION, ORIGIN, PIVOT, CORE, MILESTONE, PROBLEM. Auto-pin for decisions and milestones.
Verbatim RecallSurface original content (not summaries) via recall tool. Dedicated FTS5 index. Importance, type, time, and flag filters.
Adaptive Compression4-tier progressive: verbatim (0-7d) → light (7-30d) → medium (30-90d) → distilled (90d+). Pinned entries stay verbatim forever.
Entity IntelligenceAuto-detect technologies, people, file paths, CamelCase, ALL_CAPS. 100+ aliases (React.js → React). Knowledge graph storage.
Temporal Factsvalid_from/valid_to on knowledge. Supersession chains. temporal_query: "what was true about X at time T?"
Wake-Up PrimerToken-budgeted context at session start. 4 layers: profile (15%), critical knowledge (40%), decisions (30%), entities (15%).
Decision TrailsEvidence chain reconstruction. explain_decision walks events backward: file reads → errors → searches → decision.
Session Narratives4 templates: PR description, standup update, ADR, onboarding guide. CLI: context-mem story --format pr.
Hybrid SearchBM25 (8 strategies + synonym expansion) + vector (nomic-embed 768-dim) parallel fusion. Optional LLM judge reranker. Sub-millisecond.
Temporal ResolverDeterministic date parsing for relative time queries ("3 days ago", "last Saturday"). Zero LLM cost.
Per-Prompt InjectionUserPromptSubmit hook auto-injects relevant memories on every user message. Rate-limited, topic-deduplicated.
Knowledge GraphEntity-relationship model: files, modules, patterns, decisions, bugs, people, libraries, services, APIs, configs.
Multi-AgentRegister, claim files, check status, broadcast. Shared memory prevents duplicate work and merge conflicts.
Privacy EngineFully local. <private> tag stripping, custom regex, 9 secret detectors. No telemetry, no cloud.

Intelligence Dashboard

Real-time web UI with 6 pages — context-mem dashboard to launch:

Dashboard — Intelligence Overview
More dashboard pages

Knowledge Graph — force-directed entity visualization with type filtering and depth control:

Dashboard — Knowledge Graph

Topics — topic cloud with observation counts and cross-project tunnels:

Dashboard — Topics

Timeline — chronological observations with importance badges, flags, and verbatim mode:

Dashboard — Timeline

How It Compares

Context Mem v3.2MemPalaceclaude-mem
Retrieval Recall98%+ session recall (4 benchmarks)96.6% LME, 60.3% LoCoMoNot benchmarked
Token Savings99% (benchmarked)0% (stores everything)~95% (claimed)
SearchBM25 (8 strategies) + Vector + LLM JudgeChromaDBBasic recall
Entity IntelligenceAuto-detect + 100 aliases + graphNoNo
Importance Scoring0.0-1.0 with 6 significance flagsNoNo
Decision TrailsEvidence chain reconstructionNoNo
Session NarrativesPR/Standup/ADR/OnboardingNoNo
Cross-Project MemoryGlobal store + topic tunnelsNoNo
LLM DependencyOptional (free by default)100% LME requires paid APIRequired (~$57/mo)
PrivacyFully local, 9 secret detectorsLocalLocal
LicenseMITProprietaryAGPL-3.0

Performance

All operations are sub-millisecond, zero LLM dependency:

OperationSpeedLatency
Importance Classification556K ops/s0.002ms
Entity Extraction179K ops/s0.006ms
Topic Detection162K ops/s0.006ms
Compression Tier Calc3M ops/s<0.001ms
Verbatim FTS Search50K ops/s0.020ms
BM25 Search3.3K ops/s0.3ms
Wake-Up Primer Assembly9K ops/s0.111ms
Narrative Generation6K ops/s0.164ms

MCP Tools (44)

Click to see all 44 tools
ToolDescription
Core
observeStore observation with auto-summarization + importance scoring
searchHybrid search with optional verbatim mode
getRetrieve full observation by ID
timelineReverse-chronological list with importance badges
statsToken economics for current session
summarizeSummarize content without storing
configureUpdate runtime configuration
executeRun code (JS, TS, Python, Shell, Ruby, Go, Rust, PHP, Perl, R, Elixir)
Content
index_contentIndex with code-aware chunking
search_contentSearch indexed chunks
Knowledge
save_knowledgeSave with contradiction detection + temporal validity
search_knowledgeSearch (filters superseded by default)
promote_knowledgePromote to global cross-project store
global_searchSearch across all projects
resolve_contradictionResolve conflicts (supersede/merge/keep/archive)
merge_suggestionsView cross-project duplicate suggestions
Graph
graph_queryTraverse entity relationships
add_relationshipLink entities
graph_neighborsFind connected entities
Session
update_profileProject profile
budget_status / budget_configureToken budget management
restore_sessionRestore from snapshot
handoff_sessionCross-session continuity
Events
emit_event / query_eventsP1-P4 event tracking
Agents
agent_register / agent_status / claim_files / agent_broadcastMulti-agent coordination
Intelligence
time_travelCompare project state at any point in time
askNatural language question answering
Total Recall
recallVerbatim memory retrieval with importance/flag/time filters
wake_upGenerate scored session primer (4-layer context)
entity_detectExtract entities from text
list_peoplePerson entities with relationship counts
temporal_queryKnowledge valid at specific timestamp
browseNavigate by topic, person, or time
list_topicsTopic list with observation counts
find_tunnelsCross-project topic bridges
import_conversationsImport ChatGPT/Claude/Slack/text conversations
explain_decisionDecision trail evidence chain
generate_storyNarrative (PR/standup/ADR/onboarding)
predict_lossMemory pressure prediction

CLI Commands

context-mem init                    # Initialize in current project
context-mem serve                   # Start MCP server (stdio)
context-mem status                  # Show database stats
context-mem doctor                  # Run health checks
context-mem dashboard               # Open web dashboard (6 pages)
context-mem why <query>             # Decision trail — why was X decided?
context-mem story --format pr       # Generate narrative (pr/standup/adr/onboarding)
context-mem import-convos <path>    # Import conversations (auto-detect format)
context-mem export                  # Export as JSON
context-mem import                  # Import from JSON
context-mem plugin add|remove|list  # Manage summarizer plugins

Configuration

.context-mem.json
{
  "storage": "auto",
  "plugins": {
    "summarizers": ["shell", "json", "error", "log", "code"],
    "search": ["bm25", "trigram", "vector"],
    "runtimes": ["javascript", "python"]
  },
  "search_weights": { "bm25": 0.45, "trigram": 0.15, "levenshtein": 0.05, "vector": 0.35 },
  "privacy": { "strip_tags": true, "redact_patterns": [] },
  "lifecycle": { "ttl_days": 30, "max_db_size_mb": 500, "max_observations": 50000 },
  "ai_curation": { "enabled": false, "provider": "auto" }
}

Platform Support

PlatformAuto-Setup
Claude Code, Cursor, Windsurf, VS Code/Copilot, Cline, Roo Codecontext-mem init
Gemini CLI, Antigravity, Goose, OpenClaw, CrewAI, LangChainSee configs/

Documentation

DocDescription
Benchmark ResultsCompression + retrieval benchmarks
ContributingHow to contribute

License

MIT — Juba Kitiashvili


Get Started

npm i context-mem && npx context-mem init

Read the Docs · View Benchmarks · Report a Bug · Contributing


Context Mem v3.2 — 98%+ accuracy on every benchmark. Your AI never forgets.

Star on GitHub npm Follow

Reviews

No reviews yet

Sign in to write a review