Claude Code Memory 系統:建立持久的專案智慧
掌握 Claude Code 的 Memory MCP。學習如何建立跨 session 持久化的知識圖譜,實現真正的專案連續性與組織記憶。
2026 年 10 月 21 日更新: 依最新官方文件與
@modelcontextprotocol/server-memory2.0 版校正:MEMORY_FILE_PATH必須是絕對路徑(且改以 JSONL 儲存)、知識圖譜欄位是entityType/relationType、/memory-*指令是自訂 skills 而非內建指令,內建的系統則是 Claude Code 的 auto memory。
AI 助理最令人沮喪的一點就是 session 失憶症——每次對話都重新開始。Claude Code 現在內建了 auto memory:以檔案為基礎的記憶目錄,可在每個專案中跨 session 持久化;你還可以在其之上加一層 Memory MCP——一個可選的知識圖譜系統,提供結構化、可查詢的專案知識。
本指南涵蓋了建立持久專案智慧所需的一切知識。
問題:Session 失憶症
傳統 AI 工作流程會遭受 context 丟失的問題:
Session 1: "我們決定使用 Redis 做 caching 是因為..."
Session 2: "為什麼我們使用 Redis?"
Session 3: "我們應該換成 Memcached 嗎?"
Session 4: [重複相同的討論]
每個 session,你都要重新解釋決策。每個 session,context 都會丟失。這就是組織記憶失效。
解決方案:Memory MCP
Memory MCP 創建一個持久化知識圖譜,儲存:
- Entities - 帶有觀察紀錄的命名概念
- Relations - 實體之間的關聯
- Observations - 關於實體的事實
┌─────────────────────────────────────────────────────────────┐
│ Knowledge Graph │
│ │
│ ┌────────────────┐ ┌────────────────┐ │
│ │ authentication │◄──uses──│ redis_cache │ │
│ │ │ │ │ │
│ │ Observations: │ │ Observations: │ │
│ │ - Uses JWT │ │ - Selected for │ │
│ │ - Tokens valid │ │ speed │ │
│ │ for 24h │ │ - v7.2 │ │
│ └────────────────┘ └────────────────┘ │
│ │ │ │
│ │ │ │
│ └──────────┬───────────────┘ │
│ │ │
│ ▼ │
│ ┌────────────────┐ │
│ │ user_session │ │
│ │ │ │
│ │ Observations: │ │
│ │ - 30 min TTL │ │
│ │ - Refresh │ │
│ │ strategy │ │
│ └────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
設定 Memory MCP
步驟 1:將 Memory MCP 加入專案
使用官方 CLI 來添加 Memory MCP:
# Add with project isolation (CRITICAL!)
# Run from the project root; the shell expands $PWD to an absolute path
claude mcp add memory \
-e MEMORY_FILE_PATH="$PWD/.claude/memory.jsonl" \
-- npx -y @modelcontextprotocol/server-memory
重要: MEMORY_FILE_PATH 環境變數可以隔離每個專案的記憶。如果沒有設定,所有專案會共用同一個記憶檔案。這個路徑必須是絕對路徑(以 ~/ 開頭也可以):伺服器會以自己的套件目錄、而非你的專案來解析相對路徑。若要透過提交到版本控制的 .mcp.json 共用這個伺服器,請加上 --scope project,並改引用每位開發者自行設定的變數,例如 "MEMORY_FILE_PATH": "${PROJECT_MEMORY_PATH}"。
步驟 2:驗證安裝
# Check MCP status: each server is listed with a health status
claude mcp list
# Inspect one server (command, scope, status, last error)
claude mcp get memory
步驟 3:初始化記憶
首次使用時,創建初始 context:
User: "Save initial project context to memory"
Claude:
→ Creates entities for: project, tech_stack, key_decisions
→ Establishes relations between entities
→ Stores initial observations
記憶操作
創建 Entities
Entities 是帶有類型和觀察紀錄的命名概念:
{
"name": "authentication_system",
"entityType": "component",
"observations": [
"Uses JWT tokens for stateless auth",
"Tokens expire after 24 hours",
"Refresh tokens rotate on each use",
"Implemented in auth/ directory"
]
}
創建 Relations
Relations 透過命名關係連接 entities:
{
"from": "authentication_system",
"to": "redis_cache",
"relationType": "uses"
}
添加 Observations
為現有 entities 添加新事實:
{
"entityName": "authentication_system",
"contents": [
"Added MFA support on 2026-01-10",
"MFA uses TOTP algorithm"
]
}
記憶指令
伺服器提供九個由 Claude 直接呼叫的工具:create_entities、create_relations、add_observations、delete_entities、delete_observations、delete_relations、read_graph、search_nodes 與 open_nodes。用自然語言即可驅動它們。下面的 /memory-* 指令是你自己在 .claude/skills/ 建立的自訂 skills,並非 Claude Code 內建指令——Claude Code 內建的指令是 /memory,用來編輯 CLAUDE.md 檔案與管理 auto memory。
儲存知識
/memory-save
或使用自然語言:
"Save this decision to memory: We chose PostgreSQL over MySQL because..."
Claude 會:
- 識別要創建/更新的 entities
- 提取 observations
- 建立 relations
- 儲存到知識圖譜
搜尋知識
/memory-search
或使用自然語言:
"What do we know about our caching strategy?"
Claude 會:
- 搜尋知識圖譜
- 找到相關 entities
- 返回 observations 和 relations
列出所有知識
/memory-list
顯示所有儲存的 entities 及其 observations。
審計記憶
/memory-audit
識別:
- 過時的資訊
- 重複的 entities
- 缺失的 relations
- 清理建議
要儲存什麼到記憶
架構決策
Entity: database_choice
Type: decision
Observations:
- "Selected PostgreSQL for JSONB support"
- "Considered MySQL but needed JSON queries"
- "Decision date: 2026-01-05"
- "Decision maker: Tech lead"
設計模式
Entity: error_handling_pattern
Type: pattern
Observations:
- "Use Result type for all async operations"
- "Never throw in domain layer"
- "Log errors at boundary only"
- "Pattern documented in ARCHITECTURE.md"
Bug 修復
Entity: auth_timeout_bug
Type: bug_fix
Observations:
- "Issue: Users logged out after 5 minutes"
- "Root cause: Token refresh race condition"
- "Solution: Implemented mutex around refresh"
- "PR: #234, Merged: 2026-01-08"
團隊慣例
Entity: code_review_process
Type: process
Observations:
- "All PRs require 2 reviews"
- "Security-sensitive code needs security-auditor"
- "Use conventional commits"
- "Squash merge only"
外部依賴
Entity: stripe_integration
Type: integration
Observations:
- "API version: 2024-11-20"
- "Webhook endpoint: /api/webhooks/stripe"
- "Using Stripe Checkout for payments"
- "Test mode API key in STRIPE_SECRET_KEY"
記憶模式
模式 1:Session 開始時載入
每個 session 開始時載入相關 context:
"What do we know about the feature I'm working on?"
Claude 會搜尋記憶並提供 context。
模式 2:決策記錄
做出決策後記錄它們:
"Save this decision to memory: We're using Redis for
session caching because it provides sub-millisecond
latency and we need 10K+ concurrent sessions."
模式 3:Bug Context
修復 bug 時,儲存 context:
"Save this bug fix to memory: The login timeout was
caused by token refresh race condition. Fixed by
adding mutex. Relevant files: auth/refresh.ts"
模式 4:定期審查
定期審計和清理記憶:
/memory-audit
然後:
"Clean up outdated observations about the old auth system"
與工作流程整合
Director Mode 整合
記憶透過提供持久 context 來實現真正的 Director Mode:
"Implement user profile editing based on our existing
patterns and decisions."
Claude:
→ Searches memory for: patterns, conventions, decisions
→ Finds: error handling pattern, API conventions
→ Implements following established patterns
多 Session 專案
對於跨越多天的複雜專案:
Day 1: "We're building a payment system. Save the architecture."
Day 2: "Continue payment work. What did we decide yesterday?"
Day 3: "Finish payment integration. What's left?"
記憶提供跨 session 的連續性。
團隊知識共享
記憶成為共享的團隊知識:
// .claude/memory.jsonl (committed to repo), one object per line
{"type":"entity","name":"Authentication System","entityType":"Architecture","observations":["Uses JWT with 24-hour expiration"]}
{"type":"relation","from":"Authentication System","to":"Database Schema","relationType":"uses"}
新團隊成員繼承組織知識。
進階記憶技巧
階層式知識
以階層方式組織知識:
project
├── architecture
│ ├── frontend
│ │ └── React patterns, state management
│ ├── backend
│ │ └── API conventions, auth patterns
│ └── database
│ └── Schema decisions, indexing strategies
└── decisions
├── technical
└── product
時間 Context
在 observations 中包含時間:
Observations:
- "[2026-01-05] Initial choice: MySQL"
- "[2026-01-08] Migrated to PostgreSQL for JSONB"
- "[2026-01-10] Added read replica for analytics"
信心程度
標記 observation 的信心程度:
Observations:
- "[CONFIRMED] Uses JWT for auth"
- "[ASSUMPTION] Token TTL is 24 hours (verify)"
- "[OUTDATED] Previous used session cookies"
交叉引用模式
連結相關知識:
Entity: auth_bug_001
Observations:
- "Related to: token_refresh_mechanism"
- "See also: session_management"
- "Fixed in: PR #234"
記憶架構
檔案結構
.mcp.json # Project-scoped MCP servers (committed)
.claude/
├── memory.jsonl # Knowledge graph storage
├── settings.json # Project settings (permissions, approvals)
└── skills/ # Custom skills
記憶圖譜格式
伺服器在磁碟上寫入 JSONL:每行一個 {"type":"entity",...} 或 {"type":"relation",...} 物件。read_graph 工具則以單一物件回傳相同資料:
{
"entities": [
{
"name": "entity_name",
"entityType": "component|decision|pattern|...",
"observations": ["observation 1", "observation 2"]
}
],
"relations": [
{
"from": "entity_a",
"to": "entity_b",
"relationType": "uses|depends_on|implements|..."
}
]
}
儲存策略
選項 1:專案本地(推薦)
MEMORY_FILE_PATH="$PWD/.claude/memory.jsonl"
- 與程式碼一起提交
- 團隊共享知識
- 專案專屬
選項 2:使用者全域
MEMORY_FILE_PATH=~/.claude/memory.jsonl
- 個人知識
- 跨專案模式
- 使用者偏好
選項 3:混合式
Project: <project>/.claude/memory.jsonl (architecture, decisions)
User: ~/.claude/memory.jsonl (personal patterns)
每個 MCP 客戶端都會啟動自己的伺服器行程,因此指向同一個檔案的兩個客戶端就是兩個寫入者。每次寫入都會在檔案旁取得獨占的 <memory file>.lock,所以並行的寫入會依序進行。
記憶維護
定期清理
/memory-audit
識別:
- 超過 30 天未存取的 entities
- 重複或衝突的 observations
- 孤立的 relations
- 建議的整合
遷移策略
重構時:
"Update memory: We migrated from Express to Fastify.
Mark all Express-related observations as outdated."
歸檔
對於已完成的專案:
"Archive all memory related to v1 authentication
with note: 'Replaced by v2 OAuth implementation'"
Memory vs 其他持久化方式
| 特性 | Memory MCP | Auto memory | CLAUDE.md | Git History |
|---|---|---|---|---|
| 結構化 | 是(graph) | 部分(一個主題一個檔案) | 否(text) | 否 |
| 可查詢 | 是 | 部分(Claude 按需讀取主題檔案) | 否 | 部分 |
| 時間性 | 是 | 每個檔案有 modified 時間戳記 | 手動 | 是 |
| 團隊共享 | 是 | 否(僅限本機) | 是 | 是 |
| Context 成本 | 低(按需) | 低(僅載入索引) | 高(始終載入) | N/A |
Auto memory 是 Claude Code 內建的系統:Claude 會自行把筆記寫進 ~/.claude/projects/<project>/memory/,每則記憶一個主題檔案,再加上一份 MEMORY.md 索引。每次對話開始時只會載入 MEMORY.md 的前 200 行(或前 25KB),主題檔案則按需讀取。它在本機工作階段預設開啟、僅存在於本機,並由同一個儲存庫的所有 worktree 共用。可在 /memory 中切換,或使用 autoMemoryEnabled 設定與 CLAUDE_CODE_DISABLE_AUTO_MEMORY=1;用 autoMemoryDirectory 可變更存放位置。
何時使用 Memory vs CLAUDE.md
使用 Memory:
- 決策和理由
- Bug 修復和解決方案
- 演進中的模式
- Session 間的 context
使用 CLAUDE.md:
- 靜態政策
- 工具配置
- 專案結構
- 工作流程定義
疑難排解
記憶沒有持久化
- 檢查
MEMORY_FILE_PATH是否設定為絕對路徑 - 驗證檔案寫入權限(伺服器還需要在旁邊建立
.lock檔案) - 檢查 MCP 是否已連線:先
claude mcp list,再claude mcp get memory
搜尋找不到結果
search_nodes會以不分大小寫的子字串比對 entity 名稱、類型與 observations——若找不到,代表這些字詞並未被儲存- 驗證 observations 包含搜尋詞
- 使用更廣泛的搜尋詞(查詢字串上限為 2,048 個字元)
重複的 Entities
- 執行
/memory-audit - 合併重複項:「Merge entity A and B」
- 更新 relations 指向合併後的 entity
最佳實踐
1. 立即儲存
做出決策時,立刻儲存:
"Save this decision to memory now before we forget the context."
2. 具體明確
好的 observation:
"Selected PostgreSQL for JSONB support needed for user preferences storage"
避免:
"Using PostgreSQL"
3. 包含 Context
添加「為什麼」而不只是「什麼」:
"Chose Redis over Memcached because we need data structures (lists, sets) for session management"
4. 定期更新
當事情改變時:
"Update memory: We increased token TTL from 24h to 7 days per user feedback"
5. 每月審計
安排定期維護:
/memory-audit
開始使用
今天:
- 將 Memory MCP 加入你的專案
- 儲存一個架構決策
- 試試
/memory-search
這週:
- 建立初始知識圖譜
- 儲存所有重大決策
- 整合到日常工作流程
這個月:
- 完成知識圖譜覆蓋
- 建立團隊慣例
- 定期審計排程
Memory 讓 Claude Code 成為知識豐富的夥伴。建立你的知識圖譜,每個 session 都能帶著完整 context 開始。