Claude Code Subagents Tutorial: 8 Working Examples (2026)

In This Article

  1. What subagents are
  2. Why parallel matters
  3. How to call the Agent tool
  4. Three core patterns
  5. Example 1: Research agent
  6. Example 2: Doc-writer agent
  7. Example 3: Code-reviewer agent
  8. Example 4: Test-writer agent
  9. Example 5: Refactor agent
  10. Example 6: SEO agent
  11. Example 7: Deploy agent
  12. Example 8: Red-team agent
  13. Anti-patterns to avoid
  14. FAQ

If you have used Claude Code for a few weeks you have probably hit the moment where one agent is not enough. You are halfway through a feature, you also need to research a competitor, you also need to write the docs, and you also need to make sure the new code does not break the existing tests. The single-agent loop is a bottleneck. The fix Anthropic shipped this year is subagents: the ability for the agent you are talking to in Claude Code to dispatch additional specialized agents in parallel and coordinate the results.

This tutorial walks through what subagents are in 2026, the three patterns that cover most real use cases, and eight working code examples you can drop into your own workflow today. It assumes you have Claude Code installed and have used it at least once.

What subagents are

A subagent is an additional Claude conversation, with its own context window and its own tool inventory, that the parent agent dispatches to do focused work. The subagent receives a prompt, executes its task, and returns a structured result to the parent. The parent agent does not see the subagent's intermediate steps. It sees the final answer.

This is a deliberate design choice. By keeping the subagent's reasoning out of the parent's context window, Anthropic lets you fan out work across many subagents without exhausting the parent's context. A research subagent might read 30 web pages and 10 PDFs internally. The parent agent never sees those tokens. It only sees the 500-word brief the subagent returns.

In Claude Code today, you dispatch a subagent by calling the Agent tool with five fields: description, subagent_type, prompt, model, and run_in_background. The parent can dispatch multiple subagents in a single tool-call message and they will run concurrently.

The mental model

Think of the parent agent as a senior engineer who delegates. The subagents are interns with focused assignments. Each intern works alone with the resources you give them, then hands you a clean deliverable. The senior engineer reviews, integrates, and decides what comes next.

Why parallel matters

Three reasons.

One, wall-clock speed. If you need to research five competitors, doing it sequentially takes five times as long as doing it in parallel. With subagents, dispatching all five at once and waiting for the slowest one is the right pattern.

Two, context isolation. A research task might pull 80,000 tokens of source material into context. If you run that in the parent agent, you have just spent most of the parent's context window on one task. Run it in a subagent and the parent stays clean.

Three, specialization. Each subagent can have its own system prompt, its own tools, and its own model. A test-writer subagent is best with a strict prompt that says "write only the test, nothing else." A research subagent benefits from web search tools the parent does not need.

How to call the Agent tool

Inside Claude Code, the parent agent calls the Agent tool with a JSON payload that looks like the example below. The parent does not write this JSON itself in the way you might think. The parent emits a tool-call request and the runtime constructs the call. As an end user, you describe what you want in natural language and the parent figures out the dispatch.

{
  "tool": "Agent",
  "description": "Research the top 5 SaaS competitors in the federal CRM space",
  "subagent_type": "general-purpose",
  "prompt": "Search the web for the top 5 SaaS CRM products that explicitly serve U.S. federal customers. For each, return: company name, founded year, key federal certifications (FedRAMP, IL5, IL6), pricing model, and one-sentence differentiator. Output as a markdown table.",
  "model": "opus",
  "run_in_background": false
}

Five fields, all required in practice:

Multiple subagents can be dispatched in a single message. The parent emits an array of tool-call requests in one assistant turn and they execute in parallel. This is the single most powerful pattern available in Claude Code today.

Three core patterns

Most real subagent workflows are one of three shapes.

Fan-out, fan-in. The parent dispatches N subagents in parallel, waits for all of them, and synthesizes the results. Best for research, multi-file analysis, and parallel review.

Pipeline. The parent dispatches subagent A, takes its output, dispatches subagent B with that output as input, and so on. Best for "research → plan → execute" workflows.

Background watcher. The parent dispatches a long-running subagent in the background, continues with other work, and checks the result later. Best for deploys, long migrations, and integration testing.

Example 1: Research agent

The single most common use case. You are about to write something and you need a fresh research brief.

{
  "tool": "Agent",
  "description": "Federal AI procurement research brief",
  "subagent_type": "general-purpose",
  "prompt": "Research the current state of AI procurement under OMB M-24-10 and OMB M-25-21. Use WebSearch and WebFetch. Read the GSA approved AI tools list. Read at least three recent (2026) news pieces from FedScoop, NextGov, or FCW. Return a markdown brief with: (1) what the memos require, (2) the GSA approved list as of April 2026, (3) FAR/DFARS implications, (4) FedRAMP constraints, (5) a 'do this / do not do this' checklist for an acquisition officer. Cite sources inline as [n] with a numbered references section at the end.",
  "model": "opus",
  "run_in_background": false
}

The parent gets back a self-contained brief with citations. You can then ask the parent to use the brief as the foundation of a new article, a slide deck, or a contracting officer memo.

Example 2: Doc-writer agent

You just shipped a feature. You need a docs page that is consistent with the rest of your docs.

{
  "tool": "Agent",
  "description": "Write user-facing docs for the new auth feature",
  "subagent_type": "general-purpose",
  "prompt": "Read /Users/bo/repo/src/auth/*.ts and /Users/bo/repo/docs/*.md. Match the voice, structure, and formatting of the existing docs. Write a new file /Users/bo/repo/docs/authentication.md that explains: (1) what the new auth system does, (2) how to enable it, (3) configuration options with examples, (4) common errors and fixes, (5) a worked example. Use the same Markdown frontmatter the other docs use. Do not invent features that do not exist in the source code. If something is unclear from the code, leave a TODO comment.",
  "model": "opus",
  "run_in_background": false
}

The "do not invent features" sentence is doing a lot of work. Without it, doc-writer subagents tend to fill gaps with plausible-but-fake config flags. Always pin the subagent to the source code.

Example 3: Code-reviewer agent

You just made a 12-file change. You want a second pair of eyes before opening the PR.

{
  "tool": "Agent",
  "description": "Code review of the pending diff",
  "subagent_type": "general-purpose",
  "prompt": "Run 'git diff main...HEAD --stat' and 'git diff main...HEAD' from /Users/bo/repo. Review every changed file. For each file, report: (1) bugs you can see, (2) security concerns (SQL injection, XSS, auth bypass, secret leakage), (3) performance issues, (4) test coverage gaps, (5) style or naming concerns. Group findings by severity (blocker / major / minor). End with an overall verdict: ship-it / needs-changes / blocker. Be specific. Cite file:line for every finding.",
  "model": "opus",
  "run_in_background": false
}

The structured severity system matters. Without it the subagent will write a vague memo. With it, you get a triage list you can act on in 10 minutes.

Example 4: Test-writer agent

Your new module needs tests. You want a thorough test file, not a four-test placeholder.

{
  "tool": "Agent",
  "description": "Write Jest tests for the new pricing module",
  "subagent_type": "general-purpose",
  "prompt": "Read /Users/bo/repo/src/pricing/*.ts. Write a complete Jest test suite for every exported function. Cover: (1) happy path, (2) every documented edge case, (3) error paths and thrown exceptions, (4) boundary values (empty, one, many, max), (5) any function that touches dates needs at least one timezone test. Use the existing test utilities in /Users/bo/repo/src/__tests__/utils.ts. Write the file to /Users/bo/repo/src/pricing/__tests__/pricing.test.ts. Run 'npm test pricing' and iterate until all tests pass. Do not change the source files.",
  "model": "opus",
  "run_in_background": false
}

Two tricks. First, the explicit list of edge case categories prevents the lazy "happy path only" output. Second, the "iterate until tests pass" instruction makes the subagent self-verify before returning.

Example 5: Refactor agent

You have a 600-line file you want broken into smaller pieces. You want it done right and you want to walk away while it happens.

{
  "tool": "Agent",
  "description": "Refactor billing.ts into smaller modules",
  "subagent_type": "general-purpose",
  "prompt": "Refactor /Users/bo/repo/src/billing.ts (currently 627 lines) into smaller modules. Group related functions. Create one file per logical unit (invoicing, taxes, dunning, refunds, webhooks). Update all imports across the repo. Run 'npm run typecheck' and 'npm test' and iterate until both pass. Do not change behavior. Do not change function signatures of exported functions. When done, return a summary of the new file layout and confirmation that typecheck and tests pass.",
  "model": "opus",
  "run_in_background": true
}

Note run_in_background: true. Refactors take time. Fire it and keep working on something else. Check back in 20 minutes.

Example 6: SEO agent

You wrote a blog post. You want it optimized for search without sacrificing voice.

{
  "tool": "Agent",
  "description": "SEO optimize the new blog post",
  "subagent_type": "general-purpose",
  "prompt": "Read /Users/bo/site/blog/new-post.html. Use WebSearch to identify the top three search queries that match the post's topic. For each query, identify: (1) intent (informational, commercial, transactional), (2) the top 5 ranking pages and their structure. Then suggest changes to the post: (a) revised title (under 60 chars, keyword-bearing), (b) revised meta description (140-155 chars), (c) 2-4 H2 additions or rewrites that target the queries, (d) a list of 5-10 internal links to add and the anchor text for each, (e) 3 schema.org additions. Return a unified-diff-style patch I can apply. Do not rewrite the post's voice. Do not insert keywords unnaturally.",
  "model": "opus",
  "run_in_background": false
}

The "do not rewrite the post's voice" line is the difference between an SEO agent that improves your content and one that strips it of personality.

Example 7: Deploy agent

You want a deploy that runs the full release checklist, deploys, smoke-tests, and reports back.

{
  "tool": "Agent",
  "description": "Deploy main to production with smoke tests",
  "subagent_type": "general-purpose",
  "prompt": "Pre-flight: ensure git status is clean, you are on main, and main is up to date with origin. Run 'npm run build' and 'npm test'. If either fails, abort and report. Then run 'wrangler deploy --env production' from /Users/bo/repo. Wait 30 seconds. Run 'curl -fsS https://api.example.com/health' and 'curl -fsS https://api.example.com/version'. The version response must match the commit SHA you just deployed. If anything fails, run 'wrangler rollback --env production' and report the failure. On success, post a summary including commit SHA, deploy time, and the version response.",
  "model": "opus",
  "run_in_background": false
}

The rollback instruction is critical. Subagents that deploy without a rollback path are the ones that ruin Friday afternoons.

Example 8: Red-team agent

You shipped a feature that takes user input. You want an honest attempt to break it before someone else does.

{
  "tool": "Agent",
  "description": "Red-team the new public file-upload endpoint",
  "subagent_type": "general-purpose",
  "prompt": "Target: POST /api/upload at https://staging.example.com. Read /Users/bo/repo/src/api/upload.ts to understand the endpoint. Then attempt the following attacks and report results: (1) oversized payload, (2) malformed multipart boundary, (3) executable file uploads (.exe, .sh, .php), (4) zip-slip path traversal in archive names, (5) polyglot files (jpg+php), (6) MIME type spoofing, (7) SSRF via filename, (8) prototype pollution via JSON metadata. For each, send the request, capture status code and response, and assess: did the server reject correctly? For any failure, write the exact reproducer and severity. Do not execute attacks against production, only staging.",
  "model": "opus",
  "run_in_background": false
}

The "staging only" pin is mandatory. Red-team subagents must never run against production without explicit authorization in the prompt.

Putting them together: parallel dispatch

The strongest use of subagents is dispatching several at once. Here is the pattern I use to ship a federal proposal section.

// Three subagents dispatched in a single assistant turn:
[
  {
    "tool": "Agent",
    "description": "Read BAA and extract topic-specific requirements",
    "subagent_type": "general-purpose",
    "prompt": "Read /Users/bo/proposals/SF254-D1201/baa.pdf and extract every requirement that applies to topic SF254-D1201. Output a markdown checklist with FAR/DFARS clauses, page limits, font requirements, file format requirements, and submission deadline. Cite page numbers.",
    "model": "opus",
    "run_in_background": false
  },
  {
    "tool": "Agent",
    "description": "Research current SOTA for the topic",
    "subagent_type": "general-purpose",
    "prompt": "Research the state of the art in passive sonar machine learning as of 2026. Use WebSearch. Find published academic papers from 2024-2026 and any DoD-funded prior work. Return a 600-word brief with 8-12 citations, suitable for the 'Related Work' section of a Phase I SBIR proposal.",
    "model": "opus",
    "run_in_background": false
  },
  {
    "tool": "Agent",
    "description": "Draft the SMART objectives section",
    "subagent_type": "general-purpose",
    "prompt": "Read /Users/bo/proposals/SF254-D1201/PLAN.md. Draft section 3 (SMART objectives) for the Phase I technical volume. 5-7 objectives, each Specific-Measurable-Achievable-Relevant-Time-bounded. Tie each to the topic-specific outcomes named in the BAA. Output as a Markdown bulleted list ready for the proposal.",
    "model": "opus",
    "run_in_background": false
  }
]

Three subagents, three deliverables, all running concurrently. The parent agent collects them and integrates. Total wall-clock time is the slowest of the three, not the sum.

Anti-patterns to avoid

Vague prompts. "Help me with this code" is a parent-agent prompt, not a subagent prompt. Subagents need precise inputs, precise outputs, and precise success criteria. The parent sees only the final result, so the subagent has to be self-sufficient.

Subagents calling subagents recursively. Possible. Almost never wise. Two levels deep is enough for any reasonable workflow. Three levels deep means you are spending more on coordination than work.

Forgetting the model field. If you do not pin model: "opus", you may inherit a weaker model on serious work. Always pin Opus 4.7 for production-grade tasks.

No rollback or no validation. Any subagent that touches production must have a rollback or a smoke-test in its prompt. Without one, a confident-but-wrong subagent will deploy a broken build.

Letting the subagent decide success. Give it explicit pass/fail criteria. "Do X. Verify by running Y. If Y fails, do Z, and report." Subagents that decide their own success criteria tend to be optimistic.

Cost discipline

Subagents are not free. Every subagent runs a full Claude conversation with its own context, prompt, and output. A research subagent that reads 30 web pages can easily burn $1-$3 of API spend. Eight subagents in parallel is eight times that.

Two practical rules. First, dispatch subagents only when the task genuinely benefits from isolation or parallelism. Single-shot questions belong in the parent. Second, watch your daily spend with anthropic-cli usage or the dashboard. The day I noticed I was spending $80/day on subagents was the day I tightened my prompts to use cheaper models for routine tasks.

Frequently asked questions

Q: Can subagents see my files?

Yes, if their tool inventory includes Read. The subagent runs in the same working directory as the parent. File access is not magic; it is the same Read/Write/Bash tools the parent uses.

Q: Can subagents talk to each other?

Not directly. They communicate only through the parent agent's coordination. If you need two subagents to share state, write that state to a file the parent can pass between them.

Q: How many subagents can I dispatch in parallel?

In practice, ten or fewer. The runtime supports more, but the parent has to integrate every result, and the cost compounds. Five or six is the sweet spot for most workflows.

Q: Do subagents run on a different model than the parent?

They can. You set the model field per dispatch. Use Opus 4.7 for serious tasks and Sonnet 4.7 or Haiku 4.7 for cheap routine work.

Q: What is the difference between a subagent and a tool?

A tool is a single function call with structured input and output. A subagent is a full Claude conversation that can use many tools and perform multi-step work. Use a tool when one call is enough. Use a subagent when the task needs planning, multiple steps, or its own context window.

Q: Can I save subagent results to a file automatically?

Yes. Just instruct the subagent to write its output to a file path before returning. The parent then receives a confirmation message and can read the file when needed.

Learn Claude Code In Person

Six months. Five U.S. cities. Live instruction on Claude Code, subagents, and production AI workflows. June through October 2026.

See Our Bootcamp

About Bo Peng

Bo Peng is the Founder and CTO of Precision AI Academy and Precision Delivery Federal LLC, a federal technology consultancy serving defense and intelligence agencies. He teaches practical AI to international students and working professionals across five U.S. cities.