跳至主要內容
精選 Memory MCP Knowledge Graph Advanced

Claude Code Memory 系統:建立持久的專案智慧

掌握 Claude Code 的 Memory MCP。學習如何建立跨 session 持久化的知識圖譜,實現真正的專案連續性與組織記憶。

2026年1月10日 20 分鐘閱讀 作者:ClaudeWorld

AI 助理最令人沮喪的一點就是 session 失憶症——每次對話都重新開始。Claude Code 透過 Memory MCP 解決了這個問題,這是一個跨 session 持久化的知識圖譜系統。

本指南涵蓋了建立持久專案智慧所需的一切知識。

問題: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!)
claude mcp add --scope project memory \
  -e MEMORY_FILE_PATH=./.claude/memory.json \
  -- npx -y @modelcontextprotocol/server-memory

重要: MEMORY_FILE_PATH 環境變數可以隔離每個專案的記憶。如果沒有設定,所有專案會共用同一個記憶檔案。

步驟 2:驗證安裝

# Check MCP status
claude mcp list

# Should show:
# memory (project) - @modelcontextprotocol/server-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"
  ]
}

記憶指令

儲存知識

/memory-save

或使用自然語言:

"Save this decision to memory: We chose PostgreSQL over MySQL because..."

Claude 會:

  1. 識別要創建/更新的 entities
  2. 提取 observations
  3. 建立 relations
  4. 儲存到知識圖譜

搜尋知識

/memory-search

或使用自然語言:

"What do we know about our caching strategy?"

Claude 會:

  1. 搜尋知識圖譜
  2. 找到相關 entities
  3. 返回 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.json (committed to repo)
{
  "entities": [...],
  "relations": [...]
}

新團隊成員繼承組織知識。

進階記憶技巧

階層式知識

以階層方式組織知識:

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"

記憶架構

檔案結構

.claude/
├── memory.json        # Knowledge graph storage
├── settings.json      # MCP configuration
└── skills/            # Custom skills

Memory JSON 格式

{
  "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=./.claude/memory.json
  • 與程式碼一起提交
  • 團隊共享知識
  • 專案專屬

選項 2:使用者全域

MEMORY_FILE_PATH=~/.claude/memory.json
  • 個人知識
  • 跨專案模式
  • 使用者偏好

選項 3:混合式

Project: .claude/memory.json (architecture, decisions)
User: ~/.claude/memory.json (personal patterns)

記憶維護

定期清理

/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 MCPCLAUDE.mdGit History
結構化是(graph)否(text)
可查詢部分
時間性手動
團隊共享
Context 成本低(按需)高(始終載入)N/A

何時使用 Memory vs CLAUDE.md

使用 Memory:

  • 決策和理由
  • Bug 修復和解決方案
  • 演進中的模式
  • Session 間的 context

使用 CLAUDE.md:

  • 靜態政策
  • 工具配置
  • 專案結構
  • 工作流程定義

疑難排解

記憶沒有持久化

  1. 檢查 MEMORY_FILE_PATH 是否已設定
  2. 驗證檔案寫入權限
  3. 檢查 MCP 是否正在執行:claude mcp list

搜尋找不到結果

  1. 檢查 entity 名稱(區分大小寫)
  2. 驗證 observations 包含搜尋詞
  3. 使用更廣泛的搜尋詞

重複的 Entities

  1. 執行 /memory-audit
  2. 合併重複項:「Merge entity A and B」
  3. 更新 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

開始使用

今天:

  1. 將 Memory MCP 加入你的專案
  2. 儲存一個架構決策
  3. 試試 /memory-search

這週:

  1. 建立初始知識圖譜
  2. 儲存所有重大決策
  3. 整合到日常工作流程

這個月:

  1. 完成知識圖譜覆蓋
  2. 建立團隊慣例
  3. 定期審計排程

Memory 將 Claude Code 從無狀態工具轉變為知識豐富的夥伴。建立你的知識圖譜,每個 session 都能帶著完整 context 開始。

資料來源:Claude Code Documentation, Memory MCP