Th Memory Mcp

io.github.worakorn-prince由 GitHub 帳號 worakorn-prince 發布v2.4.3更新於 Nov 8, 2026

Local long-term memory MCP server (SQLite) for AI coding agents — OpenCode, Claude Code, Cursor

發布方自己的服務:Memory.fit

已驗證STDIO僅桌面知識與記憶開發者工具

概覽

AI 產生的概覽

以本機 SQLite 為後端的長期記憶伺服器,讓程式開發代理能跨工作階段記住偏好、經驗教訓與過往互動。

可以做什麼
  • 儲存並更新偏好、經驗教訓與個人檔案,並以關鍵字或混合檢索召回
  • 在權杖預算內取得與任務相關的上下文,可選擇記憶圖譜擴展
  • 搜尋過往提示詞與近期互動,並從中擷取或提煉記憶候選
  • 管理記憶生命週期:關聯、合併、更新、取代、整併與刪除單筆記錄
  • 檢視統計資訊,並以 JSON 檔案匯出或匯入記憶
適用情境
適合希望程式開發代理在工作階段之間延續偏好、修正與習慣,且不依賴任何雲端服務的情況。最適用於單一機器上的單一使用者,想要一個私有、以檔案為基礎的記憶庫,並在多個支援 MCP 的工具間共用。
執行需求
透過 npm 套件 th-memory-mcp 以 stdio 在本機執行,需要 Node.js(僅限已修補的 22、24 或 26 版本,Node 20 不受支援)以及用於安裝與建置的 npm。不需要帳號、API 金鑰或外部服務。需設定 MEMORY_DB_PATH 指向 SQLite 檔案,伺服器與自動擷取外掛必須使用相同路徑。
安裝前請注意
資料庫是未加密的一般 SQLite 檔案,任何能存取檔案系統的人都能讀取,敏感資料請仰賴全碟加密。沒有身分驗證或授權:呼叫端提供的使用者、工作階段與專案 ID 會被直接信任,因此不要將同一伺服器或資料庫共用給不受信任的使用者。工具可以刪除、合併、取代與匯入記錄,匯入與擷取僅在明確確認後才會寫入。請使用已修補的 Node.js 版本,因為 npm audit 不涵蓋 Node 核心漏洞。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Th Memory Mcp,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

th-memory-mcp

Requirements

  • Node.js 22.23.4+, 24.22.1+, or 26.12.1+ — patched releases only; the server uses Node-only APIs (better-sqlite3 native build, import.meta.url). Node.js 20 is EOL and unsupported. CI tests the minimum patched version of each supported line (22/24/26).
  • npm — for npm install, npm run build, npm test. No external services, accounts, or API keys — everything lives in a single local SQLite file.
  • OpenCode — the host that loads the MCP server and the auto-capture plugin (any build with MCP over stdio + plugins). The plugin uses node:sqlite on OpenCode Desktop/Node 22.5+ and falls back to bun:sqlite on the Bun-based CLI.
  • OS: Windows / macOS / Linux — cross-platform (Node); Windows: set MEMORY_DB_PATH with setx, macOS/Linux: export in your shell profile.

Security: Use a patched Node.js release — check your runtime with npx is-my-node-vulnerable. npm audit covers npm dependencies only, not Node.js core CVEs.

Audit: Independently smoke-tested by AddonAudit on v2.4.1 — an automated test, not a security guarantee; the one high advisory it found was fixed in 2.4.2, and fresh installs from 2.4.3 onward report 0 critical/high advisories.

Quick Start

Fastest path: npm run quickstart (after cloning) builds, wires opencode.json/opencode.jsonc, deploys the plugin, and sets MEMORY_DB_PATH — the steps below are the manual equivalent. npm alternative: npm install -g th-memory-mcp (or npx th-memory-mcp) and point mcp.command to th-memory-mcp instead of dist/index.js (plugin still from this repo; not on GitHub Packages anymore).

bash
# 1. Clone and buildgit clone https://github.com/worakorn-prince/th-memory-mcp.gitcd th-memory-mcp && npm install && npm run build# 2. Share one DB between the server and the pluginsetx MEMORY_DB_PATH "$PWD/data/memory.db"      # Windows (PowerShell)# export MEMORY_DB_PATH="$PWD/data/memory.db"  # macOS/Linux — add to your shell profile (~/.zshrc)
  1. Merge this into ~/.config/opencode/opencode.json (replace <REPO> with the absolute clone path; ready-made block in opencode.example.json). MEMORY_DB_PATH must be the SAME file for server and plugin — a system/user-level env var covers both; environment below covers the server only. Example rules: AGENTS.memory.example.md (attachable at project level).
json
{ "instructions": ["<REPO>/AGENTS.memory.example.md"],  "mcp": { "memory": { "type": "local", "command": ["node", "<REPO>/dist/index.js"], "enabled": true, "environment": { "MEMORY_DB_PATH": "<REPO>/data/memory.db" } } } }
  1. (Optional) Auto-capture: deploy the dual-mode plugin to a directory (OpenCode V2 only auto-discovers local plugins from a folder) — src/plugin/learning-capture.ts → ~/.config/opencode/plugins/learning-capture/index.ts
  2. Restart OpenCode (config loads at startup only), then try: "Remember that I prefer pnpm" → new session → "What package manager do I prefer?"

The plugin works in both modes: OpenCode V2 calls the default export's id + setup(ctx) (domain hooks for prompt/tool/compaction/failure events), while V1 (1.18.29+) calls the same default export's server(), which returns the legacy hook object. One file, no runtime import of @opencode/plugin (types only), so it loads under both Node and Bun.

If startup reports Failed to load plugin ... Received protocol 'bun:' or the plugin is silently ignored on V2, you are on an older install layout. Re-deploy the current src/plugin/learning-capture.ts to ~/.config/opencode/plugins/learning-capture/index.ts; a legacy ~/.config/opencode/plugins/learning-capture.ts is renamed to .bak-<timestamp> by npm run quickstart (never deleted). It loads node:sqlite first and only falls back to bun:sqlite under Bun.

Architecture

OpenCode loads the plugin learning-capture (dual-mode V1/V2, Node/Bun) — auto-captures prompt/tool/error into the DB, injects the profile on compaction — and the MCP server th-memory-mcp (Node stdio) exposing the 16 tools on that same SQLite DB; global rules (memory-protocol.md) teach the AI to use them.

Why th-memory-mcp?

  • Context-based learning, not fine-tuning — captures your preferences, corrections, and habits, then recalls them next session; no data leaves your machine.
  • 100% local & private — one SQLite file, no cloud, no external API; secrets (api_key=, password:, token) filtered before storage.
  • Low overhead & resilient — tool calls are capped (latency < 10 ms, bounded output) and degrade gracefully if the DB is unavailable.
  • Open & extensible — MIT licensed; 16 documented tools, rule-based distill, auto-capture plugin; Node + better-sqlite3 only (no extra native extensions).

Highlights

  • Structured memory — preferences with confidence scoring plus lesson records (situation → mistake → correction), not just flat facts.
  • Lifecycle, temporal & conflict-aware — states (active/stale/superseded/archived), confidence/importance/salience scoring, per-type decay, validity intervals for point-in-time truth and supersession chains; duplicate/contradiction resolution keeps both sides of ambiguous evidence.
  • Hybrid retrieval — get_context blends FTS5 keyword search with dependency-free lexical fuzzy matching (hashed n-gram similarity, 512-dim FNV-1a) via RRF fusion, then assembles a token-budgeted context with optional memory-graph expansion.
  • Consolidation — clusters similar memories into derived ones with full provenance (derived_from links).
  • First-class Thai / i18n — Thai-aware tokenization in distill; Thai and English accepted interchangeably.

Works with other harnesses

A standard MCP server: 16 tools anywhere MCP-over-stdio works; all harnesses share one SQLite file via MEMORY_DB_PATH. Auto-capture needs a hook runtime (built into OpenCode, bridged for Claude Code).

FeatureOpenCodeClaude CodeQwen CodeCodexCursor
16 MCP tools✅✅✅✅✅
Auto-capture (background)✅ plugin✅ hooks⚠️ adapter❌ manual❌ Rules
Profile injection✅ compaction✅ UserPromptSubmit❌ get_profile❌ get_profile❌ get_profile
Lexical fuzzy matching✅ (v2.0)✅ (v2.0)✅ (v2.0)✅ (v2.0)✅ (v2.0)

Scripts

CommandDescription
npm run buildcompile TypeScript → dist/
npm startrun the MCP server (stdio) from dist/index.js
npm run distillinteractions → profile sections + prune old data (RETENTION_DAYS, default 30)
npm testbuild + full suite (46 files, 148 tests: 147 pass, 1 skip)
node test/<name>.test.mjsrun one suite: capture, distill, lifecycle, temporal, conflict, retrieval, graph, context, consolidation, benchmark, security
node test/smoke.mjsend-to-end smoke test over JSON-RPC (16 tools)

Tools (16)

ToolDescription
rememberupsert preference (category+key); re-save +0.1 confidence (cap 1.0)
recallsearch preferences + lessons (FTS5) + recent matching interactions — run before a new task
get_profileprofile sections + top preferences + 5 most recent lessons
save_lessonrecord a lesson from a correction (situation / mistake / correction)
search_historysearch past prompts by keyword (200-char snippets)
forgetdelete one row (preference/lesson/interaction) by id (+type avoids cross-table id clash)
memory_statscounts by kind, DB size, oldest/newest interaction, profile sections
get_recent_interactionsrecent raw interactions (filter by kind) — Smart Distill feedstock
export_memoryexport to JSON under data/exports/ only (filename auto-sanitized)
get_contexttask-relevant memories via hybrid retrieval (+ graph expansion), token-budgeted
consolidatecluster similar memories via embedding similarity; optionally create derived memories linked via derived_from
link_memorytyped link between two memories: supports/contradicts/supersedes/derived_from/related_to/caused_by/depends_on
merge_memorymerge a duplicate into canonical memory (source superseded; provenance in metadata.merged_from)
update_memoryupdate fields in place, or create a superseding memory when content changes (supersede=false edits in place)
import_memoryimport from JSON (validates type, dedupes, never overwrites blindly); dry-run by default, apply=true to insert
extract_memoriesscan recent interactions for memory-intent phrases, propose candidates (deterministic, no LLM); dry-run by default, apply=true to create (source=captured)

CLI (th-memory)

BinaryEntryPurpose
th-memory-mcpdist/index.jsMCP server (stdio) — the 16 tools above
th-memorydist/cli.jszero-dep local CLI (same DB via MEMORY_DB_PATH)

Usage: th-memory [--db <path>] [--json] [--plain] <command> [options] — per-command help via th-memory <command> --help. highlight/recall --highlight: matches underlined (ESC[4m) on a color TTY, else [mem]…[/mem] markers (piped, --plain, --json).

FlagEffect
--db <path>use this SQLite file (sets MEMORY_DB_PATH)
--jsonprint JSON {ok,data} instead of plain text
--plain / --no-colordisable colors
-h, --help / -V, --versionshow help / print version
CommandUsage
rememberremember --category <c> --key <k> --value <v|-> — save a preference (--value - reads from stdin)
recallrecall <topic> [--limit <n>] [--highlight] — search memory
forgetforget <id> [--type <t>] — delete by id (t: memory|preference|lesson|interaction)
exportexport [--include-interactions] [--filename <n>] — export to data/exports/*.json
importimport (--file <p>|--json <s>) [--apply] [--user-id <id>] — import backup (dry-run by default)
statsstats — memory statistics
profileprofile — distilled user profile
historyhistory [--query <q>] [--limit <n>] — search past prompts (no query = recent prompts)
recentrecent [--limit <n>] [--kind <k>] — recent interactions (k: prompt|tool_call|error)
highlighthighlight [text...] -q <topic> [--limit <n>] — highlight topic matches (empty text = stdin pipe)
bash
th-memory remember --category coding_pref --key package_manager --value pnpmth-memory recall pnpm --limit 5echo "I prefer pnpm for installs" | th-memory highlight -q pnpm

Daily usage

The AI accepts Thai and English interchangeably; long-term care: npm run distill summarizes stats and prunes interactions older than 30 days.

  • "Remember that..." → remember — save a preference
  • "Summarize memory" / "distill memory" → Smart Distill — AI reads get_recent_interactions, finds patterns, saves insights itself
  • "How is my memory?" / "memory status" → memory_stats
  • "Export memory" / "backup memory" → export_memory
  • "Search history..." → search_history · "Forget..." → forget

data/ structure

data/├── memory.db          # SQLite (WAL mode) — main DB (+ .db-wal, .db-shm); path overridable via MEMORY_DB_PATH└── exports/           # JSON files from export_memory (writeable only in this dir)# everything in data/ is git-ignored

Known Limitations

  • No encryption at rest — data/memory.db is plain, unencrypted SQLite (WAL mode, better-sqlite3); "100% local & private" means no cloud/network exfiltration, not encrypted at rest — anyone with filesystem access can read it. For sensitive data: OS full-disk encryption (BitLocker / FileVault / LUKS) or an opt-in SQLCipher build (native rebuild + key management); no in-code encryption by default (src/db/index.ts documents this).
  • Single-user, no auth layer (Batch B-3) — userId / sessionId / projectId are caller-supplied with no authentication or authorization check inside the server; scope isolation (retrieval, get_context, graph, consolidate, link_memory, merge_memory) binds only to caller-sent values, so any scope is readable/writable by passing a different id. Suitable for a single-user local process; do not share one server/DB across untrusted users without an auth layer in front enforcing the correct userId (projectId / sessionId). No auth is built in by design.

License

MIT © 2026 worakorn-prince — see LICENSE for the full text.

來源:README.md,提交 7047183

工具

16

remember

Remember preference

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().

輸入參數key必填value必填category必填

recall

Recall memory

Search preferences + lessons via full-text index, plus recent matching interactions. Use before starting a new task.

輸入參數limittopic必填

get_profile

Get user profile

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.

輸入參數userIdprojectIdsessionId

save_lesson

Save lesson

Record a lesson learned from a correction: what situation, what mistake, what is the correct way. Call immediately after the user corrects your work.

輸入參數mistake必填situation必填correction必填

search_history

Search prompt history

Search past user prompts (kind='prompt') by keyword. Returns timestamped snippets truncated to 200 chars each.

輸入參數limitquery必填sessionId

forget

Forget a memory entry

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).

輸入參數typetarget_id必填

memory_stats

Memory statistics

Summarize memory usage: interaction counts by kind, preference/lesson totals, DB file size, oldest/newest interaction timestamps, and profile sections.

無需輸入參數。

get_recent_interactions

Recent interactions

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.

輸入參數kindlimitsessionId

export_memory

Export memory to JSON

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.

輸入參數filenameincludeInteractions

get_context

Get assembled context

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.

輸入參數limitqueryuserIdmaxTokensprojectIdsessionIdincludeGraphincludeHistory

consolidate

Consolidate memories

Cluster similar memories via embedding similarity and optionally create derived/consolidated memories linked via 'derived_from'. Use during periodic consolidation.

輸入參數deriveuserIdprojectIdsessionIdthresholdminClusterSize

merge_memory

Merge memories

Merge a duplicate/near-duplicate memory into a canonical one. The source becomes superseded and provenance is recorded in metadata.merged_from.

輸入參數sourceId必填targetId必填

update_memory

Update a memory

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).

輸入參數id必填contentsummarymetadatasupersedevalidFromconfidenceimportancevalidUntil

import_memory

Import memories

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.

輸入參數filejsonapplyuserIdtrusted

extract_memories

Extract memories from interactions

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).

輸入參數kindapplylimituserIdsessionId

版本歷史

7
  1. v2.4.3最新Nov 7, 2026
  2. v2.4.1Oct 29, 2026
  3. v2.4.0Oct 23, 2026
  4. v2.3.5Oct 21, 2026
  5. v2.3.4Oct 21, 2026
  6. v2.3.2Oct 18, 2026
  7. v2.0.0Sep 16, 2026

評分

已滿足適用檢查項的 90%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分
  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具必需15 分
  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分

其他 Memory 整合