概要
この章では、カスタムSubagentの作成方法について解説します。 前章でSubagentの概念と利点を学びました。 ここでは実際にSubagentを作成し、設定する方法を詳しく見ていきます。
クイックスタート
まずは最も簡単なSubagent作成方法を紹介します。
/agentsコマンドによる作成
/agentsコマンドを使用すると、対話的なインターフェースでSubagentを作成できます。
/agentsコマンドでは以下の操作が可能です。
- 利用可能なすべてのSubagent(組み込み、ユーザー、プロジェクト、プラグイン)を表示
- ガイド付きセットアップまたはClaude生成で新しいSubagentを作成
- 既存のSubagentの設定とツールアクセスを編集
- カスタムSubagentを削除
- 重複がある場合にどのSubagentがアクティブかを確認
以下の手順で作成します。
/agentsコマンドを実行してSubagentインターフェースを開く- 「Create new agent」を選択
- 「User-level」または「Project-level」を選択
- 「Generate with Claude」を選択してSubagentを生成
- ツールを選択(読み取り専用のみ、またはすべてのツール)
- モデルを選択(Haiku、Sonnet、Opusなど)
- 背景色を選択(実行中のSubagentを識別しやすくするため)
- 保存
Subagentの定義では、以下のオプションがあります。
- Claudeで生成 まずClaudeにSubagentを生成させ、その後カスタマイズする方法を推奨します
- 手動で作成
エディタで直接システムプロンプトを編集します(
eキーで外部エディタを起動)
作成したSubagentは、以下のように明示的に呼び出せます。
Use the code-reviewer subagent to check my recent changesSubagent名を指定することで、確実に目的のSubagentを使用できます。
ファイルを直接作成
コマンドを使わずに、ファイルを直接作成することもできます。
プロジェクトSubagentを作成する場合は以下のコマンドを実行します。
mkdir -p .claude/agentsユーザーSubagentを作成する場合は以下のコマンドを実行します。
mkdir -p ~/.claude/agents作成したディレクトリにMarkdownファイルを配置することで、Subagentが利用可能になります。
Subagentはセッション開始時に読み込まれます。
手動でファイルを追加した場合は、セッションを再起動するか、/agentsコマンドを実行して即座に読み込めます。
Subagentファイルの構造
Subagentは、YAMLフロントマターとMarkdownプロンプトで構成されるファイルです。
基本形式
Subagentファイルの基本構造を以下に示します。
---
name: your-subagent-name
description: Description of when this subagent should be invoked
tools: tool1, tool2, tool3
model: sonnet
---
Your subagent's system prompt goes here. This can be multiple paragraphs
and should clearly define the subagent's role, capabilities, and approach
to solving problems.
Include specific instructions, best practices, and any constraints
the subagent should follow.| name | your-subagent-name |
|---|---|
| description | Description of when this subagent should be invoked |
| tools | tool1, tool2, tool3 |
| model | sonnet |
Your subagent's system prompt goes here. This can be multiple paragraphs and should clearly define the subagent's role, capabilities, and approach to solving problems.
Include specific instructions, best practices, and any constraints the subagent should follow.
フロントマターの---で囲まれた部分にYAML形式で設定を記述し、その下にシステムプロンプトを記述します。
設定フィールド一覧
Subagentで使用可能な設定フィールドは以下のとおりです。
| フィールド | 必須 | 説明 |
|---|---|---|
name |
はい | 小文字とハイフンを使用した一意の識別子 |
description |
はい | Subagentの目的の自然言語説明 |
tools |
いいえ | 許可するツールのカンマ区切りリスト |
disallowedTools |
いいえ | 明示的に拒否するツールのリスト |
model |
いいえ | 使用するモデル(sonnet、opus、haiku、inherit) |
permissionMode |
いいえ | 権限処理モード |
skills |
いいえ | Subagentに読み込むSkills |
hooks |
いいえ | ライフサイクルHooks |
toolsを省略すると、メインスレッドのすべてのツールを継承します。
ツールアクセス制御
Subagentがアクセスできるツールを制御することで、セキュリティと動作の予測可能性を向上させます。
許可リスト方式
toolsフィールドで特定のツールのみを許可します。
---
name: safe-researcher
description: Research specialist with read-only access
tools: Read, Grep, Glob, Bash
---この例では、ファイル読み取りと検索に関連するツールのみがアクセス可能です。
拒否リスト方式
disallowedToolsフィールドで特定のツールを拒否します。
---
name: code-reviewer
description: Reviews code without making changes
disallowedTools: Write, Edit
---この例では、ファイル書き込みと編集が明示的に禁止されています。 それ以外のすべてのツールは使用可能です。
権限モード
permissionModeフィールドで権限の処理方法を制御できます。
| モード | 動作 |
|---|---|
default |
標準の権限チェック(プロンプトを表示) |
acceptEdits |
ファイル編集を自動承認 |
dontAsk |
権限プロンプトを自動拒否 |
bypassPermissions |
すべての権限チェックをスキップ(注意して使用) |
plan |
読み取り専用の探索モード |
権限モードの設定例を以下に示します。
---
name: auto-fixer
description: Automatically fixes code issues
permissionMode: acceptEdits
---bypassPermissionsは強力ですが、セキュリティリスクがあるため慎重に使用してください。
親がbypassPermissionsを使用している場合、この設定が優先され、オーバーライドできません。
特定のSubagentの無効化
特定のSubagentを無効にするには、settingsのdeny配列に追加します。
Task(subagent-name)の形式でSubagent名を指定します。
{
"permissions": {
"deny": ["Task(Explore)", "Task(my-custom-agent)"]
}
}この設定は組み込みSubagentとカスタムSubagentの両方に適用されます。
CLIフラグでも無効化できます。
claude --disallowedTools "Task(Explore)"このフラグにより、指定したSubagentがセッション中に呼び出されなくなります。
モデル選択
Subagentが使用するモデルを指定できます。
モデルエイリアス
使用可能なモデルエイリアスは以下のとおりです。
sonnetバランスの取れた性能とコスト(デフォルト)opus最高性能、複雑なタスク向けhaiku高速・低コスト、シンプルなタスク向けinheritメイン会話と同じモデルを使用
選択の指針
タスクの特性に応じてモデルを選択します。
| タスクタイプ | 推奨モデル | 理由 |
|---|---|---|
| コードベース探索 | haiku |
高速で低コスト |
| コードレビュー | sonnetまたはinherit |
バランスの取れた分析能力 |
| 複雑なデバッグ | opusまたはinherit |
深い推論が必要 |
| 一貫性が重要 | inherit |
メイン会話と同じ動作 |
inheritを使用すると、Subagentがメイン会話のモデル選択に適応し、セッション全体で一貫した機能と応答スタイルを確保できます。
Subagentスコープと優先度
Subagentは複数の場所に配置でき、それぞれ異なるスコープを持ちます。
スコープの種類
Subagentの配置場所とスコープは以下のとおりです。
| スコープ | 場所 | 有効範囲 |
|---|---|---|
| CLIフラグ | --agentsオプション |
現在のセッションのみ |
| プロジェクト | .claude/agents/ |
現在のプロジェクト |
| ユーザー | ~/.claude/agents/ |
すべてのプロジェクト |
| プラグイン | プラグインのagents/ディレクトリ |
プラグインがインストールされた場所 |
優先度
同名のSubagentが複数存在する場合、以下の優先度で解決されます。
flowchart TD
A[Subagent名の解決] --> B{CLIフラグで定義?}
B -->|はい| C[CLIフラグのSubagentを使用]
B -->|いいえ| D{プロジェクトレベルに存在?}
D -->|はい| E[プロジェクトSubagentを使用]
D -->|いいえ| F{ユーザーレベルに存在?}
F -->|はい| G[ユーザーSubagentを使用]
F -->|いいえ| H{プラグインに存在?}
H -->|はい| I[プラグインSubagentを使用]
H -->|いいえ| J[Subagentが見つからない]この図は、Subagent名の解決順序を示しています。 CLIフラグが最も高い優先度を持ち、プラグインが最も低い優先度となります。
CLIによる動的定義
--agentsフラグを使用して、セッション固有のSubagentを動的に定義できます。
--agentsフラグ
JSON形式でSubagentを定義する例を以下に示します。
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
}
}'このコマンドを実行すると、code-reviewerという名前のSubagentが現在のセッションで利用可能になります。
ユースケース
CLIによる動的定義は以下のユースケースで有効です。
- 設定のテスト Subagent設定を保存前に素早くテスト
- 一時的なSubagent 特定のセッションでのみ必要なSubagent
- 自動化スクリプト カスタムSubagentが必要な自動化処理
- 設定の共有 ドキュメントやスクリプトでSubagent定義を共有
Subagent Hooks
Hooksを使用して、Subagentの動作をより細かく制御できます。
フロントマターHooks
Subagentファイル内でHooksを定義できます。
---
name: validated-agent
description: Agent with tool validation
tools: Read, Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./validate.sh"
PostToolUse:
- matcher: "Edit|Write"
hooks:
- type: command
command: "./run-linter.sh"
Stop: []
---使用可能なHookタイプは以下のとおりです。
PreToolUseツール実行前に呼び出されるPostToolUseツール実行後に呼び出されるStopSubagent終了時に呼び出される
条件付きツール検証
Hooksを使用して、ツールの実行を条件付きで検証できます。 以下は読み取り専用のデータベースクエリを強制する例です。
Subagentファイルを以下のように定義します。
---
name: db-reader
description: Execute read-only database queries
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---
You are a database analyst with read-only access.
Execute SELECT queries to answer data questions.
You cannot modify data (INSERT, UPDATE, DELETE blocked).検証スクリプトを以下のように作成します。
#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
# 書き込み操作をブロック
if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE)\b' > /dev/null; then
echo "Blocked: Only SELECT queries allowed" >&2
exit 2
fi
exit 0このスクリプトは、SQLクエリに書き込み操作が含まれている場合にブロックします。 終了コード2を返すと、ツールの実行がキャンセルされます。
プロジェクトレベルHooks
settings.jsonでプロジェクト全体のSubagent Hooksを定義できます。
{
"hooks": {
"SubagentStart": [
{
"matcher": "db-agent",
"hooks": [
{ "type": "command", "command": "./setup-db.sh" }
]
}
],
"SubagentStop": [
{
"matcher": "db-agent",
"hooks": [
{ "type": "command", "command": "./cleanup-db.sh" }
]
}
]
}
}SubagentStartはSubagent開始時、SubagentStopはSubagent終了時に実行されます。
matcherでSubagent名をフィルタリングできます。
Subagentの例
実践的なSubagentの例を紹介します。
コードレビュアー
読み取り専用でコード品質とセキュリティをチェックするSubagentです。
---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: inherit
---
You are a senior code reviewer ensuring high standards of code quality and security.
When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately
Review checklist:
- Code is simple and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed
Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)
Include specific examples of how to fix issues.| name | code-reviewer |
|---|---|
| description | Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code. |
| tools | Read, Grep, Glob, Bash |
| model | inherit |
You are a senior code reviewer ensuring high standards of code quality and security.
When invoked:
- Run git diff to see recent changes
- Focus on modified files
- Begin review immediately
Review checklist:
- Code is simple and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed
Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)
Include specific examples of how to fix issues.
このSubagentはgit diffで変更を確認し、体系的なチェックリストに基づいてレビューを行います。
デバッガー
編集可能で根本原因分析に特化したSubagentです。
---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
---
You are an expert debugger specializing in root cause analysis.
When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works
Debugging process:
- Analyze error messages and logs
- Check recent code changes
- Form and test hypotheses
- Add strategic debug logging
- Inspect variable states
For each issue, provide:
- Root cause explanation
- Evidence supporting the diagnosis
- Specific code fix
- Testing approach
- Prevention recommendations
Focus on fixing the underlying issue, not just symptoms.| name | debugger |
|---|---|
| description | Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues. |
| tools | Read, Edit, Bash, Grep, Glob |
You are an expert debugger specializing in root cause analysis.
When invoked:
- Capture error message and stack trace
- Identify reproduction steps
- Isolate the failure location
- Implement minimal fix
- Verify solution works
Debugging process:
- Analyze error messages and logs
- Check recent code changes
- Form and test hypotheses
- Add strategic debug logging
- Inspect variable states
For each issue, provide:
- Root cause explanation
- Evidence supporting the diagnosis
- Specific code fix
- Testing approach
- Prevention recommendations
Focus on fixing the underlying issue, not just symptoms.
このSubagentはEditツールを持っているため、問題を特定した後に修正も行えます。
データサイエンティスト
SQLクエリとデータ分析に特化したSubagentです。
---
name: data-scientist
description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.
tools: Bash, Read, Write
model: sonnet
---
You are a data scientist specializing in SQL and BigQuery analysis.
When invoked:
1. Understand the data analysis requirement
2. Write efficient SQL queries
3. Use BigQuery command line tools (bq) when appropriate
4. Analyze and summarize results
5. Present findings clearly
Key practices:
- Write optimized SQL queries with proper filters
- Use appropriate aggregations and joins
- Include comments explaining complex logic
- Format results for readability
- Provide data-driven recommendations
For each analysis:
- Explain the query approach
- Document any assumptions
- Highlight key findings
- Suggest next steps based on data
Always ensure queries are efficient and cost-effective.| name | data-scientist |
|---|---|
| description | Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries. |
| tools | Bash, Read, Write |
| model | sonnet |
You are a data scientist specializing in SQL and BigQuery analysis.
When invoked:
- Understand the data analysis requirement
- Write efficient SQL queries
- Use BigQuery command line tools (bq) when appropriate
- Analyze and summarize results
- Present findings clearly
Key practices:
- Write optimized SQL queries with proper filters
- Use appropriate aggregations and joins
- Include comments explaining complex logic
- Format results for readability
- Provide data-driven recommendations
For each analysis:
- Explain the query approach
- Document any assumptions
- Highlight key findings
- Suggest next steps based on data
Always ensure queries are efficient and cost-effective.
このSubagentはsonnetモデルを明示的に指定しており、分析タスクに適したバランスの取れた性能を発揮します。
ベストプラクティス
効果的なSubagentを作成するためのベストプラクティスを紹介します。
Claudeで生成してからカスタマイズ
最初のSubagentはClaudeに生成させることを推奨します。
/agentsコマンドで「Claudeで生成」オプションを選択すると、適切な構造と内容を持つSubagentが生成されます。
生成後に必要に応じてカスタマイズすることで、効率的に高品質なSubagentを作成できます。
単一責任の原則
1つのSubagentには1つの明確な責任を持たせます。 すべてを行う汎用Subagentよりも、特定のタスクに特化したSubagentの方がパフォーマンスが高く、動作も予測可能です。
詳細なプロンプト作成
システムプロンプトには以下を含めます。
- 役割の明確な定義 Subagentが何をする存在かを明示
- 具体的な手順 タスクを実行する時のステップ
- チェックリスト 確認すべき項目のリスト
- 出力形式 結果をどのように報告するか
提供するガイダンスが多いほど、Subagentのパフォーマンスが向上します。
ツールアクセスの最小化
Subagentの目的に必要なツールのみを許可します。 これにより以下の利点があります。
- セキュリティの向上
- 予期しない動作の防止
- Subagentが関連するアクションに集中
バージョン管理への登録
プロジェクトSubagentをバージョン管理に登録することで、チーム全員が同じSubagentを使用できます。
git add .claude/agents/
git commit -m "chore: add custom agents"これにより、Subagentの改善をチームで協力して行えます。
Auto-Compaction
Subagentは自動コンパクション機能をサポートしています。
自動コンパクションの仕組み
Subagentのコンテキストが容量の約95%に達すると、自動的にコンパクションが実行されます。 コンパクションにより、古いコンテキストが要約され、新しいコンテキストのためのスペースが確保されます。
しきい値のカスタマイズ
環境変数でコンパクションのしきい値を変更できます。
# 50%の容量でコンパクションを実行
export CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=50早めにコンパクションを実行することで、コンテキストの損失を最小限に抑えられます。
コンパクションはトランスクリプトに記録されます。
{
"type": "system",
"subtype": "compact_boundary",
"compactMetadata": {
"trigger": "auto",
"preTokens": 167189
}
}この情報を確認することで、コンパクションがいつ発生したかを追跡できます。