th-memory-mcp
memory-mcp
OpenCode용 장기 기억 MCP 서버 — 기본 설정, 교훈, 사용 기록을 단일 로컬 SQLite 파일에 저장합니다(100% 로컬, 외부 API 없음). 이를 통해 AI는 컨텍스트 기반 학습을 통해 사용자를 "기억하고 적응"할 수 있습니다.
상태: v1.1.0 — 4단계 모두 구현, 테스트 70/70 어서션 통과 (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 tools전체 세부 사항은 design.md를 참조하세요.
Related MCP server: MCP Vector Memory
Scripts
Command | Description |
| TypeScript를 |
|
|
| 규칙 기반 distill: 상호작용 → 프로필 섹션 + 오래된 데이터 정리 (env |
| JSON-RPC를 통한 엔드투엔드 스모크 테스트 ( |
| capture-core 테스트 (비밀 정보 필터링, 중복 제거, 잘라내기, SQL 삽입) |
| distill-core 테스트 (태국어 토큰화, 통계, 프로필 섹션, 정리) |
Tools (9)
Tool | Description |
| 기본 설정 upsert (카테고리+키) — 같은 키를 다시 저장하면 신뢰도가 0.1 증가 (최대 1.0) |
| 기본 설정 + 교훈 (FTS5) + 최근 일치 상호작용 검색. 새 작업을 시작하기 전에 사용하세요. |
| 사용자 프로필 개요: 프로필 섹션 + 상위 기본 설정 + 최근 교훈 5개 |
| 수정에서 배운 교훈 기록 (상황 / 실수 / 수정) |
| 키워드로 과거 사용자 프롬프트 검색 (행당 200자 스니펫) |
| ID로 메모리 행 하나 삭제 (기본 설정/교훈/상호작용) (+type은 테이블 간 ID 충돌 방지) |
| 메모리 통계: 종류별 개수, DB 크기, 가장 오래된/최신 상호작용, 프로필 섹션 |
| 최근 원시 상호작용 나열 (종류로 필터링) — Smart Distill의 원료 |
| 메모리를 |
Install with OpenCode
opencode.example.json의mcp섹션을opencode.json(전역 또는 프로젝트 수준)에 병합하세요.중요: 서버와 플러그인 모두에 대해
MEMORY_DB_PATH를 동일한 데이터베이스 파일로 설정하세요 (예제는<ABSOLUTE_PATH>/memory-mcp/data/memory.db를 사용합니다). 그렇지 않으면 자동 캡처 플러그인이 AI가 읽는 DB와 다른 DB에 씁니다.설정 방법 (하나 선택):
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을 선호한다는 것을 기억해" → 새 세션을 열고 다시 물어보세요.
Daily usage
AI는 태국어와 영어를 모두 상호 교환적으로 받아들입니다 — 언제든지 경고 없이 언어를 전환할 수 있습니다.
Thai | English | Effect |
"จำไว้ว่า..." | "기억해..." |
|
"สรุปความจำ" / "distill memory" | "메모리 요약" / "메모리 디스틸" | Smart Distill — AI가 |
"ระบบความจำเป็นไงบ้าง" | "내 메모리는 어때?" / "메모리 상태" |
|
"สำรองความจำ" | "메모리 내보내기" / "메모리 백업" |
|
"ค้นประวัติ..." | "기록 검색..." |
|
"ลืม..." | "잊어..." |
|
장기 관리: 가끔 npm run distill을 실행하여 통계를 요약하고 30일보다 오래된 상호작용을 정리하세요.
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 경로는
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