๐Ÿ“š Domain 1 ยท Task Statement 1.3

Configure Subagent Invocation, Context Passing & Spawning

๐Ÿ“Š Domain Weight: 27% โญ High Exam Priority ๐Ÿ”— Scenario: Developer Productivity & Research System

Knowing that you should use subagents is one thing โ€” knowing exactly how to invoke them, what to pass, how to spawn them in parallel, and how to fork sessions for exploration is what this task statement tests. These mechanics are the plumbing that makes multi-agent systems actually work in production.

๐Ÿ“‹ Contents

  1. Analogy โ€” The Task Briefing Packet
  2. The Task Tool โ€” The Spawning Mechanism
  3. allowedTools โ€” The Permission Gate
  4. AgentDefinition Configuration
  5. Explicit Context Passing โ€” What & How
  6. Structured Metadata in Handoffs
  7. Parallel Subagent Spawning
  8. Fork-Based Session Management
  9. Goal-Oriented vs Step-by-Step Coordinator Prompts
  10. Summary & Exam Key Points

๐Ÿ“ฆ Analogy โ€” The Task Briefing Packet

๐ŸŽ–๏ธ Analogy โ€” Military Mission Briefing

A field commander (coordinator) needs to dispatch three specialist teams (subagents) simultaneously. Each team gets a sealed briefing packet โ€” a self-contained document with: the mission objective, relevant intelligence gathered so far, the tools they're authorised to use, and the output format expected back.

Teams don't share packets. Team Alpha doesn't know what Team Bravo was briefed on. The commander holds the full picture. When teams return, the commander synthesises their reports into a combined intelligence assessment.

The Task tool is the sealed briefing packet. The allowedTools list is the authorised equipment list. AgentDefinition is the team's role card. And explicit context passing means writing everything the team needs into the packet โ€” because they can't radio the commander mid-mission to ask for background.

๐Ÿ› ๏ธ The Task Tool โ€” The Spawning Mechanism

In the Claude Agent SDK, subagents are spawned via the Task tool. When the coordinator emits a tool_use block with name: "Task", the SDK creates a new isolated agent session and runs it with the provided prompt and configuration.

๐Ÿ’ก Key Fact

The Task tool is itself just another tool in Claude's tool list. For a coordinator to spawn subagents, "Task" must appear in its allowedTools array โ€” otherwise, Claude will never be able to call it, even if it wants to. This is a frequently tested configuration detail.

Figure 1 โ€” Task Tool Invocation Flow
COORDINATOR Emits Task tool calls stop_reason="tool_use" Task calls AGENT SDK Reads task tool params Creates isolated session Applies allowedTools Applies AgentDefinition Subagent A Isolated context Subagent B Isolated context Subagent C Isolated context Results Returned to coordinator All three spawned simultaneously โ€” parallel execution
Python โ€” Spawning a Subagent via Task Tool
# The coordinator's tool definition MUST include "Task"
coordinator_config = {
    "allowedTools": ["Task", "read_file", "web_search"],
    "systemPrompt": "You are a research coordinator..."
}

# When coordinator calls Task, SDK receives:
task_call = {
    "type": "tool_use",
    "name": "Task",
    "input": {
        "description": "Web Search Specialist",
        "prompt": """Search for recent articles on AI in music (2022-2024).
Return: JSON array of {title, url, key_finding, date}
Limit: Top 10 most relevant results.""",
        "allowedTools": ["web_search", "read_url"]  # Scoped
    }
}

๐Ÿ”‘ allowedTools โ€” The Permission Gate

allowedTools is a critical security and reliability control. It defines exactly which tools each agent can access. Getting this right prevents agents from mis-using tools outside their specialisation and reduces tool-selection errors.

Agent RoleAppropriate allowedToolsWhy Restricted
CoordinatorTask, web_search, read_fileNeeds Task to spawn subagents. May do light research itself.
Web Search Agentweb_search, read_url, extract_contentOnly web tools. No file write โ€” prevents accidental data loss.
Document Analystread_file, extract_text, parse_pdfFile-read tools only. No web access โ€” prevents scope creep.
Synthesis Agentverify_fact (scoped lookup only)Minimal tools. Prevents synthesis agent attempting full web searches.
Report Generatorwrite_file, format_outputWrite-only. No search or read of external sources.
โš ๏ธ Common Mistake โ€” Giving All Agents All Tools

Giving a synthesis agent access to web_search causes it to attempt its own searches mid-synthesis, breaking the hub-and-spoke architecture and producing inconsistent, non-reproducible results. Always scope tools to the minimum needed for each agent's role.

โญ Pro Tip โ€” Use allowedTools as Architecture Documentation

Your allowedTools lists serve as living documentation of what each agent is designed to do. When a new team member reads the config, the tool list tells them immediately whether an agent is a reader, writer, searcher, or orchestrator. Treat it like access control policy โ€” not just a runtime setting.

๐Ÿ“‹ AgentDefinition Configuration

AgentDefinition is the blueprint for a subagent type. Think of it like a job description combined with an access badge. It specifies:

๐Ÿ“ description

Short label for this agent type (e.g., "Web Search Specialist"). Used by the coordinator to select the right subagent type when multiple types are available.

๐Ÿง  systemPrompt

The agent's identity, role, and standing instructions. Defines how it behaves, what format it returns, and any standing constraints (e.g., "always cite sources").

๐Ÿ”‘ allowedTools

The list of tools this agent type is permitted to use. Acts as a security boundary โ€” the agent cannot access anything outside this list.

๐Ÿ“ outputSchema (optional)

JSON schema that the agent's output must conform to. Forces structured output and makes downstream aggregation reliable.

Python โ€” AgentDefinition Configuration Example
agent_definitions = {
    "web_search": {
        "description": "Web Search Specialist โ€” finds recent online sources",
        "systemPrompt": """You are a web research specialist.
Your job: search the web for relevant, recent sources on the given topic.
Output format: JSON array of results, each with:
  - title: article title
  - url: source URL
  - key_finding: 1-sentence summary of the key insight
  - date: publication date (ISO 8601)
  - credibility: "high" | "medium" | "low"
Always return at least 5 results. Prefer sources from the last 2 years.""",
        "allowedTools": ["web_search", "read_url"]
    },
    "doc_analyst": {
        "description": "Document Analyst โ€” extracts insights from provided documents",
        "systemPrompt": """You are a document analysis specialist.
Your job: extract structured insights from the documents provided to you.
Output format: JSON with keys: summary, key_claims, data_points, source_citations.
Preserve exact quotes for key claims. Include page/section references.""",
        "allowedTools": ["read_file", "extract_text"]
    }
}

๐Ÿงณ Explicit Context Passing โ€” What & How

Since subagents start with empty context, the coordinator must package everything the subagent needs into the Task prompt. This is the most common source of multi-agent bugs โ€” missing context leads to vague, generic outputs.

The Context Passing Checklist

For each Task call, ensure the subagent's prompt includes:

What to IncludeExampleWhy It Matters
Original user goal"The user wants a comprehensive report on AI in music 2022-2024"Subagent understands relevance filtering criteria
Prior agent findings (if needed)Full JSON output from Web Search agentSynthesis agent can't synthesise what it hasn't seen
Scope boundaries"Focus ONLY on music โ€” not visual arts or film"Prevents scope creep and duplication
Output format spec"Return JSON with keys: findings[], gaps[], sources[]"Coordinator can parse and aggregate consistently
Quality criteria"Cite at least 3 sources per claim. Flag low-confidence findings."Drives quality without step-by-step micromanagement
Constraints"Do not include findings older than 2022."Prevents irrelevant content polluting the synthesis
Python โ€” Good vs Bad Context Passing
## โŒ BAD โ€” Synthesis agent has no idea what to synthesise
bad_prompt = """
Synthesise the research findings about AI.
"""

## โœ… GOOD โ€” Synthesis agent has everything it needs
good_prompt = f"""
ROLE: You are a research synthesis specialist.

ORIGINAL USER GOAL: {user_query}

TOPIC SCOPE: AI's impact on the global music industry, 2022-2024.
Do NOT cover visual arts, film, or other creative sectors.

WEB SEARCH FINDINGS (from Web Search Agent):
{json.dumps(web_search_results, indent=2)}

DOCUMENT ANALYSIS FINDINGS (from Doc Analysis Agent):
{json.dumps(doc_analysis_results, indent=2)}

YOUR TASK: Produce a structured synthesis with:
1. Executive Summary (200 words)
2. Key Trends (with source citations from above findings)
3. Conflicting Data (where sources disagree โ€” annotate both values)
4. Coverage Gaps (topics not addressed by either source set)

QUALITY REQUIREMENTS:
- Every claim must cite at least one source from the provided findings
- Conflicting statistics must both be reported with source attribution
- Do NOT introduce information not present in the provided findings
"""

๐Ÿ—ƒ๏ธ Structured Metadata in Handoffs

When passing findings between agents, always separate content from metadata. Metadata includes: source URLs, document names, page numbers, publication dates, and confidence scores. Without this, downstream agents lose the ability to cite sources or assess credibility.

โŒ Prose-Only Handoff (Loses Attribution)

"A 2023 McKinsey report found that 40% of music producers use AI tools daily. Another study showed a 25% increase in AI-generated tracks."

The synthesis agent cannot tell which claim came from which source, cannot cite either, and cannot cross-reference for conflicts.

โœ… Structured JSON Handoff (Preserves Attribution)

[{"claim": "40% of music producers use AI tools daily", "source": "McKinsey 2023 AI in Creative Industries", "url": "https://โ€ฆ", "page": 12, "confidence": "high"}, {"claim": "25% increase in AI-generated tracks", "source": "IFPI Report 2024", "url": "https://โ€ฆ", "confidence": "medium"}]

โญ Pro Tip โ€” Include Temporal Metadata Always

Always include publication_date or data_collection_date in structured handoffs. Without dates, the synthesis agent may treat a 2019 statistic and a 2024 statistic as equivalent, producing misleading trend analysis. Temporal context turns "AI adoption is growing" into "AI adoption grew from 12% (2019) to 67% (2024)".

โšก Parallel Subagent Spawning

One of the most powerful patterns in the Agent SDK is spawning multiple subagents simultaneously by emitting multiple Task tool calls in a single coordinator response. This is identical to the parallel tool calls pattern in the agentic loop โ€” but for subagents.

Figure 2 โ€” Sequential vs Parallel Subagent Spawning
โŒ Sequential (3 round-trips) Coordinator Agent A runs Agent B runs waits for A first Agent C runs waits for B first Total time = A_time + B_time + C_time โœ… Parallel (1 coordinator call) Coordinator 3 Task calls Agent A Agent B Agent C all run simultaneously Total time = max(A_time, B_time, C_time)
Python โ€” Parallel Task Spawning (single coordinator response)
# The coordinator emits MULTIPLE Task calls in ONE response.
# The SDK runs them concurrently.
# This happens automatically when Claude emits multiple tool_use blocks.

# Example coordinator response content (simplified):
coordinator_response_content = [
    {
        "type": "tool_use", "name": "Task", "id": "task_01",
        "input": {"description": "Web Search Agent", "prompt": search_prompt}
    },
    {
        "type": "tool_use", "name": "Task", "id": "task_02",
        "input": {"description": "Doc Analysis Agent", "prompt": doc_prompt}
    },
    {
        "type": "tool_use", "name": "Task", "id": "task_03",
        "input": {"description": "Fact Checker Agent", "prompt": fact_prompt}
    }
    # SDK runs all three simultaneously, returns all three results
]
โญ Pro Tip โ€” Only Parallelise Independent Tasks

Parallel spawning only works for tasks that don't depend on each other's outputs. If Synthesis needs Web Search results before it can run, those two cannot be parallelised. Map your dependency graph first: independent tasks โ†’ parallel; dependent tasks โ†’ sequential.

๐ŸŒฟ Fork-Based Session Management

fork_session creates an independent branch from a shared analysis baseline. Instead of starting from scratch, you take a session that has already done expensive codebase exploration or research, and branch it into two divergent approaches โ€” without either branch polluting the other.

๐ŸŒฟ Analogy โ€” Git Branching for Agent Sessions

In Git, you fork a branch when you want to try two different approaches from the same commit without affecting each other. fork_session does the same for Claude sessions: both branches share the same "commit" (the analysis done so far), but subsequent actions in Branch A don't appear in Branch B.

Use case: "We've analysed the codebase. Now explore both a microservices refactor approach and a monolith-with-modules approach in parallel, then compare results."

Figure 3 โ€” fork_session: Shared Baseline, Divergent Exploration
SHARED BASELINE Codebase analysis complete Architecture understood fork_session Branch A Explore microservices approach Isolated โ€” doesn't affect B Branch B Explore modular monolith Isolated โ€” doesn't affect A Coordinator compares Branch A vs B results โ†’ picks best approach

Key use cases for fork_session:

๐Ÿ“ฆ Packaging Subagent Workflows as Skills

In complex multi-agent systems, repetitively configuring subagents and context passing can become brittle. A more elegant architectural pattern is to package subagent configurations as Skills. As covered in the AI Fluency materials, a Skill is a bundle of instructions and tools that teaches Claude a specific workflow.

By organizing subagent logic into a structured Skill folder (with a strictly formatted SKILL.md containing a precise YAML Frontmatter description), the coordinator agent can invoke predefined, expert-level subagent workflows simply by mentioning them. The YAML Frontmatter acts as the trigger, allowing the coordinator to dynamically load the skill's instructions into the subagent's isolated context only when strictly necessary.

๐ŸŽฏ Goal-Oriented vs Step-by-Step Coordinator Prompts

The exam tests a subtle but important design principle: coordinator prompts should specify what to achieve, not how to do it step-by-step. Over-specifying steps removes the subagent's adaptability and makes the system brittle when inputs vary.

โŒ Step-by-Step (Rigid)

"Step 1: Search Google for AI music articles. Step 2: Click the first 5 results. Step 3: Extract the headline. Step 4: Summarise each headline in one sentence. Step 5: Return all summaries."

Breaks immediately if any article has a non-standard layout, is paywalled, or if a better source isn't in the first 5 results.

โœ… Goal-Oriented (Adaptable)

"Find the 10 most credible recent sources on AI's impact on music production (2022-2024). For each, extract: the key finding, source URL, publication date, and credibility assessment. Prefer peer-reviewed research and established industry reports over blogs."

The agent adapts its search strategy to the actual web landscape it encounters.

โญ Pro Tip โ€” Specify Quality Criteria, Not Process Steps

Instead of telling a subagent how to do something, tell it what good looks like. Include: minimum number of sources, required fields in output, credibility thresholds, and coverage requirements. This gives Claude the freedom to find the best path while ensuring the output meets your standards.

๐Ÿ“ Summary & Exam Key Points

๐ŸŽฏ Exam Scenario โ€” Developer Productivity Tool & Research System

This task draws from two exam scenarios: (1) "You are building developer productivity tools using the Claude Agent SDK. The agent helps engineers explore unfamiliar codebases, understand legacy systems, generate boilerplate code, and automate repetitive tasks. It uses the built-in tools (Read, Write, Bash, Grep, Glob) and integrates with MCP servers." and (2) the Multi-Agent Research System from Task 1.2.


Expect questions where a multi-agent system misbehaves โ€” subagents produce generic output, the coordinator can't spawn agents, or parallel calls run sequentially. The root cause traces to one of: missing "Task" in allowedTools, inadequate context in Task prompts, step-by-step over-specification, wrong tool scope per agent, or sequential spawning where parallel was possible.

1
The Task tool is the mechanism for spawning subagents. The requirement that allowedTools must include "Task" for a coordinator to invoke subagents is critically tested. Without it, Claude cannot spawn subagents even if instructed to.
2
Subagent context must be explicitly provided in the prompt. Subagents do not automatically inherit parent context or share memory between invocations. Assume zero inheritance โ€” everything goes in the Task prompt.
3
AgentDefinition configuration includes descriptions, system prompts, and tool restrictions for each subagent type. The description is the selection label, systemPrompt defines role and output format, and allowedTools is the security boundary.
4
Always separate content from metadata in handoffs. Use structured formats (JSON or markdown tables) to separate content from metadata (source URLs, document names, page numbers, publication dates, confidence scores). Unstructured prose handoffs cause attribution loss permanently.
5
Parallel spawning = multiple Task calls in one coordinator response. By emitting multiple Task tool calls in a single coordinator response, the SDK runs them concurrently. This is the most efficient pattern for independent tasks. Sequential spawning (one per turn) multiplies latency unnecessarily.
6
Fork-based session management for divergent exploration. fork_session creates independent branches from a shared analysis baseline for exploring divergent approaches. Both branches share the baseline but subsequent actions don't pollute each other.
7
Scope allowedTools tightly per agent role. A synthesis agent must not have web_search access. A report generator must not have database write access. Minimal tool sets enforce separation of concerns, reduce mis-use, and improve tool selection reliability.
8
Coordinator prompts specify research goals and quality criteria, not step-by-step procedural instructions. Goal-oriented prompts enable subagent adaptability โ€” step-by-step instructions break on any variation in the actual input or web landscape.