th-memory-mcp
memory-mcp
Langzeitgedächtnis-MCP-Server für OpenCode – speichert Präferenzen, Lektionen und Nutzungshistorie in einer einzigen lokalen SQLite-Datei (100 % lokal, keine externe API), damit die KI durch kontextbasiertes Lernen den Benutzer „merken und sich anpassen“ kann.
Status: v1.1.0 – alle 4 Phasen implementiert, Tests bestehen 70/70 Assertions (Smoke 53 + Capture 8 + Distill 9)
ไทย / Thai: README.th.md
Architecture
OpenCode ──┬─ Plugin learning-capture (Bun) ── auto-captures prompts/tool/error into DB
│ └─ injects profile back into context on compaction
└─ MCP memory-mcp (Node.js stdio) ── 9 tools read/write the same SQLite DB
▲
Global instructions (memory-protocol.md) teach the AI to use the toolsSiehe design.md für vollständige Details.
Related MCP server: MCP Vector Memory
Scripts
Command | Description |
| TypeScript nach |
| MCP-Server (stdio) von |
| regelbasiertes Distill: Interaktionen → Profilabschnitte + alte Daten bereinigen (env |
| End-to-End-Smoke-Test über JSON-RPC ( |
| teste capture-core (Geheimnisse filtern, deduplizieren, kürzen, SQL einfügen) |
| teste distill-core (Thai-Tokenisierung, Statistiken, Profilabschnitte, Bereinigung) |
Tools (9)
Tool | Description |
| Präferenz upserten (Kategorie+Schlüssel) – erneutes Speichern desselben Schlüssels erhöht die Konfidenz um 0,1 (max. 1,0) |
| Präferenzen + Lektionen (FTS5) + kürzlich passende Interaktionen durchsuchen. Vor dem Start einer neuen Aufgabe verwenden |
| Benutzerprofilübersicht: Profilabschnitte + Top-Präferenzen + 5 neueste Lektionen |
| eine aus einer Korrektur gelernte Lektion aufzeichnen (Situation / Fehler / Korrektur) |
| frühere Benutzeraufforderungen nach Stichwort durchsuchen (200-Zeichen-Ausschnitte pro Zeile) |
| eine Speicherzeile (Präferenz/Lektion/Interaktion) per ID löschen (+Typ verhindert ID-Kollision zwischen Tabellen) |
| Speicherstatistiken: Anzahl nach Art, DB-Größe, älteste/neueste Interaktion, Profilabschnitte |
| kürzliche rohe Interaktionen auflisten (nach Art filtern) – Rohmaterial für Smart Distill |
| Speicher als JSON unter |
Install with OpenCode
Fügen Sie den
mcp-Abschnitt ausopencode.example.jsonin Ihreopencode.jsonein (global oder auf Projektebene)Wichtig: Setzen Sie
MEMORY_DB_PATHauf DIESELBE Datenbankdatei für Server und Plugin (das Beispiel verwendet<ABSOLUTE_PATH>/memory-mcp/data/memory.db), sonst schreibt das Auto-Capture-Plugin in eine andere DB als die, die die KI liestSo legen Sie es fest (eine Option wählen):
definieren Sie es in der mcp-
environment(siehe Beispiel) – deckt nur den MCP-Server aboder setzen Sie es als System-/Benutzer-Umgebungsvariable (z. B.
setx MEMORY_DB_PATH "D:/path/to/memory.db"unter Windows) – deckt Server und Plugin ab, da das Plugin im selben Prozess wie OpenCode läuft
Fügen Sie die globalen Speicherregeln hinzu – fügen Sie zu
opencode.jsonhinzu:"instructions": ["C:/Users/<user>/.config/opencode/memory-protocol.md"](Beispielregelinhalt befindet sich in
AGENTS.memory.example.md– kann stattdessen auf Projektebene angehängt werden)(Optional) Auto-Capture-Plugin bereitstellen: Kopieren Sie
src/plugin/learning-capture.ts→~/.config/opencode/plugins/learning-capture.tsOpenCode neu starten (Konfiguration wird nur beim Start geladen)
Test: „Merken Sie sich, dass ich pnpm bevorzuge“ → eine neue Sitzung öffnen und zurückfragen
Daily usage
Die KI akzeptiert Thai und Englisch gleichermaßen – Sie können jederzeit ohne Vorwarnung die Sprache wechseln.
Thai | English | Effect |
"จำไว้ว่า..." | "Merken Sie sich, dass..." |
|
"สรุปความจำ" / "distill memory" | "Speicher zusammenfassen" / "Speicher destillieren" | Smart Distill – KI liest |
"ระบบความจำเป็นไงบ้าง" | "Wie ist mein Speicher?" / "Speicherstatus" |
|
"สำรองความจำ" | "Speicher exportieren" / "Speicher sichern" |
|
"ค้นประวัติ..." | "Verlauf durchsuchen..." |
|
"ลืม..." | "Vergessen..." |
|
Langzeitpflege: Führen Sie gelegentlich npm run distill aus, um Statistiken zusammenzufassen und Interaktionen zu bereinigen, die älter als 30 Tage sind.
data/ structure
data/
├── memory.db # SQLite (WAL mode) — main DB (+ .db-wal, .db-shm)
└── exports/ # JSON files from export_memory (writeable only in this dir)DB-Pfad kann über die Umgebungsvariable
MEMORY_DB_PATHüberschrieben werdenalles in
data/ist git-ignoriert
Available Tools
16 toolsconsolidateConsolidate memoriesA
Cluster similar memories via embedding similarity and optionally create derived/consolidated memories linked via 'derived_from'. Use during periodic consolidation.
Inputs: derive, userId, projectId, sessionId, +2 more.
export_memoryExport memory to JSONA
Export preferences, lessons, profile (and optionally raw interactions) to a JSON file under data/exports/. Only writes inside that directory. Returns the file path, size in bytes and a JSON preview.
Inputs: filename, includeInteractions.
extract_memoriesExtract memories from interactionsA
Scan recent captured interactions for memory-intent phrases and propose memory candidates (deterministic, no LLM). Dry-run by default; pass apply=true to create them (source=captured).
Inputs: kind, apply, limit, userId, +1 more.
forgetForget a memory entryA
Delete one memory row (preference, lesson or interaction) by id and sync the search index. Pass type when you know it (ids from remember are preference ids, from save_lesson are lesson ids).
Inputs: target_id (required), type.
get_contextGet assembled contextB
Assemble relevant memories for the current task via hybrid retrieval (+ optional memory-graph expansion), with token budgeting. Use to load memory into context before a task.
Inputs: limit, query, userId, maxTokens, +4 more.
get_profileGet user profileA
Get the distilled user profile: profile sections, top preferences by confidence (max 15), and the 5 most recent lessons. Optional userId/sessionId/projectId scope the auto-projected memories; without them only GLOBAL memories are included.
Inputs: userId, projectId, sessionId.
get_recent_interactionsRecent interactionsA
List recently captured raw interactions (newest first) as [id] ts [kind] content lines. Optionally filter by kind. Use for auditing history or before distilling memory.
Inputs: kind, limit, sessionId.
import_memoryImport memoriesA
Import memories from a JSON array or a .json file inside data/exports/. Validates type, dedupes against existing memories, and never overwrites active memory blindly. Dry-run by default; pass apply=true to insert.
Inputs: file, json, apply, userId, +1 more.
link_memoryLink two memoriesC
Create a typed relationship between two memories in the graph (supports/contradicts/supersedes/derived_from/related_to/caused_by/depends_on).
Inputs: relation (required), sourceId (required), targetId (required).
memory_statsMemory statisticsA
Summarize memory usage: interaction counts by kind, preference/lesson totals, DB file size, oldest/newest interaction timestamps, and profile sections.
Inputs: no named parameters.
merge_memoryMerge memoriesA
Merge a duplicate/near-duplicate memory into a canonical one. The source becomes superseded and provenance is recorded in metadata.merged_from.
Inputs: sourceId (required), targetId (required).
recallRecall memoryA
Search preferences + lessons via full-text index, plus recent matching interactions. Use before starting a new task.
Inputs: topic (required), limit.
rememberRemember preferenceA
Save or update a user preference (category+key upsert). Re-saving the same key increases confidence by 0.1 (cap 1.0). Returns the row id for forget().
Inputs: key (required), value (required), category (required).
save_lessonSave lessonA
Record a lesson learned from a correction: what situation, what mistake, what is the correct way. Call immediately after the user corrects your work.
Inputs: mistake (required), situation (required), correction (required).
search_historySearch prompt historyA
Search past user prompts (kind='prompt') by keyword. Returns timestamped snippets truncated to 200 chars each.
Inputs: query (required), limit, sessionId.
update_memoryUpdate a memoryA
Update mutable fields (summary/importance/confidence/valid_from/valid_until/metadata) in place. If content changes, a superseding memory is created by default (set supersede=false to edit in place).
Inputs: id (required), content, summary, metadata, +5 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 16 tools
Most tools target distinct actions and memory types, but retrieval is split across recall, get_context, get_profile, and search_history, and remember vs update_memory has some conceptual overlap. The descriptions clarify these boundaries, but an agent may still hesitate over which retrieval tool to use first.
Most names follow a clear snake_case verb_noun pattern such as save_lesson, get_profile, link_memory, and update_memory. A few exceptions like remember, recall, forget, consolidate, and memory_stats deviate from that pattern but remain readable and predictable enough.
At 16 tools the set is slightly on the heavy side, but each tool covers a meaningful part of a sophisticated memory lifecycle: capture, retrieval, curation, graph operations, import/export, and stats. It does not feel padded, though a smaller surface could reduce cognitive load.
The tool surface covers the full memory lifecycle: creation via remember/save_lesson/extract/import, retrieval via recall/get_context/profile/history, updates, deletion, linking, merging, consolidation, export, and stats. No obvious CRUD or lifecycle gap remains for the stated memory-management purpose.
Maintenance
Related MCP Connectors
Persistent memory for Claude Code and Cursor. Stop re-explaining your project every session.
Persistent cross-session memory shared by Codex, Claude Code, ChatGPT, and other AI agents.
Shared memory for coding agents. Stop re-explaining your codebase every session.
Long-term memory for AI assistants. Isolated per-user storage, recall across conversations.
Related MCP Servers
- -licenseNot gradedqualityNot gradedmaintenanceProvides persistent local memory functionality for AI assistants, enabling them to store, retrieve, and search contextual information across conversations with SQLite-based full-text search. All data stays private on your machine while dramatically improving context retention and personalized assistance.3-
- AlicenseNot gradedqualityNot gradedmaintenanceProvides AI coding agents with persistent, long-term memory through local semantic search and SQLite storage. It enables agents to save and retrieve architectural decisions or project context across different conversation sessions without requiring cloud services.MIT
- AlicenseAqualityDmaintenanceProvides persistent cross-session memory and full-text search for AI coding assistants, storing project context, decisions, and preferences while enabling searchable access to conversation history via local SQLite.81MIT
- AlicenseAqualityBmaintenanceProvides AI coding assistants with persistent memory storage using a local SQLite database. Enables tools to remember project details, notes, and relationships across sessions to maintain context and reduce repetitive explanations.174MIT