マルチエージェントアーキテクチャ:並列実行パターン
専門化されたエージェントを並列で活用し、5〜10倍の効率向上を実現する方法。公式の Task ツール構文、エージェントタイプ、そして並列実行を成功させるパターンを学びます。
Claude Code の最も強力な機能の一つがマルチエージェント実行です。これは並列で動作する専門化されたエージェントを生成する機能で、正しく使用すれば複雑なタスクで5〜10倍の効率向上を実現できます。
このガイドでは、公式の Task ツール構文、組み込みエージェントタイプ、そして並列実行の実践的なパターンを解説します。
Task ツールの理解
Task ツールは、サブエージェントを生成するための Claude Code のメカニズムです。公式ドキュメントによると:
公式構文
Task({
subagent_type: "Explore", // Required: "Explore" or "general-purpose"
model: "haiku", // Optional: "haiku", "sonnet", or "opus"
prompt: ` // Required: Task description
Explore authentication module (thoroughness: medium).
Find all JWT-related functions and their usage.
`,
run_in_background: false // Optional: Run asynchronously
})
利用可能な subagent_type 値
| subagent_type | 目的 | 最適なユースケース |
|---|---|---|
Explore | Haiku 4.5 による高速なコードベースナビゲーション | ファイル検索、パターンマッチング、構造分析 |
general-purpose | 複雑な多段階推論 | 実装、リファクタリング、コードレビュー |
モデル選択
// Haiku 4.5 - Fast & cheap (default for Explore)
Task({ subagent_type: "Explore", model: "haiku", ... })
// Sonnet 4.5 - Balanced (default for general-purpose)
Task({ subagent_type: "general-purpose", model: "sonnet", ... })
// Opus 4.5 - Most capable (critical tasks)
Task({ subagent_type: "general-purpose", model: "opus", ... })
コスト/速度のトレードオフ:
- Haiku 4.5: Sonnet と比較して2倍高速、1/3のコスト
- Sonnet 4.5: 最高のコーディング性能、Extended Thinking サポート
- Opus 4.5: 最高の知性、デフォルトで Thinking Mode 有効(v2.0.67+)
Explore エージェントの詳細
Explore エージェント(v2.1.0 で導入)は、高速なコードベース探索のために特別に設計されています。
徹底度レベル
// Quick - 10-30 seconds
Task({
subagent_type: "Explore",
model: "haiku",
prompt: "Explore auth module (thoroughness: quick). Find login handler."
})
// Medium - 30-60 seconds (recommended)
Task({
subagent_type: "Explore",
model: "haiku",
prompt: "Explore auth module (thoroughness: medium). Map JWT flow and middleware."
})
// Very Thorough - 60-120 seconds
Task({
subagent_type: "Explore",
model: "haiku",
prompt: "Explore auth module (thoroughness: very thorough). Complete security analysis."
})
なぜ Explore がより効率的なのか
従来のアプローチ(5つの連続ステップ):
1. Glob: find *auth*.ts → 15 seconds
2. Grep: search "JWT" → 15 seconds
3. Read: auth/index.ts → 10 seconds
4. Grep: find authenticate() → 15 seconds
5. Read: test files → 10 seconds
Total: 65 seconds
新しいアプローチ(1つの Explore エージェント):
Task({
subagent_type: "Explore",
model: "haiku",
prompt: "Explore authentication (thoroughness: medium). Focus on JWT, middleware, tests."
})
// Total: 30-45 seconds, same or better results
組み込み専門エージェント
Claude Code は以下の専門エージェントタイプを提供しています:
| エージェント | 役割 | 使用タイミング | 推奨モデル |
|---|---|---|---|
code-reviewer | コード品質分析 | 実装後 | Sonnet |
security-auditor | 脆弱性検出 | 認証/決済変更時 | Sonnet/Opus |
test-runner | テスト実行と分析 | コード変更後 | Haiku |
debugger | 根本原因分析 | エラー調査 | Sonnet |
refactor-assistant | コード改善 | 複雑さの削減 | Sonnet |
doc-writer | ドキュメント作成 | API 変更時 | Haiku/Sonnet |
順次実行 vs 並列実行
順次実行(遅い):
Task 1 (30s) → Task 2 (30s) → Task 3 (30s) → Task 4 (30s)
Total: 120 seconds
並列実行(速い):
Task 1 (30s) ┐
Task 2 (30s) ├→ All complete in 30 seconds
Task 3 (30s) │
Task 4 (30s) ┘
Total: 30 seconds
計算式: 並列実行時間 = max(個別の時間)、合計ではない。
コアパターン
パターン 1: 分析スウォーム
複数の Explore エージェントを起動して、異なる角度から同時に分析します。
Prompt: "I need to understand how user authentication works in this project."
Claude spawns 5 parallel agents:
→ Task 1 (Explore quick): Map auth-related file structure
→ Task 2 (Explore quick): Find all JWT/session references
→ Task 3 (Explore medium): Analyze middleware chain
→ Task 4 (Explore quick): Identify auth configuration
→ Task 5 (Explore quick): Review existing auth tests
Results synthesized into comprehensive overview.
実装:
// All 5 agents launch simultaneously
Task({ subagent_type: "Explore", model: "haiku",
prompt: "Map auth-related file structure (thoroughness: quick)" })
Task({ subagent_type: "Explore", model: "haiku",
prompt: "Find all JWT and session references (thoroughness: quick)" })
Task({ subagent_type: "Explore", model: "haiku",
prompt: "Analyze authentication middleware chain (thoroughness: medium)" })
Task({ subagent_type: "Explore", model: "haiku",
prompt: "Find auth configuration files (thoroughness: quick)" })
Task({ subagent_type: "Explore", model: "haiku",
prompt: "Review authentication test files (thoroughness: quick)" })
ユースケース:
- 不慣れなコードベースの探索
- 複雑な機能の理解
- 変更前の影響分析
- 技術的負債の評価
パターン 2: 分割統治
大きなタスクを並列で実行できる独立したサブタスクに分割します。
Prompt: "Refactor the payment module to use the new API client."
Claude spawns agents per file:
→ Agent 1: Refactor payment/checkout.ts
→ Agent 2: Refactor payment/subscription.ts
→ Agent 3: Refactor payment/refund.ts
→ Agent 4: Update payment/types.ts
→ Agent 5: Update tests in payment/__tests__/
Each agent has context about the new API client pattern.
実装:
// Shared context provided to all agents
const sharedContext = `
Migration context:
- Replace RestClient with new ApiClient from src/lib/api.ts
- Use new error handling pattern from src/lib/errors.ts
- Maintain backward compatibility for exported functions
`;
Task({ subagent_type: "general-purpose", model: "sonnet",
prompt: `${sharedContext}\n\nRefactor payment/checkout.ts` })
Task({ subagent_type: "general-purpose", model: "sonnet",
prompt: `${sharedContext}\n\nRefactor payment/subscription.ts` })
// ... etc
ユースケース:
- 複数ファイルのリファクタリング
- バッチ更新(名前変更、パターン変更)
- 大規模マイグレーション
- ファイル全体のドキュメント更新
パターン 3: 実装とレビュー
同時に構築とレビューを行い、問題を早期に発見します。
Prompt: "Implement user profile editing with proper validation."
Phase 1 - Implementation (parallel):
→ Agent 1: Implement API endpoint
→ Agent 2: Create form component
→ Agent 3: Write validation logic
Phase 2 - Review (parallel, starts after Phase 1):
→ Agent 4 (security-auditor): Security review
→ Agent 5 (code-reviewer): Quality check
→ Agent 6 (test-runner): Verify coverage
ユースケース:
- 新機能開発
- 重要なコード変更
- セキュリティに敏感な実装
- 高複雑度機能
パターン 4: 多角的レビュー
同じコードに対して異なる専門家の視点を得ます。
Prompt: "Review PR #123 comprehensively."
Claude spawns specialized reviewers:
→ Agent 1 (code-reviewer): Code quality and patterns
→ Agent 2 (security-auditor): Security vulnerabilities
→ Agent 3 (Explore): Performance implications
→ Agent 4 (test-runner): Test coverage analysis
→ Agent 5 (general-purpose): Backward compatibility
Synthesized review with categorized findings.
ユースケース:
- コードレビュー
- アーキテクチャの決定
- 技術提案
- 依存関係の更新
パターン 5: バグ調査
どこを探すべきか分からない場合の並列検索。
Prompt: "Users report 'undefined is not a function' on dashboard."
Claude spawns search agents:
→ Agent 1 (Explore): Search for error message in codebase
→ Agent 2 (Explore): Find recent dashboard changes
→ Agent 3 (Explore): Analyze dashboard dependencies
→ Agent 4 (Explore): Check for TypeScript errors
→ Agent 5 (Explore): Review related test failures
First agent to find strong lead guides investigation.
ユースケース:
- バグハンティング
- エラー原因の理解
- 非推奨の使用箇所の発見
- データフローのトレース
ベストプラクティス
1. 適切なモデルを選択する
Exploration/Search → Haiku 4.5
- File structure mapping
- Pattern searching
- Simple analysis
- Cost: ~$0.001 per task
Complex reasoning → Sonnet 4.5
- Code review
- Architecture planning
- Implementation
- Cost: ~$0.003 per task
Critical decisions → Opus 4.5
- Security analysis
- Complex refactoring
- Architectural decisions
- Cost: ~$0.015 per task
2. エージェントをフォーカスさせる
各エージェントは単一の明確な目標を持つべきです。
範囲が広すぎる(悪い例):
"Analyze the entire codebase and find all issues"
フォーカスされている(良い例):
Task({ prompt: "Find all usages of deprecated API v1" })
Task({ prompt: "Check for missing error handling in API routes" })
Task({ prompt: "Identify components without prop validation" })
3. 共有コンテキストを提供する
すべてのエージェントが必要なコンテキストを持つようにします:
const sharedContext = `
Context for all agents:
- We're migrating from REST to GraphQL
- Target files are in src/api/
- Use the new ApiClient from src/lib/api.ts
- Follow error handling patterns in src/lib/errors.ts
`;
Task({ prompt: `${sharedContext}\n\nTask 1: ...` })
Task({ prompt: `${sharedContext}\n\nTask 2: ...` })
4. バックグラウンドタスクを処理する
長時間実行されるタスクには run_in_background を使用します:
Task({
subagent_type: "general-purpose",
model: "sonnet",
prompt: "Comprehensive security audit of entire codebase",
run_in_background: true // Returns immediately, runs async
})
// Check on it later
TaskOutput({ task_id: "...", block: false })
5. 統合を計画する
複数のエージェントは複数の出力を生成します。それらの統合方法を計画してください:
After parallel analysis:
1. Collect findings from all agents
2. Deduplicate overlapping discoveries
3. Prioritize by severity/impact
4. Create actionable summary
実践例
機能開発ワークフロー
User: "Implement a notification system for order updates."
Phase 1 - Discovery (5 parallel Explore agents):
→ Map existing notification patterns
→ Find email/push notification code
→ Analyze order state machine
→ Review notification templates
→ Check existing event handlers
Phase 2 - Design (sequential, needs Phase 1 results):
→ Plan agent: Design notification architecture
Phase 3 - Implementation (4 parallel agents):
→ Create notification service
→ Add order event listeners
→ Build email templates
→ Write unit tests
Phase 4 - Review (3 parallel agents):
→ security-auditor: Check for data leaks
→ code-reviewer: Review patterns
→ test-runner: Verify coverage
バグ調査
User: "Production error: 'Payment failed' but money was charged."
Parallel investigation (5 Explore agents):
→ Search payment logs for error pattern
→ Analyze payment service error handling
→ Check Stripe webhook handlers
→ Review recent payment changes
→ Find similar issues in error tracking
Results:
- Agent 3 finds: Webhook handler doesn't retry on timeout
- Agent 4 confirms: Recent change added new timeout logic
- Agent 1 shows: Pattern started after deploy on Jan 5
Root cause identified in ~1 minute vs 10+ sequential.
コードベース監査
User: "Audit for security issues and tech debt."
Parallel audit (8 agents):
Security team:
→ security-auditor: SQL injection patterns
→ security-auditor: XSS vulnerabilities
→ security-auditor: Authentication issues
→ security-auditor: Sensitive data exposure
Quality team:
→ code-reviewer: Code duplication
→ code-reviewer: Complexity hotspots
→ test-runner: Coverage gaps
→ Explore: Outdated dependencies
All 8 agents work simultaneously.
Results categorized and prioritized.
パフォーマンスの考慮事項
並列が最も効果的な場合
- 真に独立したタスク
- I/O バウンドな操作(ファイル読み込み、API 呼び出し)
- 複数の視点から恩恵を受ける分析
- 大きな対象範囲(多くのファイル、多くのパターン)
並列の効果が低い場合
- 強い依存関係のあるタスク(A が B の前に完了する必要がある)
- 非常に短いタスク(オーバーヘッドが利点を上回る)
- 深い順次推論を必要とするタスク
- 限られたスコープ(1つのファイルまたは関数のみ)
オーバーヘッドの認識
並列実行にはオーバーヘッドがあります:
- エージェントの初期化:各約1〜2秒
- コンテキスト共有コスト
- 結果統合時間
5秒未満のタスクでは、順次実行の方が速い場合があります。
はじめに
今日:
- 1つの並列 Explore スウォームを試す:“Find all usages of X in the codebase”
- 順次探索との速度の違いに注目する
今週:
- 分析スウォームを使って複雑な機能を理解する
- 分割統治パターンを実験する
今月:
- 自分のワークフローに特有のパターンを開発する
- どのタスクが並列化から最も恩恵を受けるか特定する
- 異なるエージェントタイプに対してモデル選択を最適化する
クイックリファレンス
Task ツールテンプレート
Task({
subagent_type: "Explore" | "general-purpose",
model: "haiku" | "sonnet" | "opus",
prompt: "Clear, focused task description",
run_in_background: true | false
})
モデル選択ガイド
| タスクタイプ | モデル | 理由 |
|---|---|---|
| ファイル検索 | haiku | 高速、安価 |
| パターンマッチング | haiku | 高速、安価 |
| コードレビュー | sonnet | バランス型 |
| 実装 | sonnet | バランス型 |
| セキュリティ監査 | sonnet/opus | 徹底的 |
| アーキテクチャ | opus | 最高能力 |
並列実行ルール
Independent tasks → Launch simultaneously
Dependent tasks → Run sequentially
Mixed → Phase approach (parallel within, sequential between)
マルチエージェントアーキテクチャは、Claude Code との対話方法を変革します。順次プロンプトの代わりに、わずかな時間で完了する並列ワークフローをオーケストレーションします。
出典: Claude Code Documentation, Claude Code GitHub, CHANGELOG