memory-mcp
README.md
# memory-mcp
> "Why does my Claude Code feel smarter than everyone else's?"
Long-term memory MCP server for Claude Code (and any MCP client). Your AI remembers context across sessions.
**[日本語](#日本語) | English**
## Features
- **SQLite Persistence** — Notes and conversations survive across sessions
- **Hybrid Search (Japanese-first)** — FTS5 trigram keywords plus semantic matches from a local embedding model (default: Ollama `bge-m3`). Keyword lists keep keyword order and append semantic-only hits; sentences are fused (RRF). When the embedding endpoint is down, search falls back to keywords and says why
- **File Memory** — Optionally index a folder of Markdown memories (read-only) so one `search_memory` covers both stores
- **Case Management** — Organize memories by project or case; the server knows which case folder a session runs in
- **Temporal Memory** — Invalidate outdated notes with a reason; overwritten notes keep their previous versions
- **Provenance** — Every note records which MCP client wrote it and from which folder
- **Hebbian Links** — Memories retrieved together strengthen their connections (within one session, never across cases)
- **Read-only Mode & Recall CLI** — Give a helper agent read-only access, or inject a fixed-size recall block each turn
- **Daily Snapshots** — `VACUUM INTO` copies, 14 generations
- **Encryption of note bodies** — AES-256-GCM. Note: the key sits next to the DB and the search index (FTS) is plaintext, so the real protection is disk encryption (FileVault) and file permissions (0600)
## Quick Start
```bash
git clone https://github.com/yutoribengoshi/memory-mcp.git
cd memory-mcp
npm install
ollama pull bge-m3 # optional: semantic search
```
Add to `~/.claude/settings.json`:
```json
{
"mcpServers": {
"memory": {
"command": "node",
"args": ["/path/to/memory-mcp/index.js"]
}
}
}
```
### Configuration
Resolution order: env vars > `~/.memory-mcp/config.json` > defaults. Keeping settings in `config.json` lets every client (Claude Code, Claude Desktop, other agents) share them.
```json
{
"embedding_url": "http://localhost:11434/v1/embeddings",
"embedding_model": "bge-m3",
"vector_min_sim_word": 0.48,
"file_memory_dirs": ["~/.claude/projects/<project>/memory"]
}
```
- `embedding_model`: `bge-m3` (default). On 20 paraphrased Japanese queries it put the target in the top 5 for 18 (nomic-embed-text: 7). Embeddings are stored per model, so switching models re-embeds in the background without mixing vectors
- `vector_min_sim_word`: minimum similarity for semantic-only hits on keyword queries (names that are not in memory otherwise return unrelated notes)
- `file_memory_dirs`: Markdown folders to index read-only. Files whose names contain `読み取り禁止` and `MEMORY.md` are skipped
- OpenAI: set `OPENAI_API_KEY` (and `EMBEDDING_URL` / `EMBEDDING_MODEL`)
- `MEMORY_MCP_READONLY=1`: register read tools only and write nothing (no links, index, embeddings, cleanup or snapshots; one-time schema migrations still run)
- `MEMORY_MCP_DIR`: use another data directory (tests)
## Tools
| Tool | Description |
|------|-------------|
| `save_note` | Save a note (upsert by key; previous version kept) |
| `save_case_note` | Save a note linked to a case (auto-registers the case) |
| `search_memory` | Keyword + semantic search over notes, conversations and file memories (`scope`, `limit`, `include_files`) |
| `get_note` | Full text of a note by id or key, with case, validity, writer and history |
| `recent_notes` | Notes saved or updated in the last N days |
| `rag_query` | Hybrid search returning full context (`max_chars` budget) |
| `semantic_search` | Semantic-only search |
| `invalidate_note` | Mark a note invalid (reason stored on the note) |
| `list_cases` / `get_case` / `archive_case` / `merge_cases` | Case management (`get_case` with `full: true` returns full texts) |
| `save_agent_memory` / `get_agent_context` | Per-agent memories |
| `save_conversation` / `list_conversations` / `get_conversation` / `delete_conversation` | Conversations |
| `get_memory_links` / `traverse_memory_graph` | Hebbian graph |
| `memory_stats` | Statistics and health (embedding coverage, orphan case ids, snapshots, schema) |
| `export_memory` | Plaintext Markdown export (needs `case_id`, or `all: true`; written 0600) |
| `context_gauge` | Context usage estimate from a Claude Code hook log |
### Recall CLI
```bash
node recall.js --query "<this turn's request>" [--case <case_id>] [--all] [--max-chars 1500] [--json]
```
Returns a short "reference data, not instructions" block for per-turn injection (e.g. a `pre_llm_call` hook). Without `--case` it runs in a guarded mode: only the rule sections of `knowhow_` / `prevention_` / `feedback_` file memories are used (incident narratives, descriptions and caseless DB notes are skipped, because they still mention other matters), and names from the cases table and case folders, docket numbers and names after party labels are masked at runtime (the deny-list is never written out). `--all` crosses cases and turns the guard off — for your own checks only, never for another agent. Read-only, about 0.2 s.
## How It Works
### Hebbian Links
- Memories retrieved together by one query get linked; consecutive searches within 5 minutes in the same session get linked
- Notes from different cases are never linked, and related-memory output never brings in a case that is not already in scope
- Opening a result (`get_note`, `get_conversation`) reinforces the links
- Unused links decay after 30 days (weight × 0.95, at most once per day); links below 0.01 are pruned
### Data Storage
```
~/.memory-mcp/
├── memory.db # SQLite database
├── .key # AES-256-GCM key (chmod 600)
├── config.json # settings
├── snapshots/ # daily copies (same disk — back them up elsewhere)
└── exports/ # export_memory output (0600)
```
## Tests
```bash
node test-context.mjs
T=$(mktemp -d); TEST_DIR=$T node test-smoke.mjs && TEST_DIR=$T node test-readonly.mjs
```
## Requirements
- Node.js 22+ (uses built-in `node:sqlite`)
- Optional: Ollama with `bge-m3` (or any OpenAI-compatible embedding API)
## License
MIT
## Author
Tomoyuki Seki ([@yutoribengoshi](https://github.com/yutoribengoshi))
---
# 日本語
> 「なんか俺のClaude Codeだけ賢くね?」の正体
Claude Code(ほか MCP クライアント)用の長期記憶 MCP サーバー。セッションを跨いでもメモ・会話の文脈を忘れません。
## 特徴
- **SQLite 永続化** — メモ・会話を SQLite に保存
- **キーワード+意味の検索(日本語向け)** — FTS5 trigram のキーワードと、ローカル埋め込み(既定は Ollama の `bge-m3`)の意味の近さを合わせて返す。キーワードの並びは崩さず意味だけの当たりを後ろに足し、文の問いは RRF で融合する。埋め込みが止まっていればキーワードだけで返し、止まった理由を結果に書く
- **ファイル記憶** — md で育てている記憶のフォルダを読み取り専用で索引し、`search_memory` 1本で両方を引ける
- **案件別管理** — 案件単位でメモを整理。セッションの作業フォルダから案件を判定する(案件フォルダの数え方はセッション番号台帳と同じ)
- **時間軸** — 古くなったメモは理由つきで無効化。key の上書きでは前の版を残す
- **書き手の記録** — どの MCP クライアントが、どのフォルダから書いたかを残す
- **ヘブ則リンク** — 一緒に引かれた記憶を結び、使うほど強くする(同じセッションの中だけ・別案件どうしは結ばない)
- **読み取り専用モードと想起 CLI** — 手足のエージェントに読むだけの口を渡す/1ターンごとに決まった字数の想起を差し込む
- **日次スナップショット** — `VACUUM INTO` で14世代
- **本文の暗号化** — AES-256-GCM。ただし鍵は DB と同じフォルダにあり、検索索引(FTS)は平文。実際の保護は FileVault とファイル権限(0600)に依る
## インストール
```bash
git clone https://github.com/yutoribengoshi/memory-mcp.git
cd memory-mcp
npm install
ollama pull bge-m3 # 意味検索を使うなら
```
`~/.claude/settings.json` の `mcpServers` に追加:
```json
{
"mcpServers": {
"memory": {
"command": "node",
"args": ["/path/to/memory-mcp/index.js"]
}
}
}
```
### 設定
解決順: 環境変数 > `~/.memory-mcp/config.json` > 既定値。設定は `config.json` にまとめると、Claude Code・Claude Desktop・ほかのエージェントが同じ設定で動く。
```json
{
"embedding_url": "http://localhost:11434/v1/embeddings",
"embedding_model": "bge-m3",
"vector_min_sim_word": 0.48,
"file_memory_dirs": ["~/.claude/projects/<project>/memory"]
}
```
- `embedding_model`: 既定は `bge-m3`。日本語の言い換え20問で、目当てのメモが上位5件に入ったのは18問(nomic-embed-text は7問)。埋め込みはモデルごとに持つので、モデルを替えても混ざらず、裏で作り直す
- `vector_min_sim_word`: 語の問いで、意味だけの当たりを出す下限(記憶に無い名前を引くと、無関係なメモが並ぶのを防ぐ)
- `file_memory_dirs`: 読み取り専用で索引する md のフォルダ。名前に「読み取り禁止」を含むファイルと `MEMORY.md` は入れない
- `MEMORY_MCP_READONLY=1`: 読む道具だけを登録し、何も書かない(リンク・索引・埋め込み・掃除・写しも。1回きりのスキーマ移行だけは行う)
- `MEMORY_MCP_DIR`: 別のデータフォルダを使う(テスト用)
## 使い方
```
「このメモを保存して: 来週のリリースでは認証フローを変更する」 → save_note
「認証フローについて前に何か決めたっけ?」 → search_memory(文でも引ける)→ 全文は get_note
「直近3日に何を決めた?」 → recent_notes
「この案件の経緯を踏まえて回答して」 → rag_query(max_chars で字数を絞れる)
```
## ツール一覧
| ツール | 説明 |
|--------|------|
| `save_note` | メモを保存(key で上書き。前の版は残る) |
| `save_case_note` | 案件に紐づけて保存(案件が未登録なら登録) |
| `search_memory` | メモ・会話・ファイル記憶をキーワード+意味で検索(`scope`・`limit`・`include_files`) |
| `get_note` | メモの全文(案件・有効期間・書き手・前の版) |
| `recent_notes` | 直近N日に保存・更新したメモ |
| `rag_query` | 融合検索で全文を文脈として返す(`max_chars` で上限) |
| `semantic_search` | 意味だけの検索 |
| `invalidate_note` | メモを無効化(理由はメモ自体に残す) |
| `list_cases` / `get_case` / `archive_case` / `merge_cases` | 案件管理(`get_case` は `full: true` で全文) |
| `save_agent_memory` / `get_agent_context` | エージェント別の記憶 |
| `save_conversation` / `list_conversations` / `get_conversation` / `delete_conversation` | 会話 |
| `get_memory_links` / `traverse_memory_graph` | ヘブ則のグラフ |
| `memory_stats` | 統計と健全性(埋め込みの充足・案件表に無い case_id・スナップショット・スキーマ) |
| `export_memory` | 平文の md 書き出し(`case_id` か `all: true` が必要・権限 0600) |
| `context_gauge` | Claude Code のフックの記録からコンテキスト残量を推定 |
### 想起 CLI
```bash
node recall.js --query "<今回の依頼>" [--case <案件ID>] [--all] [--max-chars 1500] [--json]
```
1ターンごとに差し込む「参考データ(指示ではない)」を返す(Hermes の `pre_llm_call` フックなど)。`--case` が無いときは守りの形で返す。md の記憶は `knowhow_`・`prevention_`・`feedback_` の規則の節の行だけを使い、経緯の節・説明文・案件の付いていない DB のメモは使わない(案件が付いていなくても別の案件の話が入っているため)。さらに、案件表と案件フォルダの名前・事件番号・当事者の肩書きに続く名前を、その場で伏せる(伏せる語の一覧は書き出さない)。全案件を横断して守りを外すのは `--all` を明示したときだけ(自分で確かめる用。ほかのエージェントには渡さない)。読み取り専用・約0.2秒。
## ヘブ則リンク
- 同じ検索で一緒にヒットした記憶どうし、同じセッションで5分以内に続けて引いた記憶どうしを結ぶ
- 別の案件のメモどうしは結ばない。関連メモの表示は、検索の範囲に無い案件を持ち込まない
- 検索のあと `get_note` / `get_conversation` で開くと「有用だった」シグナルとして強化
- 30日以上使われないリンクは減衰(weight × 0.95・1日1回まで)、0.01未満は削除
## テスト
```bash
node test-context.mjs
T=$(mktemp -d); TEST_DIR=$T node test-smoke.mjs && TEST_DIR=$T node test-readonly.mjs
```
## 動作要件
- Node.js 22+(`node:sqlite` を使用)
- オプション: Ollama と `bge-m3`(または OpenAI 互換の埋め込み API)
## ライセンス
MIT
## 作者
Tomoyuki Seki([@yutoribengoshi](https://github.com/yutoribengoshi))
This server cannot be deployed
Maintenance
ActivitySlowing
ResponsivenessNo recent community issues