Personal Fact Source MCP
by liuzhaowei1
README.md
# Personal Fact Source MCP (`personal-fact-mcp`)
[English](README.md) | [简体中文](README_CN.md)
A local, model-agnostic **Model Context Protocol (MCP)** server that decouples your personal Markdown knowledge/memory vault from any specific AI coding agent harness (Claude Code, OpenCode, Codex, Cursor, Antigravity, Reasonix, etc.).
---
## Hand This Repo to Your AI Agent (Recommended)
You do **not** need to configure this server by hand. Paste this prompt into your AI Agent (Claude Code, OpenCode, Codex, Cursor, Antigravity, etc.) along with this repository URL or local path:
> **Copy-paste prompt for your Agent:**
>
> `Please read AGENT_SETUP.md in this repository (<repo-url-or-local-path>) and help me deploy, configure, and connect Personal Fact Source MCP to your environment. Ask me for my preferences before editing any config files or starting services.`
Your Agent will automatically:
1. Detect your OS / topology (native Windows, macOS, Linux, or WSL + Windows);
2. Ask you 4 concise setup questions (existing Markdown vault vs. built-in `starter_vault`, primary language / embedding model, port, and client write permissions);
3. Install dependencies, generate `config.local.toml`, run `memory_health`, and start the server;
4. Consult your Harness's official MCP docs to register `fact-source` and (with your approval) add the global protocol instructions.
Already have the server running and want to connect a **second** Agent client? Give that new Agent `AGENT_SETUP.md` and tell it to run **Phase 2 only**.
---
## Core Design Principles
1. **Markdown Files Remain the Single Source of Truth**
- The server is purely a local retrieval and write-governance layer pointed at your Markdown directory via `config.local.toml`.
- Zero vendor lock-in and zero proprietary database: stop or delete the server at any time and your Markdown notes stay 100% intact.
2. **Code-Driven Hybrid Retrieval — Never LLM-as-Selector**
- Instead of dumping an index into every prompt and paying a "book-selection token tax" for the LLM to guess which files to read, relevance scoring and budget truncation run deterministically in code (~25–35ms on CPU):
- **Specificity-weighted exact triggers** (CJK substring + ASCII whole-word boundaries; short generic words are damped against false positives)
- **Chunk-level BM25** (`##` H2 section chunking + frontmatter metadata chunk)
- **Local CPU ONNX embeddings** (`BAAI/bge-small-zh-v1.5` or `BAAI/bge-small-en-v1.5` via `fastembed`, with atomic chunk-content-keyed disk cache)
- **1-hop `[[wikilink]]` graph expansion** (filtering fenced/inline code false positives)
- **Asymmetric gating**: specific triggers pass reliably; generic triggers require lexical/semantic corroboration; zero-trigger rescue in `precise` mode uses three calibrated gates (dual-channel BM25+dense co-verification, high-confidence pure-vector rescue, or 1-hop active-seed BM25 corroboration for short follow-ups) without hurting cold-start silence.
3. **Dual-Layer Context Supply & Scenario Modes**
- **Resident Persona Layer (`memory_bootstrap`)**: compact always-on operational directives (`DIRECTIVES.md`) and `⚠️` behavioral constraints injected once per session.
- **Incremental Factual Layer (`memory_sync`)**: turn-by-turn verbatim message retrieval with version-aware per-session deduplication (`NO_NEW_CONTEXT` with silence reason when nothing new is relevant; auto-re-injects if a file changes on disk) and `reset_compact=True` support after context compaction.
- **Two Modes**: `precise` (minimal sufficient context set) vs. `panoramic` (broad synthesis with higher 1-hop graph weight, relaxed thresholds, and larger char budget).
4. **Out-of-Band Write Governance (Immune to Client `yolo` Mode)**
- Default-readonly client whitelist (`readonly` vs. opt-in `approvable_write`), optional Bearer token identity binding (`[auth.tokens]` / `stdio --client-id`), mandatory full-file `memory-writing-rules` read gate (hash-bound), static YAML & full `INDEX.md` contract validation, TOCTOU baseline verification + cross-process commit lock + multi-file rollback journal, and a **native desktop Tkinter red/green Diff approval dialog** backed by an auto-paired `X-Approval-Token` daemon channel (zero unauthenticated approval endpoints).
---
## MCP Tools (5-Tool Surface)
| Tool | Purpose |
|---|---|
| `memory_bootstrap(client_id, mode)` | Initialize a session and return the resident persona layer + `session_id` |
| `memory_sync(session_id, user_message, mode?, reset_compact?)` | Pass the verbatim user message for incremental code-driven recall |
| `memory_read(session_id, target, section?)` | Resolve `[[wikilink]]` pointers with tiered outline expansion (>8K archives); unlocks write gate on full `memory-writing-rules` read |
| `memory_propose(session_id, action, target, summary, ...)` | Governed `create` / `update` / `patch` with static checks + desktop Diff approval + atomic UTF-8/LF write & index hot-reload |
| `memory_health()` | Audit `INDEX.md` 3-column contract, dead `[[wikilink]]` pointers, and unreachable orphan files |
---
## Paper artifact (v0.5.0)
[Reviewer guide and paper-to-artifact map](REPRODUCIBILITY.md) · [Public results](benchmarks/results/) · [Windows approval example](examples/approval_dialog.png)
| Paper section | Artifact | Reference result |
|---|---|---|
| §4 engine, five-tool contract and tests | `src/fact_mcp/`, `tests/`, `config.example.toml` | 17 core modules, 6,170 physical lines. WSL 34 passed; Windows 32 passed, 2 skipped |
| §4.3 governed write | [Attended Windows evidence](benchmarks/results/windows_attended.json) | Both the proposed Markdown and its INDEX row were verified after approval |
| §5.2 public retrieval | `benchmarks/run_paper_track_a.py`, `run_dev_retuned_ablation.py` | Curated precise Strict-F1 95.7%. Bare reconstruction 73.7%; historical cloud report 81.4% |
| §5.2 private replay | [Aggregate counts](benchmarks/results/track_b_aggregates.csv) | 83.3% Strict-F1 on 38 historical sessions; private inputs withheld |
| §5.3 scaling | `benchmarks/run_scale_bench.py`, `profile_query_stages.py` | 1,000-doc real ONNX reference P50 25.11 ms. A separate synthetic-vector profile is provided for 5,000 docs |
| §5.4 model Pilot | `benchmarks/pilot/`, `benchmarks/results/` | 51 units per model. Push condition: 11/12 tasks passed and 14/14 pre-action fact deliveries on each model |
The supported desktop approval UI for this release is Windows. WSL can use the Windows approval front end. Retrieval can run on other desktop platforms. Headless deployments can select read-only governance. The generated-code Pilot grader requires Linux bubblewrap; native macOS and Windows were not validated for the full paid-model workflow.
## Manual Quickstart
Out of the box, `config.example.toml` points to `./starter_vault` so you can run and test immediately.
### Linux / macOS / WSL
```bash
uv venv .venv
uv pip install -e .
cp config.example.toml config.local.toml
# Foreground
.venv/bin/python -m fact_mcp.server --config config.local.toml --transport streamable-http
# Or background daemon via helper script
bash scripts/server_ctl.sh start
```
> **WSL + Windows users**: To enable the native Windows Diff approval window from a WSL-hosted server (zero extra ports, zero firewall issues), also run in a **normal interactive Windows PowerShell/Terminal** (`WinSta0\Default`; never from a sandboxed IDE agent runner or Windows service):
> ```powershell
> powershell.exe -NoProfile -ExecutionPolicy Bypass -File ".\scripts\approval_daemon_ctl.ps1" -Action start
> ```
### Native Windows (PowerShell)
```powershell
uv venv .venv
uv pip install -e .
Copy-Item config.example.toml config.local.toml
# Start background server (native Windows spawns the Tkinter Diff window directly — no separate approval daemon needed)
powershell.exe -NoProfile -ExecutionPolicy Bypass -File ".\scripts\server_ctl.ps1" -Action start
```
### Stdio Transport (for stdio-only MCP clients)
```bash
.venv/bin/python -m fact_mcp.server --config config.local.toml --transport stdio
```
---
## Repository Layout
- `src/fact_mcp/` — MCP server, hybrid retriever, index/wikilink parser, write governance, and desktop Diff approval UI
- `starter_vault/` — Zero-PII starter Markdown vault (`DIRECTIVES.md`, `INDEX.md`, `memory-writing-rules.md`, linked notes, and a >8K archive example)
- `AGENT_SETUP.md` / `AGENT_SETUP_CN.md` — Agent-First self-deployment & onboarding playbooks
- `scripts/` — Portable `server_ctl.sh`, `server_ctl.ps1`, and WSL-to-Windows `approval_daemon_ctl.ps1`
- `tests/` — Self-contained `pytest` suite running against `starter_vault/`
## License
Apache-2.0 — see [LICENSE](LICENSE).
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues