Task 工具与 allowedTools
生成子代理并授予 Task 能力。
Task 工具与 allowedTools 是 CoddyKit 上的免费 Claude Architect 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Claude Architect 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Claude Architect 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Subagents Exist
A single agent that does everything keeps too much in its head: history, half-finished subtasks, and verbose tool output all compete for attention. Subagents let a coordinator break a big job into focused pieces and hand each piece to a fresh worker.
The Agent SDK exposes this through one capability: the Task tool. When a coordinator calls Task, the SDK spins up a subagent with its own clean context to handle one delegated unit of work, then returns the result to the coordinator.
This is the foundation of the hub-and-spoke multi-agent pattern: one coordinator at the hub, many specialized subagents on the spokes.
The Coordinator's Job
In hub-and-spoke, the coordinator never does the detailed work itself. It owns five responsibilities:
- Decompose the request into independent tasks
- Delegate each task to a subagent via
Task - Aggregate the returned results
- Route follow-up work based on what came back
- Handle errors, including partial results
To delegate at all, the coordinator must be allowed to use the Task tool. If Task is missing from its allowedTools, it cannot spawn anything and will try to do everything alone.
Granting the Task Capability
Capabilities are granted explicitly. The coordinator's allowedTools (or allowed_tools) list must include "Task" for delegation to work. This is a deliberate, auditable grant, not an automatic default.
Notice that the coordinator here is given only what it needs to orchestrate: Task to spawn workers and Read to inspect inputs. It does not get Bash or Write because it is not supposed to touch the system directly.
from claude_agent_sdk import ClaudeAgentOptions
coordinator = ClaudeAgentOptions(
system_prompt="You are a coordinator. Decompose the"
" request and delegate each part via Task.",
# Task = permission to spawn subagents
allowed_tools=["Task", "Read"],
)Defining a Subagent
Each subagent is described by an AgentDefinition with four parts:
name— a short identifier the coordinator delegates todescription— when to use this agent (this is how the coordinator selects it)system_prompt— the role and instructionsallowed_tools— the tools this worker may use
The description matters most: just like tool descriptions, it is the primary selection signal. A vague description leads the coordinator to delegate to the wrong worker.
researcher = {
"name": "researcher",
"description": "Searches the web and summarizes"
" findings for a single topic. Use for"
" any open-ended fact-finding task.",
"system_prompt": "You research ONE topic and return"
" a cited summary.",
"allowed_tools": ["WebSearch", "Read"],
}Least Privilege per Subagent
Each subagent's allowed_tools should follow least privilege: grant only the tools the role genuinely needs, scoped to that role.
A research worker gets WebSearch and Read — never Bash or process_refund. A file-writer gets Write and Edit. Narrow tool sets also improve selection reliability: 4-5 tools per agent is optimal, and giving an agent 18+ tools degrades how reliably it picks the right one.
Critically, most subagents should not receive Task themselves. Delegation authority belongs at the hub; handing it out widely creates uncontrolled spawning.
The Context Isolation Rule
This is the single most tested fact about subagents: subagents do NOT inherit the coordinator's conversation history.
Each subagent starts with a clean context. It sees only what you put in its prompt. That isolation is a feature — it prevents one bloated history from polluting every worker — but it means the coordinator carries a responsibility: all context the subagent needs must be passed explicitly in its task prompt.
If a subagent needs a file path, a customer ID, a deadline, or prior findings, the coordinator must include them in the delegated instruction. Assuming the subagent 'already knows' is the classic failure.
Passing Context Explicitly
Because nothing is inherited, write task prompts that are self-contained. Bundle every fact the worker needs into the prompt string the coordinator sends.
Compare a bad delegation ('research the topic') with a good one that names the topic, the scope, the required output shape, and the constraints. The subagent has no other source of truth.
# Coordinator builds a SELF-CONTAINED task prompt
task_prompt = (
"Research: 'EU AI Act enforcement timeline'.\n"
"Scope: official sources published after 2024-01.\n"
"Return: 3 bullet findings, each with a source URL"
" and publication date.\n"
"Do NOT cover non-EU regulation."
)
# This whole string is the subagent's ONLY context.Parallel Delegation
When the coordinator issues multiple Task calls in a single response, those subagents run in parallel. This is how a research system fans out across several topics at once instead of investigating them one after another.
Use parallel Tasks when the subtasks are independent — researching three separate topics, reviewing three unrelated files. If task B needs task A's output, you cannot parallelize them; the coordinator must wait for A, then delegate B in a later turn.
# Three independent topics -> three Task calls in ONE
# response -> they execute concurrently.
topics = ["data residency", "audit rights", "breach SLA"]
# The model emits three tool_use blocks for Task,
# each with its own self-contained prompt, in a
# single assistant turn. The SDK runs them in parallel
# and returns all three results together.Aggregating and Handling Partial Results
After parallel workers return, the coordinator aggregates. Real systems must tolerate one worker failing without aborting the whole job.
If two of three researchers succeed and one hits an access failure, the coordinator should keep the two good results, annotate the gap, and report partial results — not throw the whole run away. Distinguish a genuine access failure (maybe retry) from a valid empty result (no matches found). Recover transient faults inside the subagent; escalate only the non-recoverable ones, carrying the partial results upward.
Silently dropping a failed worker or aborting everything on one error are both anti-patterns.
Stopping the Loop Correctly
Delegation runs inside the agentic loop. The coordinator sends a request, inspects stop_reason, runs any Task tool calls, appends their results to the message history, and repeats until stop_reason is end_turn.
You terminate on the stop reason, never by scanning the model's text for words like 'done' or 'finished'. Decisions about which subagent to spawn next are model-driven. An iteration cap is a safety net against runaway spawning — not the primary way you stop.
while True:
resp = client.messages.create(**req)
if resp.stop_reason == "tool_use":
results = run_tools(resp) # may include Task
req["messages"] += [assistant(resp), user(results)]
continue
if resp.stop_reason == "end_turn":
break # terminate on stop_reason, not on textPutting It Together
A correct multi-agent setup has a recognizable shape:
- Coordinator's
allowed_toolsincludes"Task"(plus minimal inspection tools). - Each subagent has a sharp
description, a focusedsystem_prompt, and a least-privilegeallowed_toolsof ~4-5 tools. - Every delegated prompt is self-contained because no history is inherited.
- Independent tasks go out as parallel
Taskcalls; dependent ones are sequenced. - The coordinator aggregates, tolerates partial failure, and stops on
end_turn.
Get the Task grant and the explicit-context rule right, and the rest of orchestration falls into place.
agents = {"researcher": researcher, "writer": writer}
coordinator = ClaudeAgentOptions(
system_prompt="Decompose, delegate via Task, aggregate.",
allowed_tools=["Task", "Read"], # hub holds Task
agents=agents, # spokes, least privilege
)Quick Check
A research coordinator delegates three independent topics to three subagents with one batch of parallel Task calls. One subagent returns a summary that omits a fact the coordinator mentioned earlier in its own conversation. What is the most likely architectural cause?
Recap
Key takeaways for the exam:
- The
Tasktool spawns subagents; the coordinator'sallowed_toolsmust include"Task"to delegate. - Architecture is hub-and-spoke: coordinator decomposes, delegates, aggregates, routes, and handles errors.
- Subagents inherit no conversation history — pass all needed context explicitly in each task prompt.
- An AgentDefinition = name, description, system_prompt, allowed_tools; the description drives selection.
- Apply least privilege per subagent; aim for ~4-5 tools, and keep
Taskat the hub. - Multiple
Taskcalls in one response run in parallel; sequence only when dependent. - Tolerate partial results; stop on
end_turn, never by parsing text, with iteration caps only as a safety net.
用 AI 导师学习 Python — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 26
- 课程
- 104
常见问题解答
「Task 工具与 allowedTools」课时是免费的吗?
是的 — 「Task 工具与 allowedTools」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Claude Architect 课程的其余内容,请升级到 CoddyKit PRO。 Claude Architect 课程共包含 4 节课。
「Task 工具与 allowedTools」这节课中我会学到什么?
生成子代理并授予 Task 能力。 你通过在浏览器中直接运行的动手代码来练习 Claude Architect,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Claude Architect 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Claude Architect 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「Task 工具与 allowedTools」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Claude Architect 课中编写并运行代码吗?
能。每节 Claude Architect 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 代理 SDK 的构件
- 定义代理
- Task 工具与 allowedTools
- 最小权限原则