Back to modules
Module 6

Subagents in the SDK

Create specialized agents in the SDK, control their tools, leverage context isolation, and design multi-agent systems.

šŸ“– 30 min
Agent DefinitionsTool RestrictionsContext IsolationSpecialization

Tool Restrictions Per Agent

Different agents can have different tools. This enforces specialization.

Example: Security Reviewer Agent

python
securityreviewer = AgentDefinition(

name="security-reviewer",

description="Audits code for security vulnerabilities",

systemprompt="""Review for:

  • SQL injection, XSS vulnerabilities
  • Insecure cryptography
  • Exposed secrets
  • Authentication bypass risks""",
  • tools=["Read", "Grep", "WebSearch"], # No Bash, no Edit

    model="claude-3-5-sonnet"

    )

    This agent can't run arbitrary commands (Bash) or edit files — only review.

    Example: Implementer Agent

    python
    implementer = AgentDefinition(

    name="implementer",

    description="Codes new features",

    systemprompt="""When implementing:

  • Read existing patterns
  • Follow the code style
  • Write tests
  • Verify with tests before reporting done""",
  • tools=["Read", "Edit", "Write", "Bash", "Grep"], # Has Bash + Edit

    model="claude-3-5-sonnet"

    )

    This agent can code and test, but not browse the web (focused on local work).

    ---

    Context Isolation Benefits

    Each agent has its own context window. This saves tokens and keeps the main agent lean.

    Without Agents

    plaintext
    Main agent researches (reads 15 files)

    → All 15 files in main agent's context

    → Context is now full

    → Can't do much else

    → Total tokens: ~50K

    With Subagents

    plaintext
    Main agent spawns researcher (reads 15 files)

    → Researcher's context: ~20K tokens used

    → Researcher summarizes: "Found X pattern in 3 files, Y pattern in 5 files"

    → Main agent gets 100-word summary

    → Main context: still lean

    → Total tokens: ~25K (50% savings)

    Real Workflow

    python
    async for message in query(

    prompt="Research auth patterns and design a refactor plan",

    options={

    "agents": {

    "researcher": researcheragent,

    "planner": planneragent

    }

    }

    ):

    # Claude automatically decides when to use each agent

    # Researcher explores (keeps findings brief)

    # Planner designs based on summary (context stays lean)

    if isinstance(message, ResultMessage):

    print(message.result)

    ---

    Specialization Patterns

    The Team Pattern

    Create agents for different roles, work together:

    python
    agents = {

    "explorer": AgentDefinition(

    description="Searches and discovers patterns",

    tools=["Glob", "Grep", "Read", "WebSearch"]

    ),

    "designer": AgentDefinition(

    description="Plans architecture and solutions",

    tools=["Read", "Grep"],

    systemprompt="Design solutions that are scalable, maintainable, and follow existing patterns"

    ),

    "builder": AgentDefinition(

    description="Implements code and features",

    tools=["Read", "Write", "Edit", "Bash"]

    ),

    "validator": AgentDefinition(

    description="Tests and validates work",

    tools=["Bash", "Grep", "Read"]

    )

    }

    Use by delegating:

    python
    options = ClaudeAgentOptions(agents=agents)

    async for message in query(

    prompt="Implement user authentication: research best practices, design it, code it, validate tests pass",

    options=options

    ):

    # Claude automatically delegates to appropriate agents

    pass

    The Focus Pattern

    Create agents with very narrow focus:

    python
    findtodos = AgentDefinition(

    description="Find all TODO comments in code",

    tools=["Grep", "Read"]

    )

    runtests = AgentDefinition(

    description="Run test suites and report status",

    tools=["Bash"]

    )

    checktypes = AgentDefinition(

    description="Run TypeScript type checker",

    tools=["Bash"]

    )

    Each agent does one thing well.

    ---

    When to Use Subagents

    Use Subagents When:

  • Tasks are independent
  • - Researching code + writing tests

    - Can happen in parallel

  • Specialization helps
  • - Security reviewer knows vulnerabilities

    - Test writer knows test patterns

  • Context isolation saves tokens
  • - Long research tasks

    - Multiple file reads

  • Different tools needed
  • - Explorer (read-only)

    - Builder (read + write + execute)

    Don't Use Subagents When:

  • Simple one-step task
  • - Just "Read a file"

    - Subagent overhead > benefit

  • Tasks are sequential
  • - Task 2 depends on results of Task 1

    - Parallelization doesn't help

  • Results are large
  • - Subagent's summary still large

    - Limited token savings

    ---

    Designing Effective Agents

    Principle 1: Single Responsibility

    python

    āŒ Bad: Vague responsibility

    broadagent = AgentDefinition(

    description="General helper"

    )

    āœ“ Good: Specific responsibility

    securityauditor = AgentDefinition(

    description="Audits TypeScript code for security vulnerabilities"

    )

    Be specific. "Security auditor" is better than "helper."

    Principle 2: Clear System Prompt

    python
    systemprompt="""You are a database schema reviewer.

    FOCUS ON:

  • Proper indexing for query performance
  • Referential integrity and constraints
  • Normalization (avoid redundancy)
  • Scalability for 1M+ records
  • IGNORE:

  • Application code
  • Frontend concerns
  • DevOps infrastructure
  • OUTPUT FORMAT:

  • Issue: [what's wrong]
  • Impact: [why it matters]
  • Fix: [what to change]
  • """

    Clear instructions = better results.

    Principle 3: Right Tool Set

    python

    āŒ Too many tools (confusing)

    tools=["Read", "Write", "Edit", "Bash", "Grep", "WebSearch", ...]

    āœ“ Focused toolset

    tools=["Read", "Grep"] # Code review agent doesn't need to write

    Give agents only the tools they need.

    ---

    Key Gotchas

    Gotcha #1: Agents can't delegate to agents

  • A subagent can't spawn its own subagents
  • Only main agent can create subagents
  • Keeps nesting depth manageable
  • Gotcha #2: Context doesn't transfer

  • Subagent doesn't see main agent's context
  • Pass all needed info in the prompt
  • Summary it sends back is all main agent knows
  • Gotcha #3: Tools visible in schema

  • If agent definition lists tools, they're in Claude's context
  • You don't control whether Claude uses them
  • Define only tools the agent should consider
  • Gotcha #4: Cost scales with agent count

  • 1 agent = 1 context window
  • 5 agents = ~5x the cost
  • Use agents strategically, not for everything
  • ---

    Next Steps

    You've mastered creating specialized agents. Next module: Multi-Agent Orchestration — how agents work together at scale!