メインコンテンツへスキップ
ブログ一覧

Claude Code カスタムサブエージェント実践ガイド — .claude/agents/ の設計・自動委譲・コスト最適化まで

(更新: 2026年04月08日)
Claude CodeサブエージェントAI開発ツールコスト最適化

Claude Code カスタムサブエージェント実践ガイド — .claude/agents/ の設計・自動委譲・コスト最適化まで

Claude Code のサブエージェントは「存在は知っているが自作はしていない」開発者が大半だ。実際、適切に設計されたサブエージェントは作業時間を半減させる一方、雑に作ると Opus がトークンを4〜7倍消費して委譲地獄に陥る。本記事では .claude/agents/ に置く Markdown ファイル1枚から、自動委譲の発火条件チューニング、haiku/sonnet/opus のコストルーティング、ツール制限によるサンドボックス設計、そして2026年4月追加の @メンション連携まで、カスタムサブエージェントを実戦投入するためのパターンを網羅する。

サブエージェントとは何か — Skills・Agent Teams との違い

3つのカスタマイズ手段の使い分け基準

Claude Code には拡張手段が3つある。混同しやすいので整理しておく。

手段 起動方法 実行コンテキスト 主な用途
Skills /スラッシュ で明示起動 メイン会話内に展開 手順が決まった定型操作
サブエージェント 自動委譲 or @メンション 独立コンテキストウィンドウ 判断・探索が必要なタスク
Agent Teams オーケストレーター設計 複数エージェント協調 大規模タスクの分割統治

判断基準はシンプルだ。手順が決まっているなら Skill、判断と探索が必要ならサブエージェント、複数エージェントの協調が必要なら Agent Teams を選ぶ。

サブエージェントが解く問題:コンテキスト分離と専門性の委譲

サブエージェントの最大の利点は、独立したコンテキストウィンドウで動作する点にある。メイン会話に大量の検索結果やコードが流れ込んでコンテキストが劣化する問題を、サブエージェントへの委譲で回避できる。「調べもの」と「意思決定」を分離するだけで、メイン会話の精度が目に見えて上がる。

最小構成から始める — 最初のサブエージェントを5分で作る

ファイル配置と frontmatter の必須フィールド

.claude/agents/ ディレクトリに Markdown ファイルを1つ置くだけで動く。最小構成はこれだけだ。

markdown
<!-- .claude/agents/test-runner.md -->
---
name: test-runner
description: "Run tests and report results. Use when: the user asks to run tests, verify test coverage, or check if tests pass. Do NOT use when: the user wants to write new tests."
---

You are a test execution specialist. Run the project's test suite and report results concisely.

- Detect the test framework (vitest, jest, pytest, etc.) from config files
- Run the full suite or specified test files
- Report: passed/failed/skipped counts, and failure details if any
- Do NOT fix failing tests — only report

必要なのは namedescription、そして本文のプロンプトだけだ。

動作確認:Agent ツールからの呼び出しと @メンション

サブエージェントには2つの起動パスがある。

  1. 自動委譲 — Claude が description を読み、タスクに合うエージェントを自動で選んで Agent ツール経由で呼び出す
  2. @メンション — ユーザーが @test-runner と入力して明示的に呼び出す(v2.1.89 以降、タイプアヘッドで候補表示される)

正直、@メンション対応が入ってからサブエージェントの使い勝手が一段上がった。自動委譲に頼りきらず、意図的に呼び分けられるのが大きい。

frontmatter 全フィールド設計指針

description — 自動委譲の発火条件を決める最重要フィールド

description は Claude がタスクとエージェントをマッチングする唯一の判断材料だ。ここを雑に書くと、意図しない委譲が頻発する。

markdown
# 悪い例
description: "Explores code"

# 良い例
description: >
  Fast codebase explorer (read-only). Use when: searching for files by
  pattern, finding function definitions, answering "where is X defined?"
  questions, or understanding code structure. Specify thoroughness: quick
  (1-2 queries), medium (5-10), thorough (10+). Do NOT use when: the user
  wants to edit code, generate code, or run commands.

ポイントは3つ。「Use when:」で発火条件を具体的なトリガーワードで列挙し、「Do NOT use when:」で誤発火を防ぎ、エージェントの能力境界を明示する。

tools / disallowedTools — サンドボックス設計

tools で許可ツールを限定すれば、読み取り専用エージェントを簡単に作れる。

yaml
tools: ["Read", "Grep", "Glob"]           # 読み取り専用
disallowedTools: ["Edit", "Write", "Bash"] # 編集・実行を禁止

レビュー系エージェントに Edit を許可しない理由は明快で、「指摘と修正を分離する」ことでレビューの客観性を保つためだ。

model / effort — コストルーティングの入口

model フィールドで haikusonnetopus を指定できる。未指定の場合はメイン会話のモデルを継承する。effort フィールド(low/medium/high/max)のうち、low/medium/high は Opus 4.6・Opus 4.5・Sonnet 4.6 で対応しているが、max は Opus 4.6 のみ対応である点に注意。

maxTurns はエージェントの暴走防止に必須だ。実践での目安を示す。

エージェント種別 maxTurns 推奨値
探索・検索系 20
コード修正系 30
レビュー・チェック系 10

モデルルーティングでコストを1/10にする

haiku / sonnet / opus の使い分け戦略

モデル選択はコストに直結する。タスク特性に応じた使い分けが重要だ。

タスク 推奨モデル 理由
ファイル検索・grep haiku パターンマッチに高い推論力は不要
コードレビュー・テスト生成 sonnet 品質とコストのバランスが最良
アーキテクチャ設計・複雑なリファクタ opus 高い推論力が成果物の質に直結

モデル解決の優先順位と環境変数オーバーライド

モデルは以下の優先順位で解決される。

  1. CLAUDE_CODE_SUBAGENT_MODEL 環境変数(チーム全体のデフォルト)
  2. Agent ツール呼び出し時の model パラメータ
  3. frontmatter の model フィールド
  4. メイン会話モデルの継承

チーム運用では CLAUDE_CODE_SUBAGENT_MODEL=haiku を設定しておき、本当に必要なエージェントだけ frontmatter で model: opus を指定するのが費用対効果が高い。

実戦パターン集 — プロジェクトに今日入れるべき5つのエージェント

以下の5つはコピペして .claude/agents/ に置けばすぐに使える。

1. explore(コードベース探索・haiku)

markdown
<!-- .claude/agents/explore.md -->
---
name: explore
description: >
  Fast read-only codebase explorer. Use when: searching files by pattern,
  finding definitions, answering "where is X?" questions. Specify
  thoroughness: quick/medium/thorough. Do NOT use when: editing or
  generating code.
model: haiku
tools: ["Read", "Grep", "Glob"]
maxTurns: 20
---

You are a fast codebase explorer. Find files, definitions, and patterns
efficiently. Return concise answers with file paths and line numbers.
Always specify the confidence of your findings.

2. reviewer(PRレビュー・sonnet)

markdown
<!-- .claude/agents/reviewer.md -->
---
name: reviewer
description: >
  Code reviewer. Use when: reviewing diffs, PRs, or code quality. Checks
  for bugs, security issues, and style. Do NOT use when: the user wants
  code to be fixed or written.
model: sonnet
tools: ["Read", "Grep", "Glob", "Bash"]
disallowedTools: ["Edit", "Write"]
maxTurns: 10
---

Review code for correctness, security, and maintainability. Be specific:
cite file:line for each issue. Classify as critical/warning/nit.
Do NOT suggest fixes in code blocks — only describe what should change.

3. test-writer(テスト生成・sonnet)

markdown
<!-- .claude/agents/test-writer.md -->
---
name: test-writer
description: >
  Test generation specialist. Use when: the user asks to add tests, improve
  coverage, or write test cases. Do NOT use when: running existing tests.
model: sonnet
tools: ["Read", "Grep", "Glob", "Edit", "Write"]
maxTurns: 30
---

Generate tests matching the project's existing test style and framework.
Read existing tests first to match patterns. Aim for edge cases and error
paths, not just happy paths.

4. doc-checker(ドキュメント整合性チェック・haiku)

markdown
<!-- .claude/agents/doc-checker.md -->
---
name: doc-checker
description: >
  Documentation consistency checker. Use when: verifying README, API docs,
  or comments match the actual code. Do NOT use when: writing new docs.
model: haiku
tools: ["Read", "Grep", "Glob"]
maxTurns: 10
---

Compare documentation against actual code. Flag outdated references,
wrong function signatures, missing parameters, and broken links.
Report as a checklist: [OK] or [STALE] per item.

5. architect(設計判断・opus)

markdown
<!-- .claude/agents/architect.md -->
---
name: architect
description: >
  Software architect for design decisions. Use when: planning new features,
  evaluating trade-offs, or designing system architecture. Do NOT use when:
  the task is implementation, not design.
model: opus
isolation: worktree
maxTurns: 15
---

You are a senior software architect. Analyze the codebase structure,
identify constraints, and propose designs with trade-off analysis.
Output: decision record with context, options considered, and recommendation.
You run in an isolated worktree — feel free to prototype if needed.

architect に isolation: worktree を指定しているのは、設計の試作を安全に行わせるためだ。変更がなければワークツリーは自動クリーンアップされる。

よくあるハマりどころと対策

自動委譲が発火しない / 意図しないエージェントに委譲される

原因の9割は description の曖昧さだ。改善例を示す。

markdown
# Before: 曖昧で Claude が委譲先を判断できない
description: "Helps with testing"

# After: トリガーワードと除外条件を明示
description: >
  Run existing test suites and report results. Use when: "run tests",
  "check if tests pass", "test coverage". Do NOT use when: "write tests",
  "add test cases", "create test file".

サブエージェントがツール不足でスタックする

tools を絞りすぎると、エージェントが調査だけして成果物を出せずに終わる。最低限のツールセット目安はこうだ。

  • 読み取り専用: Read, Grep, Glob
  • コード修正可能: 上記 + Edit, Write
  • フルアクセス: 上記 + Bash, Agent

トークン消費が想定の数倍になる

maxTurns 未設定で model: opus を指定すると、サブエージェントがさらにサブエージェントを呼ぶ連鎖委譲が発生しうる。対策は3つ。

  1. maxTurns を必ず設定する — 上限なしは事故のもと
  2. デフォルトを haiku に固定するCLAUDE_CODE_SUBAGENT_MODEL=haiku を環境変数に設定
  3. Agent ツールを tools から外す — 連鎖委譲を構造的に防止

まとめ — サブエージェント設計の3原則

  1. description を制するものが自動委譲を制する — 「Use when:」で発火条件、「Do NOT use when:」で除外条件を明示せよ
  2. モデルはデフォルト haiku、必要な場面だけ昇格 — haiku と opus のコスト差は約10倍。運用が長くなるほど効いてくる
  3. tools 制限は権限設計 — 読み取り専用・編集可能・フルアクセスの3段階で考えよ

まずは explore(haiku・読み取り専用)を1つ作って効果を実感してみてほしい。Markdown 1枚で開発体験が変わるのを体感できるはずだ。

もっと読む他の技術記事も読む