Longterm Memory

io.github.MarcelRoozekrans由 GitHub 帳號 MarcelRoozekrans 發布v1.6.1更新於 Oct 31, 2026

A fully local MCP server for long-term memory with semantic search

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

已驗證STDIO僅桌面資料庫知識與記憶

概覽

AI 產生的概覽

一個完全在本機執行的 MCP 伺服器,為助理提供具語意搜尋的長期記憶,資料存於 SQLite,向量在本機產生。

可以做什麼
  • 儲存、更新與刪除記憶,可附上標籤、重要度與記憶類型,並依內容雜湊去重
  • 以自然語言查詢進行語意搜尋,透過本機嵌入與餘弦相似度比對
  • 分頁列出所有記憶,或依類型、標籤、建立日期範圍篩選
  • 查看記憶庫統計,例如總數與資料庫位置
  • 手動建立資料庫備份,並將所有記憶匯出為 JSON
適用情境
適合希望助理跨工作階段記住事實、決策與偏好,又不願把資料送往雲端服務的情境。也適合想讓所有專案與用戶端共用同一個本機記憶庫,或透過設定為單一專案隔離記憶庫的使用者。
執行需求
以本機 stdio 程序執行,可透過 npx 或全域 npm 安裝;需要 Node.js 22.13 或更新版本。不需帳號、API 金鑰或雲端服務。嵌入模型(約 30MB)首次使用時下載一次並快取在本機。選用環境變數可設定資料庫路徑、備份路徑與召回行為。
安裝前請注意
刪除全部記憶無法復原,且預設資料庫由機器上所有專案與用戶端共用。記憶會寫入磁碟與 JSON 備份,因此移除私有片段、拒絕疑似密鑰的內容防護相當重要;此防護可透過環境變數關閉或擴充,且不會重新掃描舊記憶。從 1.4 或更早版本升級時,須先停止所有執行中的工作階段,以免覆蓋較新的資料。

安裝

在 SourceWeft 中

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

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

其他 MCP 客戶端

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

README

[LongtermMemory-MCP]

LongtermMemory-MCP

[codecov] [GitHub Sponsors]

A fully local MCP server that gives AI agents persistent, semantic long-term memory — without any cloud dependencies.

Inspired by mcp-mem0, but runs 100% on your machine:

Featuremcp-mem0This project
StoragePostgreSQL / SupabaseSQLite (Node's built-in node:sqlite)
EmbeddingsOpenAI APILocal transformer (all-MiniLM-L6-v2)
Vector searchCloud vector DBIn-process cosine similarity
LLM dependencyOpenAI / OpenRouter / OllamaNone
SetupDatabase + API keysnpx longterm-memory-mcp

Tools

Core

ToolDescription
save_memoryStore text with auto-generated semantic embedding, tags, importance, and type
search_memoryFind relevant memories using natural language queries (cosine similarity)
update_memoryModify an existing memory's content, metadata, tags, importance, or type
delete_memoryRemove a specific memory by ID
delete_all_memoriesWipe all memories (irreversible)
get_all_memoriesList all stored memories (paginated)
memory_statsGet count and database location

Search

ToolDescription
search_by_typeFilter memories by category (general, fact, preference, conversation, task, ephemeral)
search_by_tagsFind memories matching any of the provided tags
search_by_date_rangeFind memories created within a specific date range (ISO format)

Maintenance

ToolDescription
create_backupManually trigger a database backup with JSON export

Quick Start

Claude Code Plugin (recommended)

Install via the Claude Code marketplace — this sets up both the MCP server and a companion skill that teaches Claude how to use memory effectively:

/plugin marketplace add MarcelRoozekrans/LongtermMemory-MCP/plugin install longterm-memory@longterm-memory-marketplace

This automatically:

  • Configures the MCP server (no manual JSON editing), pinned to the plugin's version: a plugin update also updates the server
  • Adds the automatic recall hook
  • Installs the long-term-memory skill (Claude learns to recall context at session start, save insights after tasks, and deduplicate memories)

Use with npx (no install needed)

bash
npx longterm-memory-mcp

npx keeps running the version it cached first and does not look for updates. To move to a new release, name the version, as in npx -y [email protected], or use @latest, which checks the registry on every start.

Or install globally

bash
npm install -g longterm-memory-mcplongterm-memory-mcp

Or from source

bash
git clone https://github.com/MarcelRoozekrans/LongtermMemory-MCP.gitcd LongtermMemory-MCPnpm install && npm run buildnpm start

Configuration

Claude Code

If you installed via the plugin marketplace, the MCP server is already configured. For manual setup, add to your MCP settings (~/.claude/settings.json or project .claude/settings.json):

json
{  "mcpServers": {    "longterm-memory": {      "command": "npx",      "args": ["-y", "longterm-memory-mcp"]    }  }}

Claude Desktop

Add to claude_desktop_config.json:

json
{  "mcpServers": {    "longterm-memory": {      "command": "npx",      "args": ["-y", "longterm-memory-mcp"]    }  }}

Agent Instructions

The repo includes agent instructions that teach AI agents how to use memory effectively (automatic recall, save patterns, deduplication):

FilePurpose
skills/long-term-memory/SKILL.mdSelf-contained skill — auto-loaded by Claude Code plugin, can be referenced from any MCP client

Database Location

By default, memories are stored in a shared, user-scoped location:

~/.longterm-memory-mcp/memories.db

This means every project and every MCP client shares the same memory pool — you save a memory in one project and it's available everywhere.

Several sessions can use the same database at once. Each server process reads and writes the shared file directly (SQLite in WAL mode), so a memory saved in one session is visible to every other session right away, and no session overwrites what another saved. Requires Node.js 22.13 or later.

Databases from older releases open unchanged. A database from v1.0–1.3, which has no schema_meta table, is migrated in place with all its memories kept; a copy named memories.db.pre-migration-<timestamp>.bak is written next to it first.

Upgrading from 1.4 or earlier: stop every running session that uses the old version before starting one with the new version. Older releases keep the whole database in memory and rewrite the file on each save, so an old process left running would overwrite what new sessions saved.

Per-project database

To isolate memories for a specific project, set the MEMORY_DB_PATH environment variable:

json
{  "mcpServers": {    "longterm-memory": {      "command": "npx",      "args": ["-y", "longterm-memory-mcp"],      "env": {        "MEMORY_DB_PATH": "/path/to/project/memories.db"      }    }  }}

Memory Types

Each memory has a memory_type that determines how it's categorized and how quickly it decays:

TypeDescriptionDecay half-life
generalDefault catch-all60 days
factVerified information120 days
preferenceUser/project preferences90 days
conversationConversation context45 days
taskTask-related notes30 days
ephemeralShort-lived context10 days

Tags & Importance

  • Tags: Categorize memories with string tags (e.g. ["auth", "backend"]). Search with search_by_tags.
  • Importance (1–10): Controls how resistant a memory is to decay. Default is 5. Higher importance decays more slowly.
  • Protected tags: Memories tagged with core, identity, or pinned skip decay entirely.

Decay & Reinforcement

Memories decay over time to keep the store relevant:

  • Decay: Each memory type has a half-life (see table above). Importance decreases exponentially based on time since last access, with a floor that prevents full deletion.
  • Reinforcement: Every time a memory is accessed via search, its importance increases by +0.1 (up to a max of 10). Frequently accessed memories stay important.
  • Lazy evaluation: Decay is calculated on access, not on a timer — no background processes needed.

Content Deduplication

Memory content is hashed (SHA-256) on save. If identical content already exists, the save is rejected with a reference to the existing memory ID. This prevents duplicate entries automatically.

Content Guard

Memories end up in the database and in its JSON backups, so content is filtered before it is stored:

  • <private> spans are removed. Text inside <private>…</private> is never stored, embedded or hashed. An unclosed <private> removes everything after it. Content that is empty once the spans are removed is rejected.
  • Secrets are rejected. save_memory and update_memory refuse content, metadata values and tags that look like a secret. The error names the pattern that matched and never the value.
PatternMatches
private-keyPEM / OpenSSH / PGP private key headers (certificates are allowed)
github-tokenghp_, gho_, ghu_, ghs_, ghr_ and github_pat_ tokens
api-keysk-… style API keys
aws-access-keyAKIA… / ASIA… access key ids
jwtJSON Web Tokens
slack-tokenxoxb-, xoxp- and similar Slack tokens
secret-assignmentrandom-looking values after password=, token:, secret=, api_key=, KEY= and similar. References ($VAR, ${{ … }}), placeholders (<…>), calls and plain words are allowed

Configure it with environment variables:

json
{  "mcpServers": {    "longterm-memory": {      "command": "npx",      "args": ["longterm-memory-mcp"],      "env": {        "MEMORY_GUARD_DISABLE": "jwt,slack-token",        "MEMORY_GUARD_EXTRA_PATTERNS": "{\"internal-host\": \"\\\\b[a-z0-9-]+\\\\.corp\\\\.example\\\\b\"}"      }    }  }}
  • MEMORY_GUARD_DISABLE: a comma-separated list of pattern names to turn off, or all for every built-in pattern. <private> spans are removed either way. An unknown name stops the server at startup.
  • MEMORY_GUARD_EXTRA_PATTERNS: a JSON object of extra patterns to reject, as name → regular expression.

The guard applies to new saves and updates only. Memories stored before it existed are not rescanned.

Automatic Recall

The Claude Code plugin ships a UserPromptSubmit hook that recalls memories without the agent having to ask. On the first prompt of each session it searches with the prompt text and adds the best matches to the context as a short list:

Long-term memories that may be relevant (longterm-memory; search_memory gives the full text):- [2026-10-22 fact] pkill -f <pattern> also matches the agent's own shell … (id 31ece450-…)
  • Once per session: the hook keeps a marker file per session id in recall-sessions/ next to the database. Later prompts in that session cost one node start, about 30 ms, and no search.
  • Project: the hook takes the project name from the session's working directory. A memory that names the project in its content, tags or metadata ranks a little higher. The name is not part of the search text: a short prompt would then match on the project name alone.
  • Cheap when it misses: nothing is injected when no memory reaches the threshold, and the block never exceeds the token cap.
  • Content guard: a stored memory that the guard rejects, such as one saved before the guard existed, is never injected.
  • Never blocks a prompt: errors go to stderr and the prompt continues.
  • Pinned version: the hook runs npx longterm-memory-mcp@<plugin version> recall --hook, so a cached older copy is never used. The plugin's MCP server is pinned the same way.

Configure it with environment variables in your Claude Code settings (env in ~/.claude/settings.json). The hook runs in Claude Code's environment, not the MCP server's, so a custom MEMORY_DB_PATH has to be set there too.

VariableDefaultMeaning
MEMORY_RECALL_ENABLEDtruefalse turns the hook off
MEMORY_RECALL_K5at most this many memories (1–50)
MEMORY_RECALL_THRESHOLD0.5minimum cosine similarity (-1 to 1)
MEMORY_RECALL_MAX_TOKENS400cap on the injected block, estimated at 4 characters per token
MEMORY_RECALL_STATE_DIR<database dir>/recall-sessionswhere the once-per-session markers live; markers older than 30 days are removed

Recall CLI

The hook calls the recall subcommand, which also works on its own:

bash
npx longterm-memory-mcp recall "how do we deploy the stack"npx longterm-memory-mcp recall --k 3 --threshold 0.4 --project docker "deploy"

It prints the same list the hook injects, or No relevant memories found. on stderr. Options: --k, --threshold, --max-tokens and --project (default: the current directory's name, "" for none). It does not create a database that does not exist yet. With --hook it reads a Claude Code UserPromptSubmit event from stdin and answers with additionalContext.

Backups

Backups are managed automatically and can also be triggered manually via the create_backup tool.

  • Auto-backup: Triggers every 24 hours or when the memory count reaches a multiple of 100.
  • Retention: The last 10 backups are kept; older ones are pruned automatically.
  • Format: Each backup is a timestamped directory containing a consistent snapshot of the SQLite database and a JSON export of all memories.
  • Location: ~/.longterm-memory-mcp/backups/ by default, or set MEMORY_BACKUP_PATH:
json
{  "mcpServers": {    "longterm-memory": {      "command": "npx",      "args": ["-y", "longterm-memory-mcp"],      "env": {        "MEMORY_BACKUP_PATH": "/path/to/backups"      }    }  }}

How It Works

  1. Save: Text is embedded locally using all-MiniLM-L6-v2 (384-dim vectors) and stored in SQLite alongside the raw content, metadata, tags, importance, and type. Content is deduplicated via SHA-256 hash.
  2. Search: Your query is embedded with the same model, then compared against every stored memory using cosine similarity. Results above the threshold are returned ranked by relevance. Accessed memories are reinforced automatically.
  3. Decay: Over time, unused memories lose importance based on their type's half-life. Protected and frequently accessed memories resist decay.
  4. Persist: Every change is written straight to the SQLite database on disk, so concurrent sessions share one consistent store. No background processes, no servers to maintain.

The embedding model (~30MB quantized) is downloaded once on first use and cached locally.

Architecture

src/                           — MCP server source  index.ts                     — Entry point (stdio server, or the `recall` subcommand)  paths.ts                     — Database and recall-state path resolution  cli.ts                       — `recall` subcommand, standalone and hook mode  recall.ts                    — Recall search, project ranking, guard filter, token-capped list  recall-session.ts            — Once-per-session markers for the recall hook  server.ts                    — MCP server factory + 11 tool definitions  memory-store.ts              — SQLite storage + vector search + decay integration  embeddings.ts                — Local embedding engine (Xenova/transformers)  decay.ts                     — DecayEngine (lazy decay, reinforcement, protected tags)  backup.ts                    — BackupManager (auto-backup, JSON export, pruning)  content-guard.ts             — Strips <private> spans, rejects secrets  types.ts                     — TypeScript interfaces (Memory, Embedder, config types)
hooks/                         — Claude Code plugin hooks  hooks.json                   — UserPromptSubmit → recall gate  recall-gate.mjs              — Dependency-free gate: runs the recall CLI once per session
skills/                        — Claude Code plugin skill  long-term-memory/SKILL.md    — Self-contained agent instructions + skill
.claude-plugin/                — Plugin & marketplace metadata  plugin.json                  — Plugin manifest  marketplace.json             — Marketplace manifestscripts/                       — Plugin launch helpers (plain Node, no dependencies)  launch-server.mjs            — Starts the MCP server pinned to the plugin version  plugin-package.mjs           — longterm-memory-mcp@<plugin version>.mcp.json                      — MCP server for working on this repo.vscode/mcp.json               — VS Code MCP server config

Benchmarks

Run with npm run bench. Results from an in-memory store using mock embeddings (isolates store/SQLite performance from model latency):

Cosine Similarity

OperationThroughputNotes
Single computation (384-dim)~4.2M ops/sMatches real embedding dimensions
128 dimensions~8.6M ops/s
768 dimensions~2.4M ops/s
1536 dimensions~1.3M ops/sScales linearly with dimensions

Memory Store Operations

OperationThroughputNotes
Save (single)~1,120 ops/sIncludes embed + SQLite insert + dedup check
Save 100 batch~18 ops/s~55ms per batch of 100
Save 1000 batch~0.3 ops/s~3.1s per batch of 1000
Update (content, re-embed)~155 ops/s
Update (metadata only)~344 ops/s2.2x faster than content update
Delete~469 ops/s

Search (semantic, at scale)

Store SizeOperationNotes
10 memoriessearch (limit=5)Full scan + cosine similarity per memory
100 memoriessearch (limit=5)
500 memoriessearch (limit=5)
1000 memoriessearch (limit=5)Linear scan — scales with store size

Decay Engine

OperationThroughput
Single decay computation~21M ops/s
Single reinforcement~25.7M ops/s
shouldProtect (tag check)~22M ops/s

Development

bash
npm install          # Install dependenciesnpm run build        # Compile TypeScriptnpm test             # Run all testsnpm run bench        # Run benchmarksnpm run test:watch   # Watch modenpm run test:coverage # Coverage report

Contributing

This project uses Conventional Commits and semantic-release for automated versioning.

Commit message format

<type>(<optional scope>): <description>
[optional body]
[optional footer(s)]
TypePurposeVersion bump
featNew featureMinor (0.x.0)
fixBug fixPatch (0.0.x)
docsDocumentation onlyNo release
styleFormatting, whitespaceNo release
refactorCode restructuringNo release
testAdding/updating testsNo release
choreMaintenance, depsNo release
ciCI/CD changesNo release

Breaking changes: Add ! after the type (e.g., feat!: remove deprecated API) or include a BREAKING CHANGE: footer. This triggers a major version bump.

Examples

bash
git commit -m "feat: add memory tagging support"git commit -m "fix: handle empty search query gracefully"git commit -m "feat!: change default database location"git commit -m "docs: update configuration examples"

Commit messages are validated locally via commitlint + husky git hooks. Non-conforming messages will be rejected.

Releases

Releases are fully automated. When commits are pushed to main:

  1. semantic-release analyzes commit messages
  2. Determines the next version (major / minor / patch)
  3. Generates release notes from commits
  4. Updates CHANGELOG.md
  5. Publishes to npm
  6. Creates a GitHub Release

No manual version bumps or tags needed.

Dependency Updates

Dependencies are managed automatically by Renovate. Patch and minor devDependency updates are auto-merged after CI passes. Major updates create PRs for manual review.

License

MIT

來源:README.md,提交 6e9dfad

工具

11

save_memory

Save information to long-term memory. The content will be embedded locally and indexed for semantic search. Use this to store facts, decisions, preferences, or any context worth remembering across sessions. Text inside <private>…</private> is removed before storing; content that looks like a secret (tokens, keys, passwords) is rejected.

輸入參數tagscontent必填metadataimportancememory_type

search_memory

Search long-term memory using semantic similarity. The query is embedded locally and compared against all stored memories using cosine similarity.

輸入參數limitquery必填threshold

get_all_memories

Retrieve all stored memories, ordered by most recent first. Results are paginated.

輸入參數limitoffset

update_memory

Update an existing memory. Can modify content (triggers re-embedding), metadata, tags, importance, or memory type.

輸入參數id必填tagscontentmetadataimportancememory_type

search_by_type

Search memories by category type (e.g. fact, preference, conversation). Returns memories ordered by importance.

輸入參數limitmemory_type必填

search_by_tags

Find memories that match any of the provided tags. Returns memories ordered by importance.

輸入參數tags必填limit

search_by_date_range

Find memories created within a specific date range. Use ISO date format.

輸入參數limitdate_todate_from必填

delete_memory

Delete a specific memory by its ID. Only delete when the user explicitly requests it or when a memory is confirmed outdated or incorrect.

輸入參數id必填

delete_all_memories

Delete ALL stored memories. This action is irreversible. Only use when the user explicitly asks to clear all memories.

無需輸入參數。

memory_stats

Get statistics about the memory store — total count and database location.

無需輸入參數。

create_backup

Create a manual backup of the memory database and export all memories as JSON.

無需輸入參數。

版本歷史

3
  1. v1.6.1最新Oct 31, 2026
  2. v1.6.0Oct 31, 2026
  3. v1.5.0Oct 22, 2026

評分

已滿足適用檢查項的 90%

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

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

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

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

其他 Memory 整合