跳轉到主要內容
Claude Code 中的自訂子代理是專門的 AI 助手,可以被調用來處理特定類型的任務。它們通過提供具有自訂系統提示、工具和獨立上下文視窗的特定任務配置,實現更高效的問題解決。

什麼是子代理?

子代理是預先配置的 AI 人格,Claude Code 可以將任務委派給它們。每個子代理:
  • 具有特定的目的和專業領域
  • 使用與主對話分離的自己的上下文視窗
  • 可以配置為允許使用特定工具
  • 包含指導其行為的自訂系統提示
當 Claude Code 遇到與子代理專業領域相匹配的任務時,它可以將該任務委派給專門的子代理,該子代理獨立工作並返回結果。

主要優勢

上下文保留

每個子代理在自己的上下文中運作,防止主對話被污染,並使其專注於高層次目標。

專門的專業知識

子代理可以使用特定領域的詳細指示進行微調,從而提高指定任務的成功率。

可重用性

建立後,子代理可以在不同專案中使用,並與您的團隊共享以實現一致的工作流程。

靈活的權限

每個子代理可以具有不同的工具存取級別,允許您將強大的工具限制為特定的子代理類型。

快速開始

要建立您的第一個子代理:
1

開啟子代理介面

執行以下命令:
/agents
2

選擇「建立新代理」

選擇是建立專案級別還是使用者級別的子代理
3

定義子代理

  • 建議:先使用 Claude 生成,然後自訂以使其成為您自己的
  • 詳細描述您的子代理及其應該被使用的時機
  • 選擇您想要授予存取權限的工具(或留空以繼承所有工具)
  • 介面顯示所有可用工具,使選擇變得容易
  • 如果您使用 Claude 生成,您也可以通過按 e 在自己的編輯器中編輯系統提示
4

儲存並使用

您的子代理現在可用!Claude 將在適當時自動使用它,或者您可以明確調用它:
> Use the code-reviewer subagent to check my recent changes

子代理配置

檔案位置

子代理儲存為具有 YAML 前置資料的 Markdown 檔案,位於兩個可能的位置:
類型位置範圍優先級
專案子代理.claude/agents/在目前專案中可用最高
使用者子代理~/.claude/agents/在所有專案中可用較低
當子代理名稱衝突時,專案級別的子代理優先於使用者級別的子代理。

外掛程式代理

外掛程式可以提供與 Claude Code 無縫整合的自訂子代理。外掛程式代理的工作方式與使用者定義的代理相同,並出現在 /agents 介面中。 外掛程式代理位置:外掛程式在其 agents/ 目錄中包含代理(或外掛程式清單中指定的自訂路徑)。 使用外掛程式代理
  • 外掛程式代理與您的自訂代理一起出現在 /agents
  • 可以明確調用:“Use the code-reviewer agent from the security-plugin”
  • 可以在適當時由 Claude 自動調用
  • 可以通過 /agents 介面進行管理(檢視、檢查)
有關建立外掛程式代理的詳細資訊,請參閱外掛程式元件參考

基於 CLI 的配置

您也可以使用 --agents CLI 標誌動態定義子代理,該標誌接受 JSON 物件:
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"
  }
}'
優先級:CLI 定義的子代理的優先級低於專案級別的子代理,但高於使用者級別的子代理。 使用案例:此方法適用於:
  • 快速測試子代理配置
  • 不需要儲存的工作階段特定子代理
  • 需要自訂子代理的自動化指令碼
  • 在文件或指令碼中共享子代理定義
有關 JSON 格式和所有可用選項的詳細資訊,請參閱 CLI 參考文件

檔案格式

每個子代理都在具有以下結構的 Markdown 檔案中定義:
---
name: your-sub-agent-name
description: Description of when this subagent should be invoked
tools: tool1, tool2, tool3  # Optional - inherits all tools if omitted
model: sonnet  # Optional - specify model alias or 'inherit'
---

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使用小寫字母和連字符的唯一識別碼
description子代理目的的自然語言描述
tools特定工具的逗號分隔清單。如果省略,則從主執行緒繼承所有工具
model此子代理要使用的模型。可以是模型別名(sonnetopushaiku)或 'inherit' 以使用主對話的模型。如果省略,則預設為配置的子代理模型

模型選擇

model 欄位允許您控制子代理使用的 AI 模型
  • 模型別名:使用可用別名之一:sonnetopushaiku
  • 'inherit':使用與主對話相同的模型(對於一致性很有用)
  • 省略:如果未指定,則使用為子代理配置的預設模型(sonnet
當您希望子代理適應主對話的模型選擇,確保整個工作階段中的功能和回應風格一致時,使用 'inherit' 特別有用。

可用工具

子代理可以被授予存取 Claude Code 任何內部工具的權限。有關可用工具的完整清單,請參閱工具文件
建議:使用 /agents 命令修改工具存取 - 它提供了一個互動式介面,列出所有可用工具,包括任何連接的 MCP 伺服器工具,使選擇您需要的工具變得更容易。
您有兩個選項來配置工具:
  • 省略 tools 欄位以從主執行緒繼承所有工具(預設),包括 MCP 工具
  • 指定個別工具作為逗號分隔清單以進行更細粒度的控制(可以手動編輯或通過 /agents 編輯)
MCP 工具:子代理可以存取來自配置的 MCP 伺服器的 MCP 工具。當省略 tools 欄位時,子代理繼承主執行緒可用的所有 MCP 工具。

管理子代理

使用 /agents 命令(建議)

/agents 命令提供了一個全面的子代理管理介面:
/agents
這會開啟一個互動式選單,您可以在其中:
  • 檢視所有可用的子代理(內建、使用者和專案)
  • 使用引導式設定建立新的子代理
  • 編輯現有的自訂子代理,包括其工具存取
  • 刪除自訂子代理
  • 查看存在重複項時哪些子代理處於活動狀態
  • 輕鬆管理工具權限,包含所有可用工具的完整清單

直接檔案管理

您也可以通過直接使用其檔案來管理子代理:
# Create a project subagent
mkdir -p .claude/agents
echo '---
name: test-runner
description: Use proactively to run tests and fix failures
---

You are a test automation expert. When you see code changes, proactively run the appropriate tests. If tests fail, analyze the failures and fix them while preserving the original test intent.' > .claude/agents/test-runner.md

# Create a user subagent
mkdir -p ~/.claude/agents
# ... create subagent file

有效使用子代理

自動委派

Claude Code 根據以下內容主動委派任務:
  • 您的請求中的任務描述
  • 子代理配置中的 description 欄位
  • 目前上下文和可用工具
為了鼓勵更主動的子代理使用,在您的 description 欄位中包含”use PROACTIVELY”或”MUST BE USED”之類的短語。

明確調用

通過在您的命令中提及特定的子代理來請求它:
> Use the test-runner subagent to fix failing tests
> Have the code-reviewer subagent look at my recent changes
> Ask the debugger subagent to investigate this error

內建子代理

Claude Code 包含開箱即用的內建子代理:

Plan 子代理

Plan 子代理是一個專門的內建代理,設計用於計畫模式期間。當 Claude 在計畫模式(非執行模式)中運作時,它使用 Plan 子代理進行研究並收集有關您的程式碼庫的資訊,然後再提出計畫。 主要特徵:
  • 模型:使用 Sonnet 進行更強大的分析
  • 工具:可以存取 Read、Glob、Grep 和 Bash 工具以進行程式碼庫探索
  • 目的:搜尋檔案、分析程式碼結構和收集上下文
  • 自動調用:當 Claude 在計畫模式中且需要研究程式碼庫時,它會自動使用此代理
工作原理: 當您處於計畫模式且 Claude 需要瞭解您的程式碼庫以建立計畫時,它會將研究任務委派給 Plan 子代理。這可以防止代理的無限嵌套(子代理無法生成其他子代理),同時仍然允許 Claude 收集必要的上下文。 範例情景:
User: [In plan mode] Help me refactor the authentication module

Claude: Let me research your authentication implementation first...
[Internally invokes Plan subagent to explore auth-related files]
[Plan subagent searches codebase and returns findings]
Claude: Based on my research, here's my proposed plan...
Plan 子代理僅在計畫模式中使用。在正常執行模式中,Claude 使用通用代理或您建立的其他自訂子代理。

範例子代理

程式碼審查員

---
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: 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: 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.

最佳實踐

  • 從 Claude 生成的代理開始:我們強烈建議使用 Claude 生成您的初始子代理,然後對其進行迭代以使其成為您個人的。這種方法會給您最好的結果 - 一個堅實的基礎,您可以根據您的特定需求進行自訂。
  • 設計專注的子代理:建立具有單一、明確責任的子代理,而不是試圖讓一個子代理做所有事情。這可以改進效能並使子代理更可預測。
  • 編寫詳細的提示:在您的系統提示中包含特定的指示、範例和約束。您提供的指導越多,子代理的效能就越好。
  • 限制工具存取:僅授予子代理目的所需的工具。這可以改進安全性並幫助子代理專注於相關操作。
  • 版本控制:將專案子代理簽入版本控制,以便您的團隊可以從中受益並協作改進它們。

進階用法

鏈接子代理

對於複雜的工作流程,您可以鏈接多個子代理:
> First use the code-analyzer subagent to find performance issues, then use the optimizer subagent to fix them

動態子代理選擇

Claude Code 根據上下文智慧地選擇子代理。使您的 description 欄位具體且面向行動以獲得最佳結果。

可恢復的子代理

子代理可以被恢復以繼續之前的對話,這對於需要在多個調用中繼續的長期執行研究或分析任務特別有用。 工作原理:
  • 每個子代理執行都被分配一個唯一的 agentId
  • 代理的對話儲存在一個單獨的文字檔案中:agent-{agentId}.jsonl
  • 您可以通過提供其 agentId(通過 resume 參數)來恢復之前的代理
  • 恢復時,代理會從其之前的對話中繼續,具有完整的上下文
範例工作流程: 初始調用:
> Use the code-analyzer agent to start reviewing the authentication module

[Agent completes initial analysis and returns agentId: "abc123"]
恢復代理:
> Resume agent abc123 and now analyze the authorization logic as well

[Agent continues with full context from previous conversation]
使用案例:
  • 長期執行研究:將大型程式碼庫分析分解為多個工作階段
  • 迭代細化:在不失去上下文的情況下繼續細化子代理的工作
  • 多步驟工作流程:讓子代理在保持上下文的同時順序執行相關任務
技術詳細資訊:
  • 代理文字儲存在您的專案目錄中
  • 在恢復期間禁用記錄以避免複製訊息
  • 同步和非同步代理都可以被恢復
  • resume 參數接受來自先前執行的代理 ID
程式設計用法: 如果您使用 Agent SDK 或直接與 AgentTool 互動,您可以傳遞 resume 參數:
{
  "description": "Continue analysis",
  "prompt": "Now examine the error handling patterns",
  "subagent_type": "code-analyzer",
  "resume": "abc123"  // Agent ID from previous execution
}
追蹤您可能想要稍後恢復的任務的代理 ID。Claude Code 在子代理完成其工作時顯示代理 ID。

效能考慮

  • 上下文效率:代理有助於保留主上下文,實現更長的整體工作階段
  • 延遲:子代理每次被調用時都以乾淨的狀態啟動,並且在收集有效執行其工作所需的上下文時可能會增加延遲。

相關文件

  • 外掛程式 - 通過外掛程式使用自訂代理擴展 Claude Code
  • 斜線命令 - 瞭解其他內建命令
  • 設定 - 配置 Claude Code 行為
  • 鉤子 - 使用事件處理程式自動化工作流程