th-memory-mcp
memory-mcp
面向 OpenCode 的长期记忆 MCP 服务器——将偏好、经验教训和使用历史存储在单个本地 SQLite 文件中(100% 本地,无外部 API),使 AI 能够通过基于上下文的记忆学习来“记住并适应”用户。
状态: v1.1.0 — 全部 4 个阶段已实现,测试通过 70/70 断言(冒烟 53 + 捕获 8 + 蒸馏 9)
ไทย / Thai: README.th.md
架构
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 tools详见 design.md。
Related MCP server: MCP Vector Memory
脚本
命令 | 描述 |
| 编译 TypeScript → |
| 从 |
| 基于规则的蒸馏:交互 → 档案部分 + 修剪旧数据(环境变量 |
| 通过 JSON-RPC 的端到端冒烟测试( |
| 测试 capture-core(过滤机密、去重、截断、插入 SQL) |
| 测试 distill-core(泰语分词、统计、档案部分、修剪) |
工具(9)
工具 | 描述 |
| 更新或插入偏好(类别+键)——重新保存相同的键会使置信度增加 0.1(上限 1.0) |
| 搜索偏好 + 经验教训(FTS5)+ 最近匹配的交互。在开始新任务前使用 |
| 用户档案概览:档案部分 + 热门偏好 + 最近 5 条经验教训 |
| 记录从纠正中学到的经验教训(情况 / 错误 / 纠正) |
| 按关键词搜索过去的用户提示(每行 200 字符片段) |
| 按 id 删除一条记忆记录(偏好/经验教训/交互)(+类型防止跨表 id 冲突) |
| 记忆统计:按类型计数、数据库大小、最早/最新交互、档案部分 |
| 列出最近的原始交互(按类型过滤)——智能蒸馏的原料 |
| 将记忆导出为 JSON,仅限 |
使用 OpenCode 安装
将
opencode.example.json中的mcp部分合并到你的opencode.json(全局或项目级别)重要: 为服务器和插件设置
MEMORY_DB_PATH为同一个数据库文件(示例使用<ABSOLUTE_PATH>/memory-mcp/data/memory.db),否则自动捕获插件会写入与 AI 读取不同的数据库如何设置(任选其一):
在 mcp 的
environment中定义(见示例)——仅覆盖 MCP 服务器或者将其设置为系统/用户级环境变量(例如在 Windows 上使用
setx MEMORY_DB_PATH "D:/path/to/memory.db")——同时覆盖服务器和插件,因为插件与 OpenCode 在同一进程中运行
附加全局记忆规则——添加到
opencode.json:"instructions": ["C:/Users/<user>/.config/opencode/memory-protocol.md"](示例规则内容位于
AGENTS.memory.example.md——也可以附加在项目级别)(可选)部署自动捕获插件:将
src/plugin/learning-capture.ts复制到~/.config/opencode/plugins/learning-capture.ts重启 OpenCode(配置仅在启动时加载)
测试:“记住我喜欢 pnpm” → 打开新会话并询问
日常使用
AI 可以互换接受泰语和英语——你可以随时切换语言,无需警告。
泰语 | 英语 | 效果 |
"จำไว้ว่า..." | "记住..." |
|
"สรุปความจำ" / "distill memory" | "总结记忆" / "蒸馏记忆" | Smart Distill — AI 读取 |
"ระบบความจำเป็นไงบ้าง" | "我的记忆怎么样?" / "记忆状态" |
|
"สำรองความจำ" | "导出记忆" / "备份记忆" |
|
"ค้นประวัติ..." | "搜索历史..." |
|
"ลืม..." | "忘记..." |
|
长期维护:偶尔运行 npm run distill 来总结统计信息并修剪超过 30 天的交互。
data/ 结构
data/
├── memory.db # SQLite (WAL mode) — main DB (+ .db-wal, .db-shm)
└── exports/ # JSON files from export_memory (writeable only in this dir)数据库路径可以通过
MEMORY_DB_PATH环境变量覆盖data/中的所有内容都被 git 忽略
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