Tutorials
Ren Okabe15 min read74 views

Claude Code Subagents: How to Create, Scope, and Nest Them (2026)

The /agents creation wizard was removed in Claude Code v2.1.198, so almost every guide still ranking for this topic teaches a flow that no longer exists. Here is the current way to write, scope, invoke, and cap Claude Code subagents, with a version number on every claim. August 2026.

Updated on August 19, 2026

A code editor open on a laptop screen showing a configuration file, August 2026
A code editor open on a laptop screen showing a configuration file, August 2026
On this page

Quick answer

As of August 2026, you create a Claude Code subagent by writing a markdown file with YAML frontmatter into .claude/agents/ (project) or ~/.claude/agents/ (personal). The /agents command no longer opens a creation wizard: that interactive flow was removed in Claude Code v2.1.198, and running /agents now just prints a reminder to ask Claude or edit the directory yourself. Only two frontmatter fields are required, name and description. Subagents can spawn their own subagents, nested 3 layers deep by default (v2.1.219 and later), with a cap of 20 running at once.

Almost every guide currently ranking for this topic still walks you through the wizard, telling you to run /agents, pick "Create New Agent", and choose a project or user level. That flow is gone. This tutorial is written against the current published behavior, with version numbers attached to every claim so you can tell when it goes stale.

Anthropic logo Everything below refers to Claude Code, the CLI. If you are writing an application with the Python or TypeScript SDK, the subagent surface is different and the section "CLI subagents or SDK subagents?" below tells you which one you actually want.

What changed in 2026: the /agents wizard is gone

This is the single thing most tutorials get wrong, so it is worth stating plainly.

Before v2.1.198, /agents opened an interactive screen where you stepped through creating a subagent, optionally with a "generate with Claude" helper. In v2.1.198 that creation wizard was removed. Per the official Claude Code subagents documentation (retrieved August 19, 2026), running /agents now "prints a reminder to ask Claude or edit .claude/agents/ directly."

So there are two supported ways to create one today:

  1. Ask Claude in the session to write the subagent file for you.
  2. Write the file yourself. That is what the rest of this tutorial does, because you should know the format before you delegate authorship of it.

If a guide tells you to select "Create New Agent" from a menu, it was written before August 2026 and you should treat the rest of its details as suspect too.

Prerequisites

  • Claude Code v2.1.219 or later. Several limits in this tutorial (the nesting default, the concurrency cap) changed across the v2.1.198 to v2.1.219 range, and I call out the version for each.
  • A project directory you are comfortable adding a .claude/ folder to.
  • Check your version with claude --version before you start. If you are below v2.1.219, the depth default in Step 5 will not match what you observe.

Write the subagent file

A subagent is one markdown file. The YAML frontmatter configures it; the markdown body is its system prompt.

Create .claude/agents/test-runner.md in your project:

markdown
---
name: test-runner
description: Runs the test suite and explains failures. Use proactively after any code change that touches src/.
tools: Bash, Read, Grep, Glob
model: sonnet
---

You are a test execution specialist.

When invoked:
1. Find the project's test command (package.json scripts, Makefile, pyproject.toml).
2. Run the full suite once. Do not modify code to make tests pass.
3. For each failure, report the test name, the assertion that failed, and the
   most likely file responsible.

Report only what the test output supports. If the suite did not run at all,
say so and quote the error instead of guessing at failures.

That is a complete, working subagent. Only name and description are required; everything else has a default.

Two details that bite people:

  • name cannot contain a colon. The colon is reserved for plugin scoping (my-plugin:agent-name). Before v2.1.218 such names were accepted and loaded anyway, which is why older files sometimes contain them.
  • description is not documentation, it is routing. Claude decides whether to delegate by matching your task against this string. "Runs tests" gets ignored. "Runs the test suite and explains failures, use proactively after any code change that touches src/" gets picked. Including the phrase "use proactively" is the documented way to encourage automatic delegation.

Claude Code watches .claude/agents/ and ~/.claude/agents/ and picks up the new file within a few seconds. There is one important exception, covered in the troubleshooting section below.

Choose the frontmatter fields that actually matter

Most guides stop at name, description, tools, and model. The current field set is considerably larger, and three of the less-known fields do most of the real work.

Scroll to see more

FieldRequiredWhat it does
nameYesUnique identifier, lowercase and hyphens. Appears as agent_type in hooks.
descriptionYesWhen Claude should delegate here. This is the routing signal.
toolsNoAllowlist. Omit it and the subagent inherits every tool available to subagents. Accepts MCP patterns like mcp__* and Agent(subagent-name) to restrict what it may spawn.
disallowedToolsNoDenylist. Applied before tools is resolved.
modelNosonnet, opus, haiku, fable, a full model ID, or inherit. Defaults to inherit.
permissionModeNodefault, acceptEdits, auto, dontAsk, bypassPermissions, plan, or manual.
maxTurnsNoHard stop on agentic turns. The cheapest guardrail there is.
skillsNoSkills preloaded into context at startup. Full content is injected.
memoryNouser, project, or local. Gives the subagent persistent memory across sessions.
backgroundNotrue keeps it in the background even when Claude asks for a foreground run.
effortNolow through max. Useful for making a cheap subagent genuinely cheap.
isolationNoworktree runs it in its own git worktree, so parallel file edits cannot collide.
hooks, mcpServersNoLifecycle hooks and MCP servers scoped to this subagent only. Ignored for plugin subagents.

The three worth reaching for first:

disallowedTools beats a long tools allowlist. If you want a subagent that can do everything except write files, disallowedTools: Edit, Write, NotebookEdit is one line and stays correct when new tools ship. An allowlist silently goes stale.

maxTurns is your budget guard. A subagent with Bash and no turn limit can grind for a long time on a bad instruction. Set it to something you would be willing to pay for.

isolation: worktree is the fix for parallel edit collisions. If you fan out several subagents that each modify files, run them in worktrees. Without it, two subagents editing the same file will clobber each other.

What the subagent does and does not inherit

This is the number one source of confusion, so here it is explicitly. A non-fork subagent starts with a fresh context containing:

  • Its own system prompt (your markdown body), not the full Claude Code prompt
  • The task delegation message
  • Your CLAUDE.md hierarchy and a git status snapshot (the built-in Explore and Plan agents skip both)
  • Any skills named in skills

It does not receive the parent's conversation history, the output style, auto memory, or the parent's context window size.

The practical consequence: whatever the subagent needs to know must be in the delegation prompt. File paths, the error text, the decision you already made. It cannot see the conversation where you established any of that.

Permissions do not work the way the frontmatter suggests either. If the parent session is running bypassPermissions or acceptEdits, the subagent inherits that and cannot override it. If the parent is in auto mode, the subagent inherits auto mode and its permissionMode frontmatter is ignored outright.

Know which definition wins

You can define the same subagent name in five places. When they collide, Claude Code resolves by priority, highest first:

Scroll to see more

PriorityLocationScope
1Managed settingsOrganization-wide
2--agents CLI flagCurrent session only
3.claude/agents/Current project
4~/.claude/agents/All your projects
5A plugin's agents/ directoryWherever that plugin is enabled

Two consequences worth internalizing:

  • A project file overrides your personal one of the same name. That is usually what you want: the repo's code-reviewer should beat your generic one when you are working in that repo.
  • Duplicate names in the same directory tree resolve by filesystem read order, which is undefined. Do not do it. Across nested project directories, the definition closest to your working directory wins.

Project subagents in .claude/agents/ should be committed to version control. That is the whole point: your team gets the same reviewer. Directories are scanned recursively, so agents/review/security.md works fine and the subfolder does not become part of the name.

Invoke it on purpose

There are four ways to get your subagent to run, in ascending order of how much they guarantee.

1. Let Claude route to it. Describe the task and let the description field do its job. Convenient, not deterministic.

2. Name it in the prompt.

text
Use the test-runner subagent to check whether my change broke anything.

3. @-mention it. This guarantees invocation for that one task:

text
@"test-runner (agent)" run the suite and report failures

You can also type @agent-test-runner directly. Plugin subagents appear scoped, as @agent-my-plugin:test-runner.

4. Make it the session default. For a whole session:

bash
claude --agent test-runner

Or in settings:

json
{
  "agent": "test-runner"
}

If Claude keeps answering directly instead of delegating, the fix is almost always the description field, not the prompt. Rewrite it to name the trigger conditions concretely, and add "use proactively".

Cap depth and concurrency before you let subagents nest

Subagents can spawn subagents. One prompt can therefore become a tree of agents, each making its own API calls. Two limits bound that, and both have moved recently enough that most published advice is wrong.

Nesting depth. The default is 3 layers below your main conversation, as of v2.1.219. Control it with CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH, where 1 turns nesting off entirely and 2 lets your subagents spawn one layer of their own. At the depth limit the Agent tool is simply withheld, so the bottom-layer subagent does the work itself rather than failing.

The history matters because it is the reason the internet disagrees with itself:

Scroll to see more

Version rangeDefault depth
v2.1.172 to v2.1.2165 layers, not configurable
v2.1.217 to v2.1.2181 layer
v2.1.219 and later3 layers, configurable

If you saw the widely shared June 2026 announcement that nesting was "capped at depth=5", that was accurate for the release it described and is no longer the current default.

Concurrency. A maximum of 20 subagents run at once by default, counting every subagent spawned through the Agent tool. Set CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS to change it. At the limit, spawning fails with Concurrent subagent limit reached until the running count drops. This requires v2.1.217 or later. Forks and resumed subagents do not count against it.

A sane starting configuration for a repository where you do not want a swarm:

bash
export CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH=1
export CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS=5

That gives you delegation without recursion, which is what most projects actually want.

Forks: the subagent that keeps your context

There is a second kind of delegation that the guides rarely separate out. A fork inherits the entire parent conversation: same system prompt, same tools, same model, same message history. It runs as a fresh instance, its tool calls stay out of your main transcript, and only its final result comes back.

Spawn one manually at any time:

text
/subtask draft unit tests for the parser

The command is /subtask in v2.1.212 and later; it was /fork from v2.1.161 through v2.1.211.

Choose between them on one question: does the task need the conversation you have already had?

Scroll to see more

ForkRegular subagent
ContextFull parent historyFresh, plus your delegation prompt
System prompt and toolsSame as main sessionFrom the definition
ModelSame as main sessionFrom model field
Prompt cacheShared, so cheaper on first requestSeparate

Forks cannot spawn further forks. They can take isolation: "worktree" for isolated file edits. In interactive sessions fork mode is on by default as of v2.1.232, and off for non-interactive -p runs and the SDK.

CLI subagents or SDK subagents?

Both surfaces are called "subagents" and they are not the same thing. This is worth ten minutes now because it saves an afternoon later.

Python logo Python and TypeScript logo TypeScript applications define subagents programmatically, through the agents option on query(), using AgentDefinition:

python
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

async for message in query(
    prompt="Review the authentication module for security issues",
    options=ClaudeAgentOptions(
        allowed_tools=["Read", "Grep", "Glob", "Agent"],
        agents={
            "code-reviewer": AgentDefinition(
                description="Expert code review specialist.",
                prompt="You are a code review specialist...",
                tools=["Read", "Grep", "Glob"],
                model="sonnet",
            )
        },
    ),
):
    if hasattr(message, "result"):
        print(message.result)
typescript
for await (const message of query({
  prompt: "Review the authentication module for security issues",
  options: {
    allowedTools: ["Read", "Grep", "Glob", "Agent"],
    agents: {
      "code-reviewer": {
        description: "Expert code review specialist.",
        prompt: "You are a code review specialist...",
        tools: ["Read", "Grep", "Glob"],
        model: "sonnet"
      }
    }
  }
})) {
  if ("result" in message) console.log(message.result);
}

Note AgentDefinition requires prompt where the markdown file uses its body, and you must include Agent in allowedTools or every delegation hits a permission prompt.

Pick this way:

  • You want a helper in your own terminal, shared with your team through the repo. Use the CLI file in .claude/agents/. That is this tutorial.
  • You are shipping an application that runs Claude on behalf of users. Use the SDK's agents parameter. Configuration lives in code, versioned with your app, and you can build definitions dynamically at runtime.
  • Both. The SDK also reads filesystem agents, and a programmatic agent overrides a filesystem agent with the same name.

The full programmatic walkthrough, including how to detect that delegation actually happened, is in our Claude Agent SDK subagents tutorial. The official SDK subagents reference has the complete AgentDefinition field table.

When your subagent file does not load

In order of how often each one is the cause:

  1. You created the first file in a brand new agents/ directory. The watcher only covers directories that existed when the session started. Restart Claude Code. This is by far the most common cause and it looks exactly like a broken config.
  2. Invalid YAML frontmatter, or a duplicate name. Check the delimiters and that no other agent already claims the name.
  3. The file lives under a directory added with --add-dir. Those are loaded but not watched, so new or edited files there need a restart.
  4. The session was started with --disable-slash-commands. Those sessions never watch the agent directories.
  5. A programmatic agent has the same name. In SDK contexts, agents passed to query() wins over the file.

To find your subagent's transcript when you need to see what it actually did, look in ~/.claude/projects/{project}/{sessionId}/subagents/agent-{agentId}.jsonl. These persist independently from the main conversation and are cleaned up after cleanupPeriodDays, which defaults to 30.

When a subagent is the wrong tool

Delegation is not free. Each subagent is a separate context that has to be told everything, and its results come back as a summary you did not write.

Skip the subagent when:

  • The task needs the conversation. Use /subtask to fork instead. A regular subagent starts blind and you will spend more tokens re-explaining than you save.
  • The task is one tool call. Reading a file does not need an agent around it.
  • You need the raw output verbatim. The parent receives the subagent's final message and may summarize it in its own response. If you need the exact text, say so explicitly in the delegation prompt.
  • You are coordinating dozens of agents. Turn-by-turn delegation is the wrong shape at that scale. The Workflow tool moves orchestration into a script the runtime executes outside the conversation.

The Hacker News thread on parallelizing with Claude Code subagents puts the tradeoff well: the main agent is context-rich while subagents are context-poor, and the ideal subagent is one that burns a lot of tokens to produce a small answer. Read-heavy research, broad codebase searches, and full test runs fit that shape. Small edits that depend on what you just discussed do not.

Common mistakes

  • Following a wizard-based tutorial. The /agents creation flow was removed in v2.1.198. If the guide starts with "Select Create New Agent", stop reading it.
  • Writing description for humans. It is the routing signal. Vague descriptions produce a subagent that never gets called.
  • Assuming the subagent can see the conversation. It cannot. Put paths, errors, and decisions in the delegation prompt.
  • Trusting the "depth=5" number. Default nesting depth is 3 as of v2.1.219, and it was 1 for two releases before that.
  • Setting permissionMode and expecting it to hold. A parent in bypassPermissions, acceptEdits, or auto mode overrides it.
  • Fanning out file-editing subagents without isolation: worktree. They will overwrite each other.
  • Editing a file in a new agents/ directory and waiting. Restart the session.

FAQ

Does /agents still work in Claude Code?
The command still exists, but as of v2.1.198 it no longer opens a creation wizard. It prints a reminder to ask Claude or edit .claude/agents/ directly. Create subagents by writing markdown files or by asking Claude to write them for you.

Where do Claude Code subagent files go?
.claude/agents/ for project subagents, which should be committed to version control, and ~/.claude/agents/ for personal ones available across all projects. Project definitions take priority over personal ones with the same name.

How many subagents can run at once in Claude Code?
20 by default, counting every subagent spawned through the Agent tool. Change it with CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS. At the limit, spawning returns Concurrent subagent limit reached. Requires v2.1.217 or later.

Can Claude Code subagents spawn their own subagents?
Yes. Nesting defaults to 3 layers below the main conversation as of v2.1.219, configurable with CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH. Set it to 1 to turn nesting off.

What is the difference between a subagent and a fork?
A regular subagent starts with a fresh context and only receives your delegation prompt. A fork inherits the entire parent conversation, including system prompt, tools, model, and message history. Spawn a fork with /subtask.

Are Claude Code subagents the same as Claude Agent SDK subagents?
No. Claude Code subagents are markdown files in .claude/agents/ used from the CLI. Claude Agent SDK subagents are defined programmatically through the agents option and AgentDefinition in Python or TypeScript. The SDK can also read filesystem agents, and programmatic definitions override files with the same name.

Why is Claude not using my subagent?
Nearly always the description field. Rewrite it to state concretely when the subagent should be used and include the phrase "use proactively". If you need a guarantee, @-mention the subagent or launch the session with claude --agent test-runner.

Ren Okabe

Written by

Ren Okabe

Ren builds agent infrastructure and writes copy-paste tutorials for engineers shipping LLM tool-use systems.

Frequently asked questions

Does /agents still work in Claude Code?

The command still exists, but as of v2.1.198 it no longer opens a creation wizard. It prints a reminder to ask Claude or edit .claude/agents/ directly. Create subagents by writing markdown files or by asking Claude to write them for you.

Where do Claude Code subagent files go?

Use .claude/agents/ for project subagents, which should be committed to version control, and ~/.claude/agents/ for personal ones available across all projects. Project definitions take priority over personal ones with the same name.

How many subagents can run at once in Claude Code?

20 by default, counting every subagent spawned through the Agent tool. Change it with the CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS environment variable. At the limit, spawning returns 'Concurrent subagent limit reached'. Requires v2.1.217 or later.

Can Claude Code subagents spawn their own subagents?

Yes. Nesting defaults to 3 layers below the main conversation as of v2.1.219, configurable with CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH. Set it to 1 to turn nesting off.

What is the difference between a Claude Code subagent and a fork?

A regular subagent starts with a fresh context and only receives your delegation prompt. A fork inherits the entire parent conversation, including system prompt, tools, model, and message history. Spawn a fork with /subtask.

Are Claude Code subagents the same as Claude Agent SDK subagents?

No. Claude Code subagents are markdown files in .claude/agents/ used from the CLI. Claude Agent SDK subagents are defined programmatically through the agents option and AgentDefinition in Python or TypeScript. The SDK can also read filesystem agents, and programmatic definitions override files with the same name.

Why is Claude not using my subagent?

Nearly always the description field. Rewrite it to state concretely when the subagent should be used and include the phrase 'use proactively'. If you need a guarantee, @-mention the subagent or launch the session with claude --agent followed by the subagent name.