← 記事一覧に戻る

SubAgentで作る、自分だけのAIアシスタント

#Claude Code#AI#開発生産性#自動化

SubAgentとは

SubAgentは、メインのClaude Codeエージェントから特定のタスクを委譲される専門化されたAIアシスタントです。

主な特徴

  • 独立したコンテキスト空間: 各SubAgentは独立したコンテキストウィンドウで動作し、メインスレッドのコンテキストを汚染しない
  • カスタマイズされたシステムプロンプト: 専門領域に特化した指示を含むプロンプトで動作
  • ツール制限: SubAgentごとに異なるツールセットを割り当て可能

使うメリット

メリット説明
コンテキスト管理長い検索結果やテスト実行がSubAgent内で処理され、メインコンテキストの消費を最小化
トークン効率不要な情報がメインスレッドに戻らず、トークン消費が削減される
並列処理複数のSubAgentが同時に異なるタスクを処理可能
専門的な知識領域特有の知識をシステムプロンプトに組み込み可能
セキュリティツール制限により、意図しないアクションのリスクを低減

SubAgentの定義方法

SubAgentは2つのレベルで定義できます。

# プロジェクトレベル(優先度高)
.claude/agents/*.md

# ユーザーレベル(全プロジェクト共通)
~/.claude/agents/*.md

プロジェクトレベルの定義はリポジトリにコミットして、チーム全体で共有できます。

基本的な設定ファイル構造

---
name: code-reviewer
description: Expert code review specialist. Use for quality, security, and maintainability reviews.
tools: Read, Grep, Glob, Bash
model: sonnet
---

# ここからシステムプロンプト

You are an expert code reviewer with deep expertise in...

YAMLフロントマッターの各フィールド

フィールド説明
nameSubAgentの一意識別子code-reviewer
descriptionいつ呼び出すかの説明Use for quality, security reviews
tools使用可能なツール(カンマ区切り)Read, Grep, Bash
modelモデル選択sonnet, opus, haiku

ツール設定のポイント

明示的にツールを指定する場合:

tools: Read, Grep, Glob

リストされたツールのみが使用可能になります。コードレビュー専用のSubAgentでは、EditWriteを除外することで「分析はできるが修正はできない」という制限を設けられます。

ツールを省略した場合:

メインスレッドのすべてのツール(MCPツール含む)を継承します。

実践的な例

1. セキュリティ監査用SubAgent

---
name: security-auditor
description: Security audit specialist. Use when performing security reviews or analyzing potentially vulnerable code.
tools: Read, Grep, Glob
model: sonnet
---

You are a security audit specialist with deep expertise in:

- OWASP Top 10
- Secure coding practices
- Vulnerability assessment
- Dependency security analysis

Your role:

1. Analyze code for security vulnerabilities
2. Check for common weaknesses (SQL injection, XSS, etc.)
3. Review dependency versions for known CVEs
4. Provide actionable remediation steps

Format your findings as:

- Severity: [Critical/High/Medium/Low]
- Vulnerability: [Name]
- Location: [File:Line]
- Recommendation: [Fix]

このSubAgentはRead, Grep, Globのみアクセス可能なので、コードを分析できますが修正はできません。

2. パフォーマンス最適化用SubAgent

---
name: performance-optimizer
description: Performance optimization specialist. Use PROACTIVELY when code changes might impact performance.
tools: Read, Edit, Bash, Grep
model: sonnet
---

You are a performance optimization specialist focused on:

- Database query optimization
- Algorithmic efficiency
- Memory usage reduction
- Async/await patterns
- Caching strategies

When analyzing code:

1. Profile the current implementation
2. Identify bottlenecks
3. Propose optimized alternatives
4. Measure impact of changes

こちらはEditも含まれているので、提案だけでなく実際の修正も行えます。

3. TypeScript専門家SubAgent

---
name: typescript-expert
description: TypeScript specialist. Use for type safety issues, generic types, and TypeScript best practices.
tools: Read, Edit, Grep, Glob
model: sonnet
---

You are a TypeScript expert with deep knowledge of:

- Advanced type system features
- Generic types and type inference
- Type guards and narrowing
- Utility types and mapped types
- Module systems and declaration files

Focus on:

1. Improving type safety
2. Eliminating `any` types where possible
3. Using proper generic constraints
4. Implementing discriminated unions

SubAgentの呼び出し方

明示的な呼び出し

プロンプトで直接SubAgentを指定できます:

Use the security-auditor subagent to check my authentication code.
code-reviewerエージェントを使って、このPRの変更をレビューしてください。

自動選択

SubAgentのdescriptionフィールドがプロンプトの内容とマッチすると、自動的に適切なSubAgentが呼び出されます。そのため、descriptionは具体的かつ明確に書くことが重要です。

ベストプラクティス

1. 単一責任の原則

1つのSubAgentは1つの明確な責任を持つべきです。「セキュリティとパフォーマンスと可読性をチェックする」ような複合的なSubAgentは避け、それぞれ別のSubAgentとして定義しましょう。

2. 明確なdescriptionを書く

# 良い例
description: Security audit specialist. Use when performing security reviews or analyzing potentially vulnerable code.

# 悪い例
description: Helps with security stuff.

3. 最小限のツール権限

SubAgentには必要最小限のツールのみを与えましょう。

# レビュー専用(読み取りのみ)
tools: Read, Grep, Glob

# 開発用(フルアクセス)
tools: Read, Write, Edit, Bash, Grep

4. モデルの適切な選択

model: opus    # 複雑なタスク、高品質が必要な場合
model: sonnet  # バランスの取れた用途(推奨)
model: haiku   # シンプルなタスク、高速処理が必要な場合

5. バージョン管理

プロジェクトレベルのSubAgent(.claude/agents/)はリポジトリにコミットして、チーム全体で共有・改善しましょう。

スラッシュコマンドとの使い分け

Claude Codeには似たような拡張機能として「スラッシュコマンド」があります。どちらを使うべきか迷うことがあるので、違いと使い分けを整理します。

機能の比較

特性SubAgentスラッシュコマンド
実行方式独立したエージェントとして実行メインスレッドでプロンプトを展開
コンテキスト独立したコンテキスト空間メインスレッドのコンテキストを共有
ツール制限個別に設定可能メインスレッドのツールをそのまま使用
モデル選択個別に設定可能メインスレッドのモデルを使用
配置場所.claude/agents/*.md.claude/commands/*.md
呼び出し方プロンプトで指示 or 自動選択/command-name で明示的に呼び出し

SubAgentを選ぶべき場面

  • コンテキストの分離が必要な場合: 大量のファイルを検索・分析する処理など、メインスレッドのコンテキストを汚染したくない場合
  • ツール制限が必要な場合: レビュー専用(読み取りのみ)など、特定のツールのみを許可したい場合
  • 異なるモデルを使いたい場合: 軽量なタスクにはhaiku、複雑なタスクにはopusなど、タスクに応じてモデルを変えたい場合
  • 自動選択させたい場合: プロンプトの内容に応じて、適切なエージェントを自動的に呼び出したい場合

スラッシュコマンドを選ぶべき場面

  • 定型的なプロンプトの再利用: 毎回同じ指示を書くのが面倒な場合に、テンプレート化して呼び出す
  • 引数を渡したい場合: /review-pr 123 のように、コマンドに引数を渡してカスタマイズしたい場合
  • 会話の流れを維持したい場合: メインスレッドのコンテキストを活用して、前後の会話を踏まえた処理をしたい場合
  • シンプルな拡張で十分な場合: ツール制限やモデル選択が不要で、プロンプトのテンプレート化だけで事足りる場合

具体例で比較

セキュリティレビューをSubAgentで実装する場合:

# .claude/agents/security-auditor.md

---

name: security-auditor
description: Security audit specialist. Use when performing security reviews.
tools: Read, Grep, Glob
model: sonnet

---

You are a security audit specialist...
  • ツールがRead, Grep, Globに制限されるため、コードを修正される心配がない
  • 大量のファイルを検索しても、メインコンテキストは汚染されない
  • 「セキュリティレビューして」と言うだけで自動的に呼び出される

同じことをスラッシュコマンドで実装する場合:

# .claude/commands/security-review.md

---

## description: Perform a security review of the codebase

Perform a comprehensive security review focusing on:

- OWASP Top 10 vulnerabilities
- Input validation and sanitization
- Authentication and authorization
  ...
  • /security-review で明示的に呼び出す
  • メインスレッドで実行されるため、コンテキストを消費する
  • ツール制限がないため、意図せずコードを修正する可能性がある

両方を組み合わせる

実際には、スラッシュコマンドからSubAgentを呼び出すこともできます:

# .claude/commands/full-review.md

---

## description: Perform a comprehensive code review

Use the following subagents to review this PR:

1. security-auditor: Check for security vulnerabilities
2. performance-optimizer: Check for performance issues
3. code-reviewer: Check for code quality

このように組み合わせることで、複数のSubAgentを協調させた複雑なワークフローを、シンプルなコマンドで呼び出せます。

Agent SDKでの利用

Claude Agent SDKを使用している場合は、プログラマティックにSubAgentを定義できます。

import { query } from "@anthropic-ai/claude-code";

const result = await query({
  prompt: "Review this API for security issues",
  options: {
    agents: {
      "security-auditor": {
        description: "Security audit specialist",
        prompt: `You are a security audit specialist...`,
        tools: ["Read", "Grep", "Glob"],
        model: "sonnet",
      },
    },
  },
});

この方法では、実行時に動的にSubAgentを定義できるため、より柔軟な構成が可能です。

まとめ

SubAgentを活用することで、以下のメリットが得られます:

  • 専門的なタスクを高品質に処理できる
  • メインコンテキストの汚染を防ぎ、トークン効率が向上する
  • ツール制限によりセキュリティを確保できる
  • チームで共有してワークフローを標準化できる

プロジェクトの特性に合わせたSubAgentを定義して、開発効率を向上させましょう。