Claudeにライブラリの使い方をSerena経由でレクチャーしつつTokenも最適化する

Claudeにライブラリの使い方をSerena経由でレクチャーしつつTokenも最適化する

Claudeにライブラリを使ったコードを実装できるよう、誘導するためにSerenaメモリ経由でリファレンスを参照できるようにしてみました。ネックとなるToken消費量への対処も含みます。
2025.08.08

Claudeにライブラリを使った実装を依頼した際、連続してエラーが発生し、作業の手戻りが続く状態に陥りました。原因を調査したところ、Claudeが試みたライブラリの使用方法が公式ドキュメントのサンプルコードと大きく異なっていたことが判明しました。

その都度サンプルコードをClaudeに貼り付けていましたが、セッションが変わるたびに情報が失われてしまいます。様々な対策を試みた結果、Serenaメモリを介しての対処となりました。

ライブラリのサンプルコード等をSerenaメモリに設定する

GitHubのRAW URLをSerenaに渡します。以下はjestのTroubleshooting.mdを活用した例です。

serenaメモリにhttps://raw.githubusercontent.com/jestjs/jest/refs/heads/main/docs/Configuration.md
の内容を追加して、CLAUDE.mdにjest用設定リファレンス参照として英語で追記する

以下の順で実施されます。

  1. URLへのFetch
  2. Claudeによる要約結果がSerenaのwrite_memoryにて保存
  3. CLAUDE.mdへ参照の追記

今回の追記は以下の通りでした。

## Jest Testing Framework
- **Configuration Reference**: Comprehensive Jest options documented in Serena memory `jest_configuration_reference.md`
- **Official Documentation**: <https://raw.githubusercontent.com/jestjs/jest/refs/heads/main/docs/Configuration.md>
- **Multi-project Setup**: Use `projects` array for backend, frontend, Vue, integration, and E2E test separation
- **TypeScript Integration**: Requires `ts-jest` preset with proper transform configuration
- **Vue Testing**: Requires `jsdom` environment with `@vue/vue3-jest` transformer for `.vue` files

実施後の変化

TagifyリポジトリのREADME.mdもSerenaメモリに追記した結果、それまで発生していた手戻りが完全になくなりました。利用するライブラリのリファレンスは事前にSerenaメモリに追加しておくことが効果的といえます。

ただ、Tokenがやや無視できない消費量になっていました。

Serenaメモリへの設定によって生じるToken消費概算

リファレンスは相応のテキスト量を含むため、それに応じたToken消費量も相当な割合を占めています。Claudeに計算させたToken消費量は以下の通りです。

__Token消費量の詳細分析__
__1. WebFetch処理でのToken消費__
入力Token: リクエスト内容 + URL + プロンプト ≈ 100-200トークン
処理Token: サイト内容のAI要約処理 ≈ 2,000-10,000トークン
出力Token: 要約されたコンテンツ ≈ 500-2,000トークン
合計: 約2,600-12,200トークン/サイト

__2. Serena Memory書き込みでのToken消費__
入力Token: メモリ書き込みコマンド + コンテンツ ≈ 500-2,000トークン
出力Token: 確認レスポンス ≈ 50-100トークン
合計: 約550-2,100トークン/メモリファイル

__3. 実際の例(今セッションで実行済み)__
Jest設定リファレンス:
- WebFetch: 約3,500トークン
- Memory書き込み: 約800トークン
- 合計: **約4,300トークン**
Jestトラブルシューティングガイド:
- WebFetch: 約2,800トークン
- Memory書き込み: 約1,200トークン
- 合計: **約4,000トークン**

サイト上のテキストを直接Serenaに追加できればWebFetchを省略でき、大幅なToken節約が見込めます。ただし、テキスト量の多さとClaudeによる解釈が課題となります。

理想的サイズ:
核となるリファレンス: 2-5KB (500-1,250トークン)
トラブルシューティング: 3-8KB (750-2,000トークン)
包括的ガイド: 8-15KB (2,000-3,750トークン)

テキスト自体のToken量もありますが、ClaudeのAI要約プロセスが毎回挟むため、長い目でみるとWebFetchのほうが低コストになるかもしれません。ちなみに、Claudeから避けるべきとして提示されたのが以下の例。

20KB超 (5,000トークン超) = ReadとMemoryでToken効率が悪化

リファレンス読込に伴うToken消費概算

Claude によると、セッション起動時の Serena メモリ構築は15,000〜20,000トークン程度に抑えるのが現実的とされています。この数値にはリファレンスも含まれています。推定消費トークン量は以下の通りです。

__軽量パターン(3-4サイト)__:
- 基本リファレンス × 3サイト: 12,000-15,000トークン
- メモリ書き込み: 2,000-3,000トークン
- 合計: 約14,000-18,000トークン
__標準パターン(5-7サイト)__:
- 技術リファレンス × 5サイト: 20,000-25,000トークン
- ライブラリドキュメント × 2サイト: 8,000-10,000トークン
- メモリ書き込み: 3,500-4,500トークン
- 合計: 約31,500-39,500トークン
__包括パターン(8-10サイト)__:
- フルスタック技術ドキュメント: 35,000-45,000トークン
- メモリ書き込み: 5,000-6,000トークン
- 合計: 約40,000-51,000トークン

適切な用途としては3パターン程度が妥当でしょう。必要に応じて作業中に参照することで、無駄な読込を減らせます。大きなドキュメントは章ごとに分割して登録するなどの対策も可能です。

以下は、Claudeが筆者のCLAUDE.mdから読み取ったドキュメントのToken消費量概算です。

1. 必須読み込みメモリ(CLAUDE.md明示指定)

メモリファイル 用途 推定Token
symbol_patterns_updated.md シンボル検索パターン 1,500-2,000
package-scripts-config.md npm scripts/Vite設定 1,000-1,500
component-template-system.md コンポーネントガイド 800-1,200
search-exclusions.md 検索除外パス 500-800
implementation-architecture.md 実装アーキテクチャ 2,000-2,500
小計 5,800-8,000
  1. 暗黙的に必要とされるメモリ(文脈から推測)
メモリファイル 根拠 推定Token
jest_configuration_reference.md Jest設定への明示的参照(186行) 1,500-2,000
jest_troubleshooting_guide.md Jestトラブルシューティング(187行) 2,000-2,500
tagify_official_documentation Tagify実装ガイドライン(195-199行) 1,500-2,000
小計 5,000-6,500

Serenaメモリが読み込まれるパターン

実際にリファレンスが読み込まれるタイミングは、CLAUDE.mdの記述内容によって決まります。

強制的に読み込まれるのは、以下のように具体的なコマンドを伴う明示的な指示がある場合のみです。

    ### Auto-execution at Session Start
    The following commands MUST be executed automatically at the beginning of each session:

    ```bash
    # 1. Check existing knowledge
    mcp__serena__check_onboarding_performed
    mcp__serena__list_memories

    # 2. Project structure scan
    mcp__serena__list_dir({ relative_path: ".", recursive: false })
    mcp__serena__get_symbols_overview({ relative_path: "src" })

    # 3. Configuration files
    mcp__serena__find_file({ file_mask: "package.json", relative_path: "." })
    mcp__serena__find_file({ file_mask: "*.config.*", relative_path: "." })
    ```

メモリ参照一覧としてCLAUDE.mdには以下のように記載していますが、これも「stored in」という表現で単にその存在を示唆するだけであり、強制的な読込は行われません。

  ## Serena Memory References
  Project-specific technical information is stored in Serena memories:
  - `symbol_patterns_updated.md` - Symbol search patterns and conventions
  - `package-scripts-config.md` - Development commands and Vite configuration

結果として、筆者のCLAUDE.md経由でセッション開始時に強制で読み込まれるドキュメントは皆無となっているようです。先の項目で必須読み込みメモリと解釈される割に、セッション開始時に読み込まれていないんですね。

メモリ種別 読み込みタイミング 強制/任意
明示指定メモリ(5個) タスクに関連する場合のみ 任意
symbol_patterns_updated.md シンボル検索が必要な時 任意
package-scripts-config.md npm scripts実行時 任意
component-template-system.md コンポーネント作成時 任意
search-exclusions.md 検索実行時 任意
implementation-architecture.md アーキテクチャ理解が必要な時 任意
暗黙的メモリ(3個) 特定機能使用時のみ 任意
jest_configuration_reference.md Jestテスト作成/実行時 任意
jest_troubleshooting_guide.md Jest問題発生時 任意
tagify_official_documentation Tagify実装時 任意

実際のToDoでリファレンスが読み込まれたケース

直近のToDoで任意に読み込まれたケースを確認してみました。

ToDoで実際にリファレンスが参照された例

1. Jest設定リファレンス参照

Todo: "タグのテストケースがないので、作成から行う"

参照されたリファレンス:
// Vitest/Jest設定エラー発生時
Error: "Unknown option 'testTimeout'"
// 対応として実行
1. WebFetch("https://raw.githubusercontent.com/jestjs/jest/.../Configuration.md")
   → jest_configuration_reference.md 作成(約4,300 Token)
2. WebFetch("https://raw.githubusercontent.com/jestjs/jest/.../Troubleshooting.md")
   → jest_troubleshooting_guide.md 作成(約4,000 Token)

実際の活用:
- testTimeoutが正しい設定名であることを確認
- プロジェクトレベルでの設定方法を理解
- 結果: Jest設定を修正し、全テスト通過
2. Tagify実装時の参照(過去セッション - メモリから推測)

Todo: "タグ編集UIをTagifyライブラリで再構築"

参照されたリファレンス:
// tagify_official_documentation.md が存在することから
WebFetch("https://raw.githubusercontent.com/yairEO/tagify/.../README.md")
→ tagify_official_documentation.md

実際の活用例(CLAUDE.mdに記載):
## Tagify Implementation Guidelines
- **Base Implementation**: Use sample scripts from the official Tagify documentation
- **Implementation Approach**: Follow official examples for initialization

しかし、現在の実装は最適とは言えません。WebFetchがSerenaメモリ内の事前チェックなしに優先されているため、WebFetch→AI処理→mcp__serena__write_memoryという流れで約4,300Tokenが消費されています。

リファレンス設定と読込パターンを元に設定・読込とToken節約のルール改善

今回の調査結果に基づき、Claudeが提案した改善項目です。WebFetch前に必須メモリチェックを実施することで、大幅なToken消費を削減できます。特定言語に依存していないため、mdファイル名の命名規則に従えば、どのプロジェクトでも汎用的に活用できるでしょう。

#### B. Memory-First Strategy
- **Before Any Investigation**: Always check existing memories first using standardized protocol:
  ```markdown
  # 1. List all available memories
  mcp__serena__list_memories

  # 2. Check for topic-specific memories using pattern matching
  # Topic examples: "jest", "vue", "typescript", "vite", etc.
  mcp__serena__read_memory("[topic]_reference.md")  # if exists
  mcp__serena__read_memory("[topic]_troubleshooting_guide.md")  # if exists

  # 3. Only proceed with WebFetch if no relevant memory exists
  ```end
- **Memory Index Usage**: Check `_index.md` memory for quick overview of available references (200 tokens)
- **Conditional WebFetch**: Use WebFetch only when `mcp__serena__list_memories` doesn't contain relevant topic
- **Memory Creation**: Always save WebFetch results to memory using standardized naming convention
- **Memory Update**: Update existing memories when discovering new patterns or deprecated information
#### H. Reference Check Priority Protocol
- **MANDATORY Memory-First Check**: Always check Serena memories before WebFetch operations
- **Memory Naming Convention**: Use standardized naming for reference memories:
  - Library docs: `[library-name]_reference.md`
  - Troubleshooting guides: `[topic]_troubleshooting_guide.md`
  - Configuration specs: `[tool]_configuration_reference.md`
  - API specifications: `[service]_api_reference.md`
- **Token Optimization**: Memory reads (500-3,000 tokens) vs WebFetch (3,000-12,000 tokens) = 60-80% savings
- **Batch Reference Checks**: Use parallel memory reads for multiple related topics
- **Reference Update Strategy**: Only use WebFetch when memory doesn't exist, always save results to memory
#### I. Efficient Reference Lookup Implementation
- **Automatic Memory Check Triggers**: When user requests contain specific keywords, automatically execute memory check before any other operations:
  ```bash
  # Testing keywords: "test", "jest", "spec", "テスト", "エラー"
  if (userRequest.includes(testingKeywords)) {
    mcp__serena__read_memory("_index")  # Always check index first
    mcp__serena__read_memory("jest_configuration_reference")  # if exists
    mcp__serena__read_memory("jest_troubleshooting_guide")    # if exists
  }

  # Component keywords: "component", "vue", "コンポーネント", "template"  
  if (userRequest.includes(componentKeywords)) {
    mcp__serena__read_memory("component-template-system")
    mcp__serena__read_memory("implementation-architecture")
  }

  # Search keywords: "find", "search", "探す", "調べる", "確認"
  if (userRequest.includes(searchKeywords)) {
    mcp__serena__read_memory("symbol_patterns_updated")  # Always for searches
    mcp__serena__read_memory("search-exclusions")
  }
  ```end
- **Topic-Based Memory Filtering**: When user requests reference for a specific topic, execute standardized pattern:
  ```bash
  # Step 1: Index check (200 tokens) - MANDATORY for any reference request
  mcp__serena__read_memory("_index")

  # Step 2: Quick memory scan (100-150 tokens)  
  memories = await mcp__serena__list_memories()

  # Step 3: Pattern matching for relevant memories
  relevant = memories.filter(m => m.toLowerCase().includes(topic.toLowerCase()))

  # Step 4: Read existing memory if found (500-3000 tokens)
  if (relevant.length > 0) {
    return mcp__serena__read_memory(relevant[0])
  }

  # Step 5: WebFetch only if no memory exists (3000-12000 tokens)
  ```end
- **Batch Reference Processing**: For multiple related topics, use parallel memory reads to minimize total token consumption
- **Memory Staleness Check**: When referencing external documentation, note last update date in memory and refresh if older than 6 months

途中に記載のある_indexはメモリのサマリを担当するファイルで、Claudeがサマリを参照し、用途別のメモリを見るというプロセスにてCLAUDE.mdのサイズを抑えることができます。

// メモリサマリーファイルの作成提案
  mcp__serena__write_memory("_index.md", `
  # Memory Index
  ## Testing
  - jest_configuration_reference: Jest設定オプション一覧
  - jest_troubleshooting_guide: Jest問題解決ガイド

  ## Libraries  
  - tagify_official_documentation: Tagify実装パターン
  - milkdown-configuration: Milkdownエディタ設定

  ## Architecture
  - implementation-architecture: システム構造
  - symbol_patterns_updated: コード検索パターン
  `);

  // 使用時(200 Tokenで全体像把握)
  mcp__serena__read_memory("_index.md");

Token消費概算は以下の通りです。初回はWebFetch + メモリ作成を含みます。

アプローチ 初回 2回目以降 10回参照時の累計
毎回WebFetch 4,300 4,300 43,000
Memory-First 4,800* 600 10,200
Index活用 5,000* 200-600 7,000-10,000

あとがき

CLAUDE.mdへ条件に基づいて自動的に処理を実行させる指示は出せますが、完全自動化のための標準フォーマットは存在しません。手元のCLAUDE.mdでどのようなプロセスが実行されるか確認したい場合は、適宜Claudeに質問しておくとよいでしょう。

なお、Claudeは明示的な指示がない限り、Serenaに対して自律的にメモリの読込や存在チェックを行いません。Serenaメモリに設定した内容が実際に正しく活用されているか確認するには、ToDo完了後にSerenaメモリの利用状況を検証することをお勧めします。

この記事をシェアする

facebookのロゴhatenaのロゴtwitterのロゴ

© Classmethod, Inc. All rights reserved.