Back to modules
Module 2

Claude Code CLI Agents

Learn how to spawn and control subagents in Claude Code, including subagent types, definitions, and foreground/background execution.

šŸ“– 30 min
SubagentsSubagent TypesDefinitionsForeground/Background

Subagent Types

Claude Code has built-in subagent types, each optimized for different tasks:

1. Explore Agent

Purpose: Research, investigation, discovery

Optimized for:

  • Searching code and files
  • Investigating problems
  • Understanding existing patterns
  • Web research
  • Tools available:

  • Read, Glob, Grep
  • WebSearch, WebFetch
  • Agent (can spawn other subagents)
  • When to use:

  • "Research all authentication patterns in this codebase"
  • "Find where the database connection is configured"
  • "Investigate what causes this performance issue"
  • 2. Plan Agent

    Purpose: Architecture, design, planning

    Optimized for:

  • Creating implementation plans
  • Designing systems
  • Breaking down large tasks
  • Considering trade-offs
  • Tools available:

  • Read, Glob, Grep
  • Agent (spawn other agents for research)
  • When to use:

  • "Create a plan to refactor the auth system"
  • "Design the database schema for user profiles"
  • "Plan how to add caching to improve performance"
  • 3. General-Purpose Agent

    Purpose: Anything not covered above

    Tools available:

  • All available tools
  • Good for: coding, testing, fixing bugs
  • When to use:

  • "Implement the user registration feature"
  • "Fix the failing test in auth.test.ts"
  • "Write a script to migrate the database"
  • ---

    Creating Custom Subagent Definitions

    You can define specialized subagents in .claude/agents/ directory. Each is a .md file with frontmatter.

    File Format

    Create .claude/agents/my-agent.md:

    markdown
    ---

    type: agent

    description: What this agent specializes in

    model: sonnet (or opus, haiku)

    tools:

    - Read

    - Bash

    - Grep

    ---

    System instructions here. Tell the agent:

  • Its role
  • What it should focus on
  • How to approach problems
  • Output format expected
  • Complete Example

    markdown
    ---

    type: agent

    description: Code reviewer specializing in security vulnerabilities

    model: sonnet

    tools:

    - Read

    - Grep

    - WebSearch

    ---

    You are a security code reviewer with deep expertise in:

  • OWASP top 10 vulnerabilities
  • TypeScript/JavaScript security best practices
  • Database security (SQL injection, etc)
  • Authentication and authorization patterns
  • When reviewing code:

  • Check for injection vulnerabilities
  • Identify authentication/authorization issues
  • Look for exposed secrets or credentials
  • Check for proper error handling
  • Verify crypto is used correctly
  • Format your response as:

  • Issue: [name]
  • Severity: Critical/High/Medium/Low
  • Location: [file:line]
  • Fix: [suggested change]
  • How Claude Code Finds Your Agent

  • You mention the agent by name in your prompt
  • Claude Code looks in .claude/agents/
  • Finds {name}.md
  • Reads the definition
  • Spawns the agent with those instructions and tools
  • ---

    Foreground vs Background Execution

    Foreground (Default)

    Main session waits for the subagent to complete before continuing.

    plaintext
    You: "Use the researcher agent to find all API endpoints"

    Timeline:

    [0s] Main starts researcher subagent

    [0s] Main waits... pauses...

    [45s] Researcher completes with findings

    [45s] Main receives results, continues

    When to use:

  • When you need the results immediately
  • When results inform your next steps
  • Task has a clear deliverable
  • Background

    Main session continues without waiting. Subagent runs independently.

    markdown
    ---

    type: agent

    description: Run integration tests

    background: true

    ---

    plaintext
    You: "Spawn a test runner in the background to validate changes"

    Timeline:

    [0s] Main starts test runner (background)

    [0s] Main continues (doesn't wait)

    [2s] You ask more questions, main keeps working

    [35s] Test runner finishes in the background

    [35s] You see "Test runner completed: 45 passed, 0 failed"

    When to use:

  • Long-running tasks (tests, builds)
  • Task result not needed immediately
  • Want to keep working while background task runs
  • ---

    How to Invoke Subagents

    Automatic Invocation

    Claude Code automatically decides to spawn a subagent based on your prompt:

    plaintext
    You: "Research all the JWT implementations in this codebase"

    Claude thinks: "This is a research task → spawn Explore subagent"

    Result: Explore agent runs, returns findings

    Explicit Request

    Tell Claude Code exactly which agent to use:

    plaintext
    You: "Use my code-reviewer agent to audit auth.ts for security issues"

    Claude: "You explicitly requested code-reviewer → spawning it now"

    Result: code-reviewer agent runs and returns security analysis

    Mention in Messages

    Send messages to running subagents:

    plaintext
    You: "@researcher, also check for deprecated API calls"

    Researcher: Gets your message, searches for deprecated calls, reports back

    ---

    Context Isolation & Efficiency

    Why Subagents Save Context

    Imagine an Explore subagent reads 20 files while researching.

    Without subagents:

  • All 20 file contents stay in main session's context
  • Wastes tokens, reduces available context for other work
  • Growing conversation gets expensive
  • With subagents:

  • Explore subagent reads 20 files (uses its context)
  • Explore summarizes findings in 1-2 sentences
  • Main session only sees the summary
  • Main session's context stays lean
  • Real Numbers

    plaintext
    Task: "Research how authentication works and create an implementation plan"

    Option 1: No subagents

    - Read 15 auth files (context bloat)

    - Summarize each one (more context)

    - Design plan

    - Total context used: ~50,000 tokens

    Option 2: Explore subagent + Plan subagent

    - Explore reads 15 files, returns 200-word summary

    - Plan reads summary + your codebase, creates plan

    - Total context used: ~25,000 tokens (50% savings!)

    ---

    Key Gotchas

    Gotcha #1: Subagents don't inherit history

  • Parent's conversation history is NOT passed to subagent
  • Must include all needed context in the prompt
  • "Use the researcher to find where UserService is defined" āœ“
  • "Use the researcher to find the thing we talked about earlier" āœ—
  • Gotcha #2: Limited tool visibility

  • Subagent can't see tools not in its definition
  • If you need a tool, add it to the agent definition
  • Can't add dynamic tools at runtime
  • Gotcha #3: Subagents can't spawn subagents

  • Subagent can't create its own subagents
  • Keeps nesting depth manageable
  • Design your agents at the top level
  • Gotcha #4: Results are summarized

  • You don't see raw tool outputs from subagent
  • Only the final text response
  • Limits debugging if something goes wrong
  • ---

    Best Practices

    Design Agents for Specific Domains

    markdown
    ---

    type: agent

    description: JavaScript/TypeScript test writing specialist

    ---

    Not generic. Be specific. "Test writing specialist" is better than "helper."

    Provide Clear Context in Prompts

    plaintext
    āŒ Wrong: "Use the researcher to find the issue"

    āœ“ Right: "Use the researcher to find where we handle 404 errors in api/handlers.ts"

    Use Foreground for Quick Tasks

    plaintext
    Foreground = 30 seconds to a few minutes

    Background = Long tasks (5+ minutes)

    Combine Agents Strategically

    plaintext
    Good combo:

    - Explore agent researches patterns

    - Plan agent designs solution

    - Implementation agent codes it

    Avoid:

    - 5+ agents for a simple task (overhead)

    - Overlapping responsibilities (confusing)

    ---

    Summary

    ConceptWhat It Is
    -----------
    SubagentSpecialized Claude Code instance for specific task
    TypesExplore (research), Plan (design), General-purpose
    ForegroundMain waits for subagent; use for immediate results
    BackgroundMain continues; use for long-running tasks
    Context isolationSubagent reads files, main only sees summary

    Next module: Meet the Agent SDK — using agents in your own code!