FocalMem MCP Server
# FocalMem
English | [简体中文](README.zh-CN.md)
**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).
---
## Architecture Overview
```text
+-------------------------------------------------------------------+
| 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`](https://docs.astral.sh/uv/) (recommended)
### Install & Initialize
```bash
# 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](README.zh-CN.md) includes complete Windows examples. [DSH MCP configuration](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/mcp/mcp-manager/README.md) · [Antigravity MCP configuration](https://antigravity.google/docs/mcp?tab=ide)
### Codex lifecycle hooks and offline notes
```text
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](https://learn.chatgpt.com/docs/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
```bash
# 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**:
```bash
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**:
```bash
export FOCAL_LLM_PROVIDER=gemini
export GEMINI_API_KEY="your-gemini-key"
export FOCAL_LLM_MODEL="gemini-2.5-flash"
```
---
## Running Tests
```bash
uv run pytest -v
```
## License
MIT License — see [LICENSE](LICENSE) for details.
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.