1349 words Slides

17.9 Subagents in the SDK

Course: Claude Code - Enterprise Development

Section: Claude Agent SDK

Video Length: 3-4 minutes

Presenter: Daniel Treasure


Opening Hook

"Some tasks are too complex for a single agent. What if you could create hierarchies of agents—a parent agent that coordinates, delegating focused tasks to specialized subagents? That's the power of subagents: divide and conquer at scale."


Key Talking Points

What to say:

  • "Subagents are agents that work under a parent agent's coordination."
  • "Use subagents for: parallel work, specialized focus, managing complexity, scaling."
  • "Parent agent maintains overall context; subagents inherit context selectively."
  • "Key constraint: subagents cannot exceed parent's permissions—security boundary."

What to show on screen:

  • Parent agent breaking task into subtasks
  • Multiple subagents working in parallel
  • Subagents reporting results to parent
  • Parent synthesizing results
  • Hierarchy visualization (parent → multiple subagents)

Demo Plan

[00:00 - 00:45] Subagent Architecture 1. Explain: parent agent as coordinator, subagents as specialists 2. Example: analyze large codebase - Parent: coordinates analysis - Subagent 1: security review - Subagent 2: performance review - Subagent 3: style/maintainability 3. Show: delegation flow, result aggregation

[00:45 - 01:45] Creating & Delegating to Subagents 1. Define parent agent 2. Create subagent instances (specialized roles) 3. In parent task, delegate to subagents 4. Show: parallel execution (speed benefit) 5. Show: results returned to parent for synthesis

[01:45 - 02:45] Context Inheritance & Selective Sharing 1. Show: parent has full codebase context 2. Parent gives subagent focused slice: "Review security of auth module only" 3. Subagent works with limited context (faster, focused) 4. Results flow back 5. Demonstrate: subagent can't access info parent didn't share

[02:45 - 03:30] Permission Boundaries 1. Explain: parent has permission level X 2. Subagent cannot exceed level X (security guarantee) 3. Example: parent can read files, subagent can read but not write (even if parent tried to elevate) 4. Emphasize: this prevents privilege escalation


Code Examples & Commands

Python with Subagents:

import asyncio
from claude_code import Agent

async def code_review_hierarchy():
    # Create parent agent (coordinator)
    parent = Agent(
        model="claude-sonnet-4-5-20250929",
        system_prompt="You are a code review coordinator. Assign tasks to specialists and synthesize their findings.",
        tools=["Read", "Grep"]
    )

    # Create subagents (specialists)
    security_reviewer = Agent(
        model="claude-sonnet-4-5-20250929",
        system_prompt="You are a security expert. Review code for vulnerabilities, injection attacks, and unsafe patterns.",
        tools=["Read"]
    )

    performance_reviewer = Agent(
        model="claude-sonnet-4-5-20250929",
        system_prompt="You are a performance expert. Review code for inefficiencies, N+1 queries, and optimization opportunities.",
        tools=["Read"]
    )

    style_reviewer = Agent(
        model="claude-sonnet-4-5-20250929",
        system_prompt="You are a code style expert. Review for readability, maintainability, and best practices.",
        tools=["Read"]
    )

    # Parent task
    parent_task = """
    Review the authentication module in /src/auth/.

    Delegate to:
    1. Security reviewer: check for vulnerabilities
    2. Performance reviewer: check for inefficiencies
    3. Style reviewer: check for maintainability

    Synthesize all findings into a single review report.
    """

    # Parent coordinates
    result = await parent.run(
        parent_task,
        subagents={
            "security": security_reviewer,
            "performance": performance_reviewer,
            "style": style_reviewer
        }
    )

    print(f"Code Review Report:\n{result.output}")

asyncio.run(code_review_hierarchy())

Parallel Subagent Execution:

import asyncio
from claude_code import Agent

async def parallel_data_processing():
    # Parent: orchestrates
    parent = Agent(
        model="claude-sonnet-4-5-20250929",
        system_prompt="You are a data pipeline orchestrator. Assign chunks to processors and combine results."
    )

    # Subagents: process chunks
    processor_agents = [
        Agent(
            model="claude-sonnet-4-5-20250929",
            system_prompt=f"You are processor {i}. Process your assigned data chunk and return structured results."
        )
        for i in range(4)
    ]

    # Parent delegates in parallel
    chunks = [
        "Data chunk 1: [raw data]",
        "Data chunk 2: [raw data]",
        "Data chunk 3: [raw data]",
        "Data chunk 4: [raw data]"
    ]

    # Run subagents in parallel
    tasks = [
        agent.run(f"Process this: {chunk}")
        for agent, chunk in zip(processor_agents, chunks)
    ]

    results = await asyncio.gather(*tasks)

    # Parent synthesizes
    synthesis_task = f"""
    Combine these results from 4 processors:
    {[r.output for r in results]}

    Create a final summary and insights.
    """

    final_result = await parent.run(synthesis_task)
    print(f"Final Result:\n{final_result.output}")

asyncio.run(parallel_data_processing())

Context Selective Sharing:

import asyncio
from claude_code import Agent

async def selective_context():
    # Parent has full codebase context
    parent = Agent(
        model="claude-sonnet-4-5-20250929",
        system_prompt="You are a code reviewer. You have access to the full codebase."
    )

    # Subagent for auth module only (limited context)
    auth_specialist = Agent(
        model="claude-sonnet-4-5-20250929",
        system_prompt="You are an authentication specialist. Focus only on auth-related code.",
        context={
            "scope": "auth",
            "files": ["/src/auth/login.py", "/src/auth/tokens.py", "/src/auth/permissions.py"]
        }
    )

    # Parent task
    task = """
    Review our authentication system.
    Assign to auth specialist with only auth files.
    """

    result = await parent.run(
        task,
        subagents={"auth": auth_specialist}
    )

    print(result.output)

asyncio.run(selective_context())

Permission Boundary Enforcement:

from claude_code import Agent, PermissionMode

# Parent agent with write permissions
parent = Agent(
    model="claude-sonnet-4-5-20250929",
    system_prompt="You are a deployment coordinator.",
    permission_mode=PermissionMode.DELEGATE,
    permission_callback=lambda action, resource, details: action == "read" or action == "write"
)

# Subagent with read-only permissions (inherited from parent)
subagent = Agent(
    model="claude-sonnet-4-5-20250929",
    system_prompt="You are an analyzer. You cannot modify files.",
    permission_mode=PermissionMode.DELEGATE,
    permission_callback=lambda action, resource, details: action == "read"
    # Note: cannot grant more permissions than parent
)

# Parent's permission callback
def parent_permission(action, resource, details):
    if action == "write":
        # Only writes to /var/deployments are allowed
        return resource.startswith("/var/deployments")
    return action == "read"

# Subagent inherits parent's constraint
# Even if subagent tries to write to /var/deployments, parent's callback controls it

TypeScript Subagents:

import Anthropic from "@anthropic-ai/sdk";

interface SubagentConfig {
  name: string;
  role: string;
  systemPrompt: string;
  tools: string[];
}

async function coordinateSubagents(): Promise<void> {
  // Define subagents
  const subagents: SubagentConfig[] = [
    {
      name: "frontend",
      role: "Frontend specialist",
      systemPrompt: "Review frontend code for UX and performance.",
      tools: ["Read", "Grep"],
    },
    {
      name: "backend",
      role: "Backend specialist",
      systemPrompt: "Review backend code for scalability and security.",
      tools: ["Read", "Bash"],
    },
  ];

  console.log("Parent agent coordinating subagents:");
  subagents.forEach((sa) => console.log(`  - ${sa.name}: ${sa.role}`));
}

coordinateSubagents().catch(console.error);

Gotchas & Tips

Gotcha 1: Context Explosion - If parent gives each subagent full codebase, memory usage explodes - Solution: Give each subagent focused context slice - Parent reads full codebase, subagents get relevant excerpts

Gotcha 2: Coordination Overhead - Subagent communication adds latency - Not beneficial for simple tasks (use single agent instead) - Solution: Use subagents for tasks that genuinely need specialization

Gotcha 3: Result Inconsistency - Multiple subagents may reach different conclusions - Parent must synthesize, reconcile conflicts - Solution: Clear instructions to subagents on what success looks like

Gotcha 4: Permission Leakage - Subagent should not exceed parent's permissions - If parent accidentally grants extra permission, subagent inherits it - Solution: Careful permission design, audit logs

Gotcha 5: Deadlocks - If subagent A waits for results from subagent B, and vice versa, deadlock - Solution: Design DAG (directed acyclic graph) of dependencies - Parent ensures no cycles

Tip 1: Task Decomposition - Parent's main job is breaking task into subtasks - Good decomposition = faster, focused subagent work

Tip 2: Result Aggregation - Parent synthesizes results from all subagents - Consider: which subagent findings conflict? How to resolve?

Tip 3: Parallel Execution - Use asyncio.gather or similar for parallel subagent runs - Massive speedup for independent tasks

Tip 4: Fallback Agents - If one subagent fails, have a fallback - Example: security review fails due to API timeout, skip it, continue

Tip 5: Monitoring & Logging - Log all subagent invocations: task, result, duration, errors - Useful for optimization and debugging


Lead-out

"You've built hierarchical agent systems—scalable, specialized, coordinated. Final SDK topic: deployment. How do you run these agents in production? We'll cover cloud infrastructure, configuration, resilience."


Reference URLs

  • Claude Code Subagent API: [check official docs]
  • Async Patterns in Python/TypeScript: [standard docs]
  • Multi-Agent Architectures: [AI research papers]

Prep Reading

  • Design a complex task that could benefit from subagent decomposition (10 min)
  • Review asyncio.gather or Promise.all patterns (5 min)

Notes for Daniel

  • Specialization benefit: Emphasize that smaller, focused agents are more reliable and faster than one large agent.
  • Real example: Use realistic tasks: code review, data processing, deployment coordination. Show where subagents shine.
  • Parallel execution: Visualize with timing: single agent (3 tasks × 30s = 90s) vs. 3 subagents in parallel (30s total).
  • Complexity warning: Mention that subagents add complexity. Use them when needed, not everywhere.