FocalMem MCP Server
This MCP server manages hierarchical AI memory with pinned constraints, causal graph retrieval, self-healing source pointers, conflict handling, consolidation, and snapshot export.
Bootstrap focused context: load L1 core rules, unresolved conflict alerts, L2 summaries, and superseded guardrails.
Query the causal memory graph by text with depth/limit controls, optionally including superseded nodes.
Hydrate exact source snippets from stored pointers, with line-drift self-healing and freshness updates.
Commit new memory nodes with tier, kind, tags, file/line pointers, causal parent edges, rationale, and surprise score, while checking L1 conflicts.
Supersede obsolete memories and link replacements through a causal chain.
Resolve or dismiss L1 constraint conflict alerts.
Run Dreamer micro-sleep consolidation to process queued memories, deduplicate, decay/demote cold nodes, and audit pointers.
Export a clean Markdown handoff snapshot for cross-session or web AI use.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@FocalMem MCP Server Save this decision as an L1 pinned constraint and point it to README.md lines 1-10"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
FocalMem
English | 简体中文
A cross-platform, local-first hierarchical context & causal pointer memory engine for AI agents (MCP + CLI).
Instead of stuffing million-token histories into the context window, FocalMem applies multi-level CPU caching (L1 / L2 / L3) and human memory consolidation to AI workflows: keeping core constraints pinned at full resolution, compressing older turns into high-density gists, storing raw source on disk behind self-healing line pointers, isolating superseded dead ends, and running offline background consolidation ("micro-sleep").
Key Capabilities
Three-Tier Visual Focal Context (
L1 / L2 / L3)L1_PINNED: Core constraints and invariant decisions, always loaded on bootstrap and immune to decay.L2_GIST: High-density semantic summaries managed by surprise weight and LRU access decay.L3_ARCHIVE: Cold-storage index; raw text stays on disk without polluting active attention.
Causal Graph + Self-Healing Source Pointers
Graph edges (
causes,depends_on,supersedes,contradicts,related_to) link memory nodes without carrying bulky raw text.Pointers store
uri,start_line:end_line,anchor_text,anchor_offset, and a normalizedsnippet_hash.When edits shift line numbers,
pointer_hydrateverifies the new location against the original fingerprint and anchors before saving it.
Active Forgetting Valve (
supersede& Conflict Guard)Explicitly deprecates obsolete ideas via
memory_supersede, filteringsupersededandforgottennodes out of default retrieval to prevent context rot.Performs bidirectional constraint/polarity conflict detection against
L1_PINNEDrules and surfaces warnings at session bootstrap.
Offline "Micro-Sleep" Consolidation (
Dreamer)Atomic lease-protected background task queue (
dream_queue), L2 deduplication by matching kind, title, and content, L2-to-L3 decay demotion, and batch pointer health audits.Works zero-config with local heuristic rules, or upgrades automatically to lightweight LLM semantic distillation (supports OpenAI-compatible endpoints and native Google Gemini REST API).
Cross-Platform & Zero External DB Dependencies
Powered by single-file SQLite (WAL + FTS5) with
trigram/ escapedLIKECJK+ASCII hybrid search.Standard MCP v2 (
stdio) server + unifiedfocalCLI + one-click client adapters for Google Antigravity, Claude Code, Cursor, and Generic MCP clients (plus clean Markdown snapshot export for web chat UIs).
Related MCP server: Lians Agent Memory
Architecture Overview
+-------------------------------------------------------------------+
| AI Clients (Antigravity / Claude Code / Cursor) |
+-----------------------------+-------------------------------------+
| MCP v2 (stdio) / CLI Hooks
v
+-------------------------------------------------------------------+
| MCPServer (mcp_server.py) & CLI / Lifecycle Hooks (cli.py) |
+-----------------------------+-------------------------------------+
|
v
+-------------------------------------------------------------------+
| FocalEngine (engine.py) | Self-Healing Pointers (pointer.py) |
| FocalDreamer (dreamer.py)| SQLite WAL + FTS5 Core (db.py) |
+-------------------------------------------------------------------+Quick Start
Prerequisites
Python
>= 3.12uv(recommended)
Install & Initialize
# Clone the repository
git clone https://github.com/kannazuki114/focal-mem.git
cd focal-mem
# Sync dependencies
uv sync --dev
# Initialize memory store & generate client adapter config in your target project
uv run focal --workspace /path/to/your/project init --client antigravity
# Or for Claude Code / Cursor / Generic MCP:
uv run focal --workspace /path/to/your/project init --client claude
uv run focal --workspace /path/to/your/project init --client cursor
uv run focal --workspace /path/to/your/project init --client generic
# Add --portable to avoid hardcoding machine-local absolute paths
uv run focal --workspace /path/to/your/project init --client antigravity --portable
# Or run as a global dynamic-routing MCP server (lazily stores per-project .focal/focal.db via workspace_path)
uv run focal mcp --workspace-routingNote: Running single-project setup (
focal init --client ...) initializes.focal/focal.dband activates hooks immediately. When using--workspace-routingwith lazy hooks, a fresh project remains untouched until its first write (memory_commit,memory_ingest, orfocal commit) against the actual project root you open in your IDE.
Shared local memory across Codex, DeepSeek Harness, and Antigravity
Configure each client to run the same local executable over stdio with args = ["mcp", "--workspace-routing", "--allowed-roots", "<absolute-project-root>"]. In Codex use [mcp_servers.focal-mem]. In DeepSeek Harness add a stdio server to the profile's MCP settings. In Antigravity add it under mcpServers in the client MCP configuration. Pass the same absolute root as workspace_path on every call from that project and use the same namespace (default default). The Chinese quick start includes complete Windows examples. DSH MCP configuration · Antigravity MCP configuration
Codex lifecycle hooks and offline notes
focal --workspace <project> init --client codex --preview
focal --workspace <project> init --client codex
focal --workspace <project> init --client codex --uninstall
focal --workspace <project> note export <memory-id> --output decision.md
focal --workspace <project> note apply decision.md
focal --workspace <project> note apply decision.md --writeReview the project hooks with /hooks in Codex. FocalMem loads budgeted memory on session start and after compaction, and queues local transcript increments on PreCompact and Stop. Hook capture requires project-local opt-in. Codex Hooks
For offline editing, edit the body below the metadata comment. Relative paths resolve from the project root. Apply previews a diff by default and checks the project, memory state, and revision before writing. Body edits preserve the existing database schema. Editing an L1 rule checks it against active L1 and L2 memories in the same namespace. Re-export to a new file before the next edit after a successful write.
CLI Usage
# Inspect L1/L2/L3 counts, pending dream tasks, and open conflicts
uv run focal status
# Commit an L1 invariant constraint with a self-healing file pointer
uv run focal commit \
--title "Zero External DB" \
--content "Local runtime must remain single-file SQLite without Docker." \
--tier L1_PINNED \
--kind constraint \
--file README.md \
--lines 1-10
# Query the causal graph (returns compact gists and pointer IDs)
uv run focal search "SQLite" --depth 1
# Hydrate exact source lines on demand (triggers self-healing if lines shifted)
uv run focal hydrate ptr_xxxxxxxxxxxx --context 5 --max-lines 100 --max-chars 6000
# Supersede an obsolete decision (isolates old node from default recall)
uv run focal supersede mem_xxxxxxxxxxxx \
--title "Storage Engine Finalized" \
--content "Use SQLite WAL + FTS5 instead of external stores." \
--reason "Satisfies single-file constraint"
# Enqueue a file or text into the Dreamer queue and run offline consolidation
uv run focal ingest --file notes.md --run
uv run focal dream
# Export a clean Markdown handoff snapshot (for new sessions or web AI chats)
uv run focal export --snapshot --max-chars 10000
# Inspect or migrate projects from a legacy central global DB into per-project .focal/focal.db
uv run focal list-legacy
uv run focal --workspace /path/to/your/project migrate-legacyMCP Tools & Resources
The standard stdio MCP server (focal mcp, or focal mcp --workspace-routing for global plugins) exposes:
Tool / Resource | Purpose |
| Load |
| Hybrid FTS5 + escaped |
| Fetch exact source lines from disk (with line-shift/stretch self-healing and size caps) and boost node freshness. |
| Persist a new memory node with optional pointer, causal parent edge, and L1 conflict check (lazily initializes |
| Promote an existing memory node to |
| Mark an obsolete/noisy memory as |
| Enqueue raw text or automatically chunked source files into the Dreamer queue (with optional immediate cycle). |
| Atomically deprecate an obsolete decision and link its replacement via a |
| Mark an open conflict as |
| Run a micro-sleep cycle ( |
| Render a clean Markdown handoff snapshot. |
| MCP Resource exposing the fixed-mode default project snapshot ( |
| Parameterized MCP Resource template for fixed-mode multi-project snapshots. |
All 11 MCP tools require an absolute project root as
workspace_pathin dynamic mode (--workspace-routingorFOCAL_MEM_WORKSPACE_ROUTING=1). The argument is optional in fixed mode. In dynamic mode tools route to<workspace_path>/.focal/focal.db, and only write operations (memory_commit/memory_ingest) lazily initialize the project database.
memory_bootstrap and memory_export_snapshot accept a positive max_chars per call (default 8000). This budget covers memory entries and excludes JSON or Markdown formatting. Read-only queries keep a legacy schema intact. Opening the database through a write-capable tool upgrades it.
pointer_hydrate accepts positive max_lines and max_chars per call (defaults 200 and 12000). With a tight limit, the excerpt prioritizes the referenced text. The CLI exposes the same settings as --max-lines and --max-chars.
Optional LLM Configuration for Dreamer
Without any API key, Dreamer runs deterministically using local heuristic extraction, safeguards, deduplication, and pointer auditing. To enable semantic distillation via a lightweight LLM:
OpenAI-compatible endpoint:
export FOCAL_LLM_PROVIDER=openai export FOCAL_LLM_API_KEY="your-api-key" export FOCAL_LLM_BASE_URL="https://api.openai.com/v1" export FOCAL_LLM_MODEL="gpt-4o-mini"Google Gemini REST endpoint:
export FOCAL_LLM_PROVIDER=gemini export GEMINI_API_KEY="your-gemini-key" export FOCAL_LLM_MODEL="gemini-2.5-flash"
Running Tests
uv run pytest -vLicense
MIT License — see LICENSE for details.
Available Tools
8 toolsdream_consolidateC
执行微睡眠整理周期:消化队列、合并重复记忆、衰减降级冷门节点并修复漂移指针。
Inputs: project_id.
graph_queryBRead-only
因果图谱检索:仅返回节点精简摘要与原文指针,默认隔离已被废止的旧方案。
Inputs: query (required), depth, limit, project_id, +1 more.
memory_bootstrapBRead-only
开局对焦:获取 L1 核心铁律、未解决冲突警报、相关 L2 摘要卡及已废止禁区列表。
Inputs: l2_limit, max_chars, task_hint, project_id.
memory_commitC
写入新记忆节点(支持挂接原文指针与因果边,并自动检测与 L1 铁律的潜在冲突)。
Inputs: title (required), content (required), kind, tags, +9 more.
memory_export_snapshotCRead-only
导出一份纯净的跨会话交接快照 Markdown,方便粘贴至任意 AI 界面继续工作。
Inputs: max_chars, task_hint, project_id.
memory_resolve_conflictC
处理或关闭一条核心铁律冲突告警(action: resolved | dismissed)。
Inputs: conflict_id (required), action.
memory_supersedeB
主动遗忘阀:废止过时/错误的旧方案并建立因果替代链,立即将其踢出默认检索。
Inputs: new_title (required), new_content (required), old_memory_id (required), reason, +3 more.
pointer_hydrateC
按原文指针拉回高清片段(支持行号漂移自愈),并刷新对应记忆的活跃热度。
Inputs: pointer_id (required), context_lines.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
Each tool maps to a distinct operation in the memory lifecycle: write (memory_commit), forget (memory_supersede), conflict resolution, consolidation, retrieval (graph_query), raw fragment hydration (pointer_hydrate), session bootstrap, and export. The only mild overlap is between memory_bootstrap and graph_query, since both surface memory context, but their descriptions clarify that bootstrap is startup triage of laws/conflicts and graph_query is targeted causal search.
All names follow a consistent noun_verb structure (memory_commit, pointer_hydrate, dream_consolidate, graph_query). The noun prefix varies by subsystem (memory, pointer, dream, graph), which is slightly less uniform than a single namespace but remains predictable and readable.
Eight tools is well scoped for a memory server: enough to cover write, retrieval, conflict handling, consolidation, forgetting, and export without redundancy. Every tool appears to earn its place in the workflow.
The surface covers the core lifecycle: commit, supersede/forget, resolve conflicts, bootstrap context, query the graph, hydrate raw text, consolidate, and export a handoff snapshot. Minor gaps exist, such as direct memory editing or explicit tagging/listing operations, but these can be worked around via supersede and graph_query.
Maintenance
Related MCP Connectors
Persistent memory and knowledge graphs for AI agents. Hybrid search, context checkpoints, and more.
Persistent memory for AI agents. Semantic search, memory graph, W3C DID identity.
Governed local-first memory and continuity for AI agents — signed receipts, optional hosted lane.
Private-by-default, local-first memory/context/task orchestrator for MCP apps and agents.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to maintain persistent, local memory with retrieval-augmented search, knowledge graphs, and context surfacing, without any cloud dependencies.MIT

Lians Agent Memoryofficial
AlicenseAqualityCmaintenanceLocal-first bitemporal memory for AI agents with deterministic supersession, point-in-time recall, erasure proofs, and tamper-evident audit history.917Apache 2.0- AlicenseBqualityCmaintenanceEnables AI agents to maintain a local, event-sourced long-term memory with semantic retrieval, decision confidence checks, and proactive recalls, ensuring data never leaves the machine.233MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to automatically capture durable knowledge and retrieve only relevant, token-bounded context from a secure local-first long-term memory, with support for progressive disclosure, snapshots, health diagnostics, and background tasks.Apache 2.0