Skip to main content
Glama
FocalMem MCP Server

FocalMem MCP Server

by kannazuki114

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

  1. 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.

  2. 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 normalized snippet_hash.

    • When edits shift line numbers, pointer_hydrate verifies the new location against the original fingerprint and anchors before saving it.

  3. Active Forgetting Valve (supersede & Conflict Guard)

    • Explicitly deprecates obsolete ideas via memory_supersede, filtering superseded and forgotten nodes out of default retrieval to prevent context rot.

    • Performs bidirectional constraint/polarity conflict detection against L1_PINNED rules and surfaces warnings at session bootstrap.

  4. 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).

  5. Cross-Platform & Zero External DB Dependencies

    • Powered by single-file SQLite (WAL + FTS5) with trigram / escaped LIKE CJK+ASCII hybrid search.

    • Standard MCP v2 (stdio) server + unified focal CLI + 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.12

  • uv (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-routing

Note: Running single-project setup (focal init --client ...) initializes .focal/focal.db and activates hooks immediately. When using --workspace-routing with lazy hooks, a fresh project remains untouched until its first write (memory_commit, memory_ingest, or focal 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 --write

Review 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-legacy

MCP Tools & Resources

The standard stdio MCP server (focal mcp, or focal mcp --workspace-routing for global plugins) exposes:

Tool / Resource

Purpose

memory_bootstrap

Load L1_PINNED invariants, open conflicts, budget-trimmed L2_GIST cards, and superseded guardrails (zero-side-effect if DB is absent).

graph_query

Hybrid FTS5 + escaped LIKE + N-hop causal graph query returning gists and pointer IDs.

pointer_hydrate

Fetch exact source lines from disk (with line-shift/stretch self-healing and size caps) and boost node freshness.

memory_commit

Persist a new memory node with optional pointer, causal parent edge, and L1 conflict check (lazily initializes .focal/focal.db on first commit).

memory_pin

Promote an existing memory node to L1_PINNED and check L1 conflict invariants.

memory_forget

Mark an obsolete/noisy memory as forgotten (excluded from recall and dismisses linked open conflicts).

memory_ingest

Enqueue raw text or automatically chunked source files into the Dreamer queue (with optional immediate cycle).

memory_supersede

Atomically deprecate an obsolete decision and link its replacement via a SUPERSEDES edge.

memory_resolve_conflict

Mark an open conflict as resolved or dismissed.

dream_consolidate

Run a micro-sleep cycle (max_tasks batching, defaults to 10; deduplicate with access-count inheritance, decay L2->L3, audit pointers).

memory_export_snapshot

Render a clean Markdown handoff snapshot.

focal://l1-pinned

MCP Resource exposing the fixed-mode default project snapshot (text/markdown).

focal://snapshot/{project_id}

Parameterized MCP Resource template for fixed-mode multi-project snapshots.

All 11 MCP tools require an absolute project root as workspace_path in dynamic mode (--workspace-routing or FOCAL_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 -v

License

MIT License — see LICENSE for details.

Available Tools

8 tools
dream_consolidateC

执行微睡眠整理周期:消化队列、合并重复记忆、衰减降级冷门节点并修复漂移指针。

Inputs: project_id.

graph_queryB
Read-only

因果图谱检索:仅返回节点精简摘要与原文指针,默认隔离已被废止的旧方案。

Inputs: query (required), depth, limit, project_id, +1 more.

memory_bootstrapB
Read-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_snapshotC
Read-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

    B3.3/5.0

    Scored across 8 tools

    Disambiguation4/5

    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.

    Naming Consistency4/5

    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.

    Tool Count5/5

    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.

    Completeness4/5

    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

    ActivityMaintained
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to maintain persistent, local memory with retrieval-augmented search, knowledge graphs, and context surfacing, without any cloud dependencies.
      MIT
    • A
      license
      B
      quality
      C
      maintenance
      Enables 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.
      23
      3
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables 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