0Pricing
Claude Architect · Aula

A Ferramenta Task e allowedTools

Crie subagentes e conceda a capacidade Task.

A Ferramenta Task e allowedTools é uma aula grátis de Claude Architect no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Claude Architect, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Claude Architect inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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 to
  • description — when to use this agent (this is how the coordinator selects it)
  • system_prompt — the role and instructions
  • allowed_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 text

Putting It Together

A correct multi-agent setup has a recognizable shape:

  • Coordinator's allowed_tools includes "Task" (plus minimal inspection tools).
  • Each subagent has a sharp description, a focused system_prompt, and a least-privilege allowed_tools of ~4-5 tools.
  • Every delegated prompt is self-contained because no history is inherited.
  • Independent tasks go out as parallel Task calls; 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 Task tool spawns subagents; the coordinator's allowed_tools must 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 Task at the hub.
  • Multiple Task calls 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.

Perguntas Frequentes

A aula “A Ferramenta Task e allowedTools” é grátis?

Sim — o texto completo de “A Ferramenta Task e allowedTools” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Claude Architect, atualize para CoddyKit PRO. O curso de Claude Architect inclui 4 aulas no total.

O que vou aprender em “A Ferramenta Task e allowedTools”?

Crie subagentes e conceda a capacidade Task. Você pratica Claude Architect com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Claude Architect?

Nenhuma experiência prévia é necessária. Claude Architect no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.

Quanto tempo leva a aula “A Ferramenta Task e allowedTools”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Claude Architect?

Sim. Cada aula de Claude Architect inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Blocos de Construção do Agent SDK
  2. Definindo um Agente
  3. A Ferramenta Task e allowedTools
  4. Princípio do Menor Privilégio
← Voltar para Claude Architect