メインコンテンツへスキップ

Claude Code Memory System: 永続的なプロジェクト知識の構築

Claude CodeのMemory MCPをマスターしましょう。セッションを超えて持続するナレッジグラフを構築し、真のプロジェクト継続性と組織知識を実現する方法を学びます。

2026年10月21日更新: 最新の公式ドキュメントと @modelcontextprotocol/server-memory 2.0 に合わせて修正しました。MEMORY_FILE_PATH は絶対パスが必要(保存形式は JSONL)、ナレッジグラフのフィールドは entityType/relationType、/memory-* コマンドは組み込みではなくカスタムスキル、組み込みの仕組みは Claude Code の auto memory です。

AIアシスタントの最もフラストレーションを感じる側面の一つはセッション健忘です。すべての会話がゼロから始まります。Claude Codeには現在、プロジェクトごとにセッションを超えて永続するファイルベースの auto memory が組み込まれており、その上にオプションとしてMemory MCPを重ねることができます。これは構造化されたクエリ可能なプロジェクト知識を提供するナレッジグラフシステムです。

このガイドでは、永続的なプロジェクトインテリジェンスの構築について知っておくべきすべてを解説します。

問題: セッション健忘

従来のAIワークフローはコンテキストの喪失に悩まされます:

Session 1: "We decided to use Redis for caching because..."
Session 2: "Why are we using Redis?"
Session 3: "Should we switch to Memcached?"
Session 4: [Repeats same discussion]

毎回のセッションで決定事項を再説明する必要があります。毎回のセッションでコンテキストが失われます。これは組織記憶の欠陥です。

解決策: 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のセットアップ

Step 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}")を参照してください。

Step 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

Step 3: メモリの初期化

初回使用時に初期コンテキストを作成します:

User: "Save initial project context to memory"

Claude:
→ Creates entities for: project, tech_stack, key_decisions
→ Establishes relations between entities
→ Stores initial observations

メモリ操作

エンティティの作成

エンティティはタイプと観察を持つ名前付き概念です:

{
  "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"
  ]
}

リレーションの作成

リレーションは名前付きの関係でエンティティを接続します:

{
  "from": "authentication_system",
  "to": "redis_cache",
  "relationType": "uses"
}

観察の追加

既存のエンティティに新しい事実を追加します:

{
  "entityName": "authentication_system",
  "contents": [
    "Added MFA support on 2026-01-10",
    "MFA uses TOTP algorithm"
  ]
}

メモリコマンド

サーバーは Claude が直接呼び出す 9 つのツールを提供します:create_entities、create_relations、add_observations、delete_entities、delete_observations、delete_relations、read_graph、search_nodes、open_nodes。自然な言葉で指示するだけで動かせます。以下の /memory-* コマンドは .claude/skills/ に自分で作るカスタムスキルであり、Claude Code の組み込みコマンドではありません。Claude Code 自身のコマンドは /memory で、CLAUDE.md ファイルの編集と auto memory の管理を行います。

知識の保存

/memory-save

または自然言語で:

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

Claudeは以下を行います:

  1. 作成/更新するエンティティを識別
  2. 観察を抽出
  3. リレーションを確立
  4. ナレッジグラフに保存

知識の検索

/memory-search

または自然言語で:

"What do we know about our caching strategy?"

Claudeは以下を行います:

  1. ナレッジグラフを検索
  2. 関連エンティティを見つける
  3. 観察とリレーションを返す

すべての知識をリスト

/memory-list

保存されているすべてのエンティティとその観察を表示します。

メモリの監査

/memory-audit

以下を識別します:

  • 古い情報
  • 重複エンティティ
  • 欠落しているリレーション
  • クリーンアップの推奨事項

メモリに保存すべきもの

アーキテクチャの決定

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"

バグ修正

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"

メモリパターン

Pattern 1: セッション開始時の読み込み

各セッションの開始時に関連コンテキストを読み込みます:

"What do we know about the feature I'm working on?"

Claudeがメモリを検索してコンテキストを提供します。

Pattern 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."

Pattern 3: バグコンテキスト

バグを修正する際、コンテキストを保存します:

"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"

Pattern 4: 定期的なレビュー

定期的にメモリを監査してクリーンアップします:

/memory-audit

その後:

"Clean up outdated observations about the old auth system"

ワークフローとの統合

Director Modeとの統合

Memoryは永続的なコンテキストを提供することで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

複数セッションにまたがるプロジェクト

複数日にわたる複雑なプロジェクトの場合:

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?"

Memoryがセッション間の継続性を提供します。

チーム知識の共有

Memoryは共有のチーム知識になります:

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

時間的コンテキスト

観察にタイミングを含めます:

Observations:
- "[2026-01-05] Initial choice: MySQL"
- "[2026-01-08] Migrated to PostgreSQL for JSONB"
- "[2026-01-10] Added read replica for analytics"

信頼度レベル

観察の信頼度をマークします:

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 を書き込みます。1 行につき {"type":"entity",...} または {"type":"relation",...} のオブジェクトが 1 つです。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|..."
    }
  ]
}

保存戦略

Option 1: プロジェクトローカル(推奨)

MEMORY_FILE_PATH="$PWD/.claude/memory.jsonl"
  • コードと一緒にコミット
  • チーム共有の知識
  • プロジェクト固有

Option 2: ユーザーグローバル

MEMORY_FILE_PATH=~/.claude/memory.jsonl
  • 個人的な知識
  • プロジェクト横断のパターン
  • ユーザー設定

Option 3: ハイブリッド

Project: <project>/.claude/memory.jsonl (architecture, decisions)
User: ~/.claude/memory.jsonl (personal patterns)

MCP クライアントはそれぞれ自分のサーバープロセスを起動するため、同じファイルを指す 2 つのクライアントは 2 つの書き込み元になります。書き込みのたびにファイルの隣で排他的な <memory file>.lock を取得するので、同時書き込みは順番に処理されます。

メモリのメンテナンス

定期的なクリーンアップ

/memory-audit

以下を識別します:

  • 30日以上アクセスされていないエンティティ
  • 重複または矛盾する観察
  • 孤立したリレーション
  • 統合の提案

移行戦略

リファクタリング時:

"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と他の永続化の比較

機能Memory MCPAuto memoryCLAUDE.mdGit History
構造化Yes (graph)Partial (1ファイル1トピック)No (text)No
クエリ可能YesPartial (Claude が必要に応じてトピックファイルを読む)NoPartial
時間的Yesファイルごとの modified タイムスタンプManualYes
チーム共有YesNo (マシンローカル)YesYes
コンテキストコストLow (on-demand)Low (インデックスのみ読み込み)High (always loaded)N/A

Auto memory は Claude Code の組み込みの仕組みです。Claude 自身が ~/.claude/projects/<project>/memory/ にメモを書き込み、1 メモリにつき 1 トピックファイルと MEMORY.md インデックスを置きます。会話の開始時に読み込まれるのは MEMORY.md の先頭 200 行(または 25KB)までで、トピックファイルは必要に応じて読まれます。ローカルセッションではデフォルトで有効、マシンローカルで、同じリポジトリのすべての worktree で共有されます。/memory のトグル、autoMemoryEnabled 設定、CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 で切り替えられ、autoMemoryDirectory で保存先を変更できます。

MemoryとCLAUDE.mdの使い分け

Memoryを使用する場合:

  • 決定とその理由
  • バグ修正と解決策
  • 進化するパターン
  • セッション間のコンテキスト

CLAUDE.mdを使用する場合:

  • 静的なポリシー
  • ツールの設定
  • プロジェクト構造
  • ワークフローの定義

トラブルシューティング

メモリが永続化されない

  1. MEMORY_FILE_PATHが絶対パスで設定されているか確認
  2. ファイルの書き込み権限を確認(サーバーは隣に .lock ファイルも作成します)
  3. MCPが接続されているか確認: claude mcp list のあと claude mcp get memory

検索で結果が見つからない

  1. search_nodes はエンティティ名・タイプ・観察を大文字小文字を区別せず部分一致で検索します。見つからない場合、その語は保存されていません
  2. 観察に検索語が含まれているか確認
  3. より広い検索語を使用(クエリは 2,048 文字までです)

重複エンティティ

  1. /memory-auditを実行
  2. 重複をマージ: “Merge entity A and B”
  3. リレーションをマージされたエンティティを指すように更新

ベストプラクティス

1. 即座に保存

決定を下したら、すぐに保存します:

"Save this decision to memory now before we forget the context."

2. 具体的に

良い観察:

"Selected PostgreSQL for JSONB support needed for user preferences storage"

避けるべき:

"Using PostgreSQL"

3. コンテキストを含める

「何を」だけでなく「なぜ」を追加します:

"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を知識豊富なパートナーへと変えます。ナレッジグラフを構築すれば、すべてのセッションが完全なコンテキストで始まります。

出典: Claude Code メモリドキュメント、Memory MCP サーバー