MCP Engram Memory README

The full upstream README, mirrored for reference. Install config, tool schemas, adoption signals and our own overview live on the MCP Engram Memory listing page.

MCP Engram Memory

.NET License: MIT NuGet Tests: .NET 8, 9, and 10 Release: 2.1

The governed, local-first cognitive memory kernel for AI agents

Memory physics, not just storage. Most agent memory systems store context. Engram evolves context — topology-driven decay, consolidation, and contradiction detection, all running locally with zero external API.

2.1 improves recall and release reliability. Questions recover relevant sources under noise, historical and compound answers retain the requested evidence, and routing preserves project, environment, tenant and namespace boundaries. Persistence, timers and installation upgrades are hardened without changing MCP tool names or arguments.

  • Tenant-Partitioned Throughout — partitioning runs through storage, graph, clusters, lifecycle, diffusion, synthesis, and visualization. Edges never cross tenants; cross-namespace association within a tenant is preserved.
  • Context Control — graph-Laplacian diffusion decays trivial chats so your context window doesn't choke on noise. Important, well-connected knowledge stays sharp; transient chatter fades.
  • Contradiction Detection — find_contradictions surfaces conflicting goals or architecture decisions on demand, so you can review and retire logic you've already reversed instead of letting the agent keep acting on it.
  • Governed Core — a deterministic Root Constitution, versioned knowledge and provenance, Teacher/Verifier promotion, authorization-first retrieval planning, and citation-aware context manifests are available to embedding hosts.
  • Privacy by default — local ONNX embeddings and local storage. The MCP executable enforces ONNX telemetry suppression before loading the native runtime on Windows, Linux and macOS; see the telemetry policy and validation. Optional remote storage, synthesis and live benchmark services make network calls only when configured. Hosts embedding the Core library must establish their own process policy.

→ See the cold-start scorecard · Get started in 5 minutes · What's new in 2.1

What's New in 2.1

ChangeWhat it means
More complete recallDirect and routed searches recover missing answers under noise, retain sources alongside summaries, and cover broad, compound and historical questions.
Evidence-based answersNon-answer text and mismatched project/environment evidence are rejected; superseded claims rank appropriately and unresolved contradictions remain visible.
Reliable persistence and maintenanceMerge/snapshot deadlocks and stale timer callbacks are fixed. Deterministic concurrency and simulated maintenance tests supplement bounded real MCP stress.
Safer installation and upgradesThe server uses a durable user data directory; the pre-update helper preserves old package-local data before replacement. Client configuration is preserved.
Early telemetry suppressionThe MCP executable suppresses ONNX telemetry before native initialization on the validated Windows, Linux and macOS platforms.

This documentation targets 2.1.0; package commands require that version in the selected feed. The three packages ship together. MCP profiles remain 17 / 39 / 63 tools, and the Core/Synthesis public APIs remain compatible with 2.0.0. New optional recall conflict diagnostics are additive.

Upgrading an existing 2.0.0 tool: stop its servers and follow the pre-update migration procedure before running a package update or uninstall. The old package manager removes version-local default data during replacement. Existing explicit data paths remain supported. Read the 2.1.0 release notes for compatibility, validation and limits. Hosts upgrading from pre-2.0 Core must still follow the 2.0 API migration.

How It Works

Engram sits between your AI assistant and a local store. Every memory is embedded, indexed for hybrid search, woven into a knowledge graph, and then left to evolve on its own — background workers decay noise, consolidate what matters, and densify the graph while you're away.

How It Works — store, search, link, route, with automatic diffusion subsystem and lifecycle transitions

The loop, end to end:

  1. Store — remember embeds text with a local ONNX model (bge-micro-v2, 384-dim), detects near-duplicates, and auto-links the new memory to related ones in the graph.
  2. Search — recall runs hybrid retrieval (BM25 keyword + vector similarity, fused with RRF), expands synonyms, and re-ranks through the graph's spectral structure. (Opt-in MMR diversity reranking is available on search_memory and cross_search.)
  3. Route — with the namespace omitted, recall auto-routes across expert namespaces to find knowledge you didn't know where to look for.
  4. Evolve — background services run the physics: spectral decay fades weakly-connected memories (archiving the weakest), sleep consolidation promotes well-connected STM to LTM, and auto-link densifies the graph.

Retrieval itself is a nine-stage pipeline — candidate generation, keyword rescue, fusion, diversity, and spectral re-ranking:

9-stage retrieval pipeline including v0.9.0 spectral re-ranking

See It in Action

Engram memory graph clustering during a consolidation cycle: STM (amber) nodes migrating into LTM (blue) clusters, with pulse-highlight on retrieval

The memory graph consolidating in real time — short-term (amber) memories cluster and promote to long-term (blue) during a sleep cycle.

The built-in D3.js graph viewer lets you explore your own memory graph interactively. Generate a snapshot from any AI assistant, then open the viewer:

Code
get_graph_snapshot   →   save the JSON   →   open visualization/memory-graph.html

Memory graph overview — 1,207 nodes, 375 edges, 178 clusters

Memory graph connected-only detail view

Viewer features:

  • Force-directed layout — related memories cluster together, typed edges (elaborates, contradicts, depends_on, …) shown in distinct neon colors
  • Lifecycle colors — STM nodes amber, LTM nodes blue; cluster summaries marked with a dashed ring
  • Convex-hull cluster overlays — cluster membership visible at a glance
  • Search & highlight — type in the search bar to instantly dim non-matching nodes and pulse-highlight matches in gold; ‹ › buttons or Enter / Shift+Enter to cycle through results
  • Zoom / pan / rotate — + / − / ⊡ buttons; scroll to zoom; right-click drag to rotate the whole graph
  • Fractal density overlay — zooms out reveal a quadtree density map color-coded by lifecycle state
  • Connected-only filter — hide isolated nodes to focus on the linked knowledge graph
  • Drag-and-drop JSON loading — drop a snapshot file directly onto the viewer

The snapshot file is not committed (it's personal memory data). Generate a fresh one any time with get_graph_snapshot.

Quickstart

Existing 2.0.0 installation? Follow the safe upgrade procedure before updating: default data in the old version directory must be backed up and migrated first. The 2.1 server uses a durable user data directory; existing explicit paths are preserved.

powershell
# Windows — clones, builds, and wires up your AI assistant automatically
irm https://raw.githubusercontent.com/wyckit/mcp-engram-memory/main/setup.ps1 | iex
bash
# macOS / Linux
curl -fsSL https://raw.githubusercontent.com/wyckit/mcp-engram-memory/main/setup.sh | bash

The embedding model (bge-micro-v2) ships inside the package — it is fetched from Hugging Face at build time, checksum-verified, and bundled, so installing the tool needs no model download and the server makes no network call to start.

Other install options (manual clone · Docker · NuGet)

Manual clone

bash
git clone https://github.com/wyckit/mcp-engram-memory.git
cd mcp-engram-memory
dotnet publish src/McpEngramMemory/McpEngramMemory.csproj -c Release -f net8.0 -p:TargetFrameworks=net8.0 -o .engram/server

Add to your MCP client config:

config.json
{
  "mcpServers": {
    "engram-memory": {
      "command": "dotnet",
      "args": ["/path/to/mcp-engram-memory/.engram/server/McpEngramMemory.dll"],
      "env": { "MEMORY_TOOL_PROFILE": "minimal" }
    }
  }
}

Docker

Terminal
docker build -t mcp-engram-memory .
docker run -i -v memory-data:/app/data mcp-engram-memory

NuGet library (embed the engine in your own .NET app)

bash
dotnet add package McpEngramMemory.Core --version 2.1.0

See examples/ for ready-to-use config files.

At a Glance

MetricValue
Version2.1.0 (compatible with 2.0 APIs)
MCP tools63 (profiles: 17 / 39 / 63)
IsolationTenant-partitioned across storage, graph, clusters, lifecycle, diffusion, synthesis, and snapshots
RetrievalHybrid BM25 + vector with synonym expansion, cascade retrieval, MMR diversity, auto-PRF
Embeddingbge-micro-v2 (384-dim, ONNX, MIT license, runs locally, concurrent inference)
Best recall0.792 realworld dataset, 0.771 scale dataset (hybrid mode)
Search latency~2.7 ms production, ~0.04 ms benchmark
StorageJSON (default) or SQLite (WAL mode)
Frameworksnet8.0, net9.0, net10.0
TestsMulti-target xUnit suite across net8.0, net9.0, and net10.0
CI/CDGitHub Actions: build + test on push, nightly MSA benchmarks

Tool Profiles

Engram exposes a tunable tool surface. Start on minimal — three headline verbs (remember, recall, reflect) plus admin and multi-agent — and widen only if you need the advanced subsystems. Control it with MEMORY_TOOL_PROFILE:

ProfileToolsWhat's included
minimal17Core CRUD + composite + admin + multi-agent — recommended starting point (default)
standard39Adds graph (+auto-link), lifecycle (+consolidation), clustering, intelligence, memory-diffusion kernel, spectral retrieval
full63Everything including governed knowledge promotion, expert routing, debate, synthesis, benchmarks

MCP Tools (63)

GroupToolsDescription
Core Memorystore_memory, store_batch, search_memory, delete_memoryVector CRUD with namespace isolation, batch import, and lifecycle-aware search
Compositeremember, recall (with spectralMode), reflect, get_context_blockHigh-level wrappers with auto-dedup, auto-linking, expert routing, context assembly, and graph-aware spectral re-ranking on recall (default auto)
Knowledge Graphlink_memories, unlink_memories, get_neighbors, traverse_graphDirected graph with 7 relation types and multi-hop BFS; similarity-based auto-link densification runs as a 6-hour background sweep
Clusteringcreate_cluster, update_cluster, store_cluster_summary, get_cluster, list_clustersSemantic grouping with auto-computed centroids
Lifecyclepromote_memory, memory_feedback, deep_recall, configure_decayState transitions (STM/LTM/archived) and per-namespace decay configuration; spectral decay diffusion and sleep consolidation run automatically as background services
Memory Diffusioncompute_diffusion_basis, diffusion_stats, invalidate_diffusion, spectral_recallGraph-Laplacian eigenbasis primitive shared by decay, consolidation, and retrieval; standalone graph-aware retrieval
Intelligencedetect_duplicates, find_contradictions, merge_memories, uncollapse_cluster, list_collapse_historyDedup, contradiction detection, merge, collapse reversal
Expert Routingdispatch_task, create_expert, get_domain_tree, link_to_parentHMoE semantic routing with 3-level domain tree
Multi-Agentcross_search, share_namespace, unshare_namespace, list_shared, whoamiNamespace sharing, permissions, cross-namespace RRF search
Debateconsult_expert_panel, map_debate_graph, resolve_debateMulti-perspective analysis with debate tracking
Synthesissynthesize_memoriesMap-reduce synthesis via a local SLM served by Ollama. For fully in-process generation, embed McpEngramMemory.Core and add the optional McpEngramMemory.Synthesis.Onnx package
Accretionget_pending_collapses, collapse_cluster, dismiss_collapseDBSCAN cluster detection and two-phase summarization (the density scan runs as a 30-min background sweep)
Governed Learningpromote_knowledgeFull-profile adapter for the Teacher → deterministic Verifier → Constitution receipt → atomic governed-store promotion path
Adminget_memory, cognitive_stats, engram_status, purge_debatesInspection, system-wide statistics, background-worker health, and stale debate-namespace cleanup
Maintenancerebuild_embeddings, compression_statsRe-embed entries and storage diagnostics
Benchmarksrun_benchmark, run_agent_outcome_benchmark, run_live_agent_outcome_benchmark, compare_live_agent_outcome_artifacts, check_for_regression, get_metrics, reset_metrics, run_mrcr_benchmark, compare_mrcr_artifactsIR quality validation, proxy and live memory-condition benchmarking, artifact diffing, CI regression gating, latency/throughput metrics, and MRCR v2 long-context A/B
Visualizationget_graph_snapshotMemory-graph JSON snapshot (nodes, typed edges, clusters) for the built-in D3 viewer (visualization/memory-graph.html)

Full tool documentation: MCP Tools Reference

The server uses the ModelContextProtocol 2.2.0 SDK with negotiated protocol handling, a global request-filter pipeline, and explicit read-only/destructive/idempotent/open-world tool metadata. SDK package version and negotiated MCP protocol revision are not the same thing.

Architecture

LayerStabilityComponents
CoreStableStorage, Embeddings, Retrieval, Lifecycle, Graph
AdvancedStableClustering, Multi-Agent Sharing, Intelligence
Governed CoreMaturingConstitution, Knowledge, Provenance, Learning, Planning, Semantic Assets
OrchestrationMaturingExpert Routing (HMoE), Debate, Benchmarks

Governed Core vs. MCP tools

The governed substrate lives in McpEngramMemory.Core: immutable Root/overlay Constitutions, versioned Knowledge and append-only Provenance, quarantined Teacher proposals, deterministic-first verification, atomic reference promotion, authorization-first retrieval planning, context manifests, profiles/loadouts, and Skill/Documentation/CodeGraph/Curriculum contracts.

The 63 MCP tools include the full-profile promote_knowledge adapter, which executes the Teacher → deterministic Verifier → Constitution receipt → atomic governed-store path. Context and other asset-management tools remain Core APIs for embedded hosts. Every tool call also passes through the global Constitution pre/post filter. Skill execution is delegated to a host-provided ISkillSandbox; Engram does not run arbitrary Skill code.

Identity is also host-owned. IPrincipalContext carries tenant and principal claims. The stdio server bootstraps it from MEMORY_TENANT_ID and AGENT_ID, which are process configuration rather than authentication. Empty tenant + default agent is explicit legacy-unisolated mode.

Multi-tenancy is complete and, as of 2.0, mandatory at the API boundary. Memory CRUD and search, the cognitive graph, clusters, lifecycle, collapse history, diffusion/spectral retrieval, intelligence, maintenance, synthesis, and visualization are all tenant-partitioned: a tenant sees and mutates only its own data, and graph edges never cross tenants (cross-namespace association within a tenant is preserved). Core's retrieval and scoping APIs take tenantId as a required argument, so scope is a decision the compiler makes you state rather than a default you can forget — "" remains a valid answer, and the legacy partition it names is a real dataset, so state it deliberately. Legacy empty-tenant deployments are byte-for-byte unchanged. See Cognitive Constitution and Governed Core and Security.

AI Assistant Setup

Model execution belongs to the host harness, not the Engram server: expert profiles route to persona-backed memory namespaces, while the host model reasons over the retrieved evidence. See Model and Reasoning Routing for canonical task tiers, the current Codex model mapping, reasoning escalation rules, and ready-to-use profiles.

Copy the reference harness for your tool — each includes recall/store/routing patterns:

ToolHarness FileMCP Config
Claude Codeexamples/CLAUDE.md → ~/.claude/CLAUDE.mdexamples/claude-code.json (standard) / claude-code-minimal.json (minimal)
GitHub Copilotexamples/copilot-instructions.md → .github/examples/vscode-copilot.json
Google GeminiGEMINI.md → workspace rootGemini CLI config
OpenAI Codexexamples/AGENTS.md → project rootCodex config

Claude Code users: Route memory sub-agents to Sonnet (model: "sonnet") and utility sub-agents to Haiku (model: "haiku") to maximize your subscription. See the harness for details.

For step-by-step setup prompts, see AI Assistant Setup.

Cost-Optimized Usage (Claude Code)

TierModelWhat runs here
Main threadOpusCoding, architecture, reasoning, decisions
Memory sub-agentsSonnet (model: "sonnet")All engram MCP tool calls: search, store, dispatch, link, merge
Utility sub-agentsHaiku (model: "haiku")Codebase exploration, file searches, grep research, simple lookups

Opus thinks, Sonnet remembers, Haiku explores.

Environment Variables

VariableDefaultDescription
MEMORY_TOOL_PROFILEminimalTool profile: minimal (17), standard (39), full (63)
AGENT_IDdefaultHost-supplied agent identity for namespace sharing. The default is explicit legacy-unisolated compatibility mode, not authentication.
MEMORY_TENANT_IDemptyHost-supplied tenant partition. Do not accept this value from model/tool arguments. Empty selects the legacy partition.
MEMORY_STORAGEjsonStorage backend: json, sqlite, or sqlserver
MEMORY_DATA_PATHUser-local app data / engram-memoryDurable server data root; see migration instructions
MEMORY_SQLITE_PATH<data-root>/memory.dbSQLite database path (when MEMORY_STORAGE=sqlite); explicit overrides are preserved
MEMORY_SQLSERVER_CONNECTIONrequiredSQL Server connection string (when MEMORY_STORAGE=sqlserver)
MEMORY_SQLSERVER_SCHEMAdboSQL Server schema name (when MEMORY_STORAGE=sqlserver)
MEMORY_MAX_NAMESPACE_SIZEunlimitedMax entries per namespace
MEMORY_MAX_TOTAL_COUNTunlimitedMax total entries across all namespaces

NuGet / GitHub Packages

The server ships as a dotnet global tool, and the core engine as a library you can embed in your own .NET applications. NuGet.org is the primary distribution feed (published via publish-nuget.ps1 from validated CI archives); GitHub Packages mirrors are published separately using the same archives and require GitHub package authentication.

Server (global tool)

bash
dotnet tool install --global McpEngramMemory --version 2.1.0
engram-memory

Core engine (library)

bash
# nuget.org (primary)
dotnet add package McpEngramMemory.Core --version 2.1.0

# GitHub Packages (optional mirror; requires GitHub Packages auth)
dotnet add package McpEngramMemory.Core --version 2.1.0 \
  --source https://nuget.pkg.github.com/wyckit/index.json

Optional: in-process synthesis

synthesize_memories generates through an ITextGenerator. The server ships one implementation — OllamaClient, talking to a local Ollama daemon. If you want generation fully in-process with no daemon, add the optional ONNX backend when embedding the library:

bash
dotnet add package McpEngramMemory.Synthesis.Onnx --version 2.1.0
csharp
using McpEngramMemory.Core.Services.Synthesis;

ITextGenerator generator = new OnnxGenAiTextGenerator(modelDir); // stage a model first

It lives in its own package because ONNX Runtime GenAI ships native binaries for every platform it supports — roughly 500 MB. Keeping it separate means neither the McpEngramMemory tool nor a plain McpEngramMemory.Core install pays that cost. Stage a model with scripts/fetch-synthesis-model.ps1.

The McpEngramMemory server does not support SYNTHESIS_BACKEND=onnx; it fails at startup with a pointer to this package. In-process synthesis is for hosts embedding the Core library.

server.ts
using McpEngramMemory.Core.Models;
using McpEngramMemory.Core.Services;
using McpEngramMemory.Core.Services.Storage;

var persistence = new PersistenceManager();
var embedding = new OnnxEmbeddingService();
var index = new CognitiveIndex(persistence);

// "" is the legacy (single-tenant) partition. Pass a real tenant id to isolate.
const string tenant = "";

// Store
var vector = embedding.Embed("The capital of France is Paris");
var entry = new CognitiveEntry(
    "fact-1", vector, "default", "The capital of France is Paris", "facts", tenantId: tenant);
index.Upsert(entry);

// Search — tenantId is required as of 2.0
var results = index.Search(embedding.Embed("French capital"), "default", tenant, k: 5);

Documentation

DocDescription
First 5 MinutesStore, close, recall — the whole loop
Cheat SheetOne-page quick reference
MCP Tools ReferenceFull documentation for all 63 tools
ArchitectureSystem design, retrieval pipeline, data flow
Cognitive ConstitutionGoverned Core boundary, knowledge/provenance, learning, planning, assets, persistence, and current tenant limits
ServicesAll services with descriptions
InternalsRetrieval, quantization, persistence deep dive
Project StructureFile tree and module organization
AI Assistant SetupStep-by-step setup prompts for each tool
Sample PromptsPower prompts and usage patterns
BenchmarksIR quality results and mode selection guide
MRCR v2 BenchmarkLong-context A/B (full context vs. hybrid retrieval) via Claude CLI subscription
TestingTest coverage breakdown and current CI coverage
2.1.0 Release NotesRecall, reliability, safe upgrades and validation limits
2.0.0 Release NotesWhat changed in 2.0, why it is major, and how to migrate an embedding host
Tenant Isolation DesignPartitioning model, guarantees, and the 2.0 required-tenantId boundary
ChangelogFull release history

Build & Test

bash
cd mcp-engram-memory
dotnet build
dotnet test    # full suite, including slower MSA benchmark cases

Tech Stack

License

MIT