La herramienta Task y allowedTools
Cree subagentes y asígneles la capacidad Task.
La herramienta Task y allowedTools es una lección gratuita de Claude Architect en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Claude Architect, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Claude Architect incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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.
Preguntas frecuentes
¿La lección «La herramienta Task y allowedTools» es gratis?
Sí — el texto completo de «La herramienta Task y allowedTools» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Claude Architect, actualiza a CoddyKit PRO. El curso de Claude Architect incluye 4 lecciones en total.
¿Qué aprenderé en «La herramienta Task y allowedTools»?
Cree subagentes y asígneles la capacidad Task. Practicas Claude Architect con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Claude Architect?
No se requiere experiencia previa. Claude Architect en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «La herramienta Task y allowedTools»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Claude Architect?
Sí. Cada lección de Claude Architect incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Componentes básicos del Agent SDK
- Definición de un agente
- La herramienta Task y allowedTools
- Principio de mínimo privilegio