claudeBenutzer09
8

Subagents

Hand a bounded task to an agent of its own — with its own context window, its own set of tools, and its own brief.

Intermediate 1 hour

A subagent is a second Claude with a brief of its own: its own context window, its own tools, its own system prompt. The gain is in the boundary. A long research run no longer fills the main conversation’s window, several agents can work side by side, and a brief you wrote once can be reused. This module goes through it in order: create, configure, invoke, keep an eye on.

Creating a subagent

A subagent is a markdown file with YAML frontmatter. Four places qualify, and on a name clash the higher one wins: your organization’s managed settings, then the --agents flag for this session only, then .claude/agents/ in the project (which goes into version control), then ~/.claude/agents/ for you personally, and last a plugin’s agents/ directory. Both directories are read recursively, so you can sort definitions into agents/review/ and agents/research/ — names have to be unique across the whole tree, otherwise filesystem read order decides. The built-in subagents are always there and take no part in that ranking. If you prefer clicking: /agents opens a menu for creating and editing them.

The frontmatter says who the agent is; the text below it is the system prompt. Write it like briefing a specialist — what to check, in what order, and in what shape the result should come back:

---
name: security-reviewer
description: Security-focused code reviewer. Use proactively after writing authentication, authorization, or data handling code.
tools: Read, Grep, Glob
---

You are a senior security engineer specializing in application security.

Review priorities:
1. Authentication and authorization flaws
2. Injection vulnerabilities (SQL, XSS, command)
3. Data exposure and sensitive information handling
4. Cryptographic weaknesses
5. Insecure direct object references

For each finding, provide: severity (Critical/High/Medium/Low), location (file:line), description, and a concrete fix with code example.

When invoked: run `git diff HEAD` first to focus on changed code.

The tools field bounds what the agent can touch. A security review needs Read, Grep and Glob and nothing else — with no write access it cannot break anything either. An implementation agent needs the full set. Leave tools out and the agent inherits everything the session has.

What goes in the frontmatter

The frontmatter does more than tools. model picks the model — haiku for short mechanical work, sonnet for the normal case, opus for heavy reasoning, or inherit to take the session’s. effort sets this agent’s reasoning depth and overrides the session’s; the docs list low, medium, high, xhigh and max, and which levels actually exist depends on the model. maxTurns caps the number of turns, permissionMode the prompting. Then there are disallowedTools, skills to preload specific skills, mcpServers for servers only this agent sees, and initialPrompt, which submits the first turn automatically.

With memory, an agent keeps something beyond the session. From the MEMORY.md in its memory directory, the first 200 lines or 25KB go into its system prompt — whichever comes first; beyond that, the instructions ask it to curate the file. The agent writes that file itself as it works:

---
name: researcher
memory: user
description: Long-running research assistant with persistent notes
---
You are a research assistant. Check your MEMORY.md at session start to recall previous findings. Update it with new discoveries.

With isolation: worktree, the agent gets a git worktree and branch of its own and never touches your working tree. At the end it reports the path and branch, you look at it and merge or discard. If it changed nothing, the worktree is removed again by itself; while it runs, the worktree is locked so a concurrent cleanup sweep can’t take it away. It branches from the repository’s default branch (origin/HEAD) — unless worktree.baseRef is set to head in settings, in which case the agent starts from your local state and carries unpushed work along.

With background: true, an agent always runs in the background and releases the main conversation right away. An agent that is already running goes to the back with Ctrl+B.

Two flags widen what a session reaches at all. --add-dir takes further directories along — handy when your code points at a shared library or a sibling package in a monorepo; a .claude/skills/ and a .claude/agents/ inside such a directory are read along with it. To make that permanent, use permissions.additionalDirectories in settings. --mcp-config loads MCP servers from one or more JSON files for this session only, on top of your other sources; --strict-mcp-config hides those other sources:

claude --add-dir ~/projects/shared-types --add-dir ~/projects/design-tokens
claude --mcp-config ./ci-servers.json

Invoking, chaining, watching

There are two ways to invoke an agent. If your task matches the description field, Claude picks it on its own; phrasing like "use proactively" makes that more likely but not certain. When it has to be that one agent, name it: @"agent-name (agent)" bypasses the automatic matching.

Plain language does the job just as well, as long as the name is in there:

Use the security-reviewer agent to audit the new auth module.
Have the test-engineer agent write integration tests for the payment service.
Ask the debugger agent to investigate the memory leak in src/workers/queue.ts.

Agents can be chained: what one produces goes into the next. What is running shows up in claude agents in the terminal — an overview of every session with its state (working, waiting, completed, failed, idle, stopped) and last activity. With --cwd you see only the sessions below one directory, which helps when juggling several repositories, and CLAUDE_CODE_DISABLE_AGENT_VIEW turns the view off. To run a whole session under one agent, use claude --agent; what a coordinator may spawn in turn is governed by an Agent(...) allowlist:

# Only show agent sessions started under ~/work/api
claude agents --cwd ~/work/api

If you want to process that overview — your own status line, a session picker, a boot script — append --json and get the same data as an array. Every entry carries pid, cwd, kind and startedAt, plus sessionId, name and status once set. When status is waiting, waitingFor says what it is waiting on — a permission prompt is a different matter from missing input, and a script can treat the two differently:

# Wake up every session that's blocked on a permission prompt
claude agents --json \
  | jq -r '.[] | select(.status == "waiting" and .waitingFor == "permission prompt") | .sessionId' \
  | xargs -I {} claude respawn {}
First use the code-analyzer agent to find performance bottlenecks, then use the optimizer agent to fix them.

Four agents are already there. general-purpose takes broad, multi-step assignments. Explore reads the codebase fast and read-only, inheriting the main session’s model, capped at Opus on the Claude API — so it never costs more than the model you already chose. Plan researches first and then puts a plan in front of you, and claude-code-guide answers questions about Claude Code itself. One detail is worth remembering: Explore and Plan skip your CLAUDE.md files and the git status to keep research cheap — every other agent loads both.

A forked subagent does not start from nothing; it takes over the main session’s full conversation. That is switched on with CLAUDE_CODE_FORK_SUBAGENT; after that /fork starts such an agent instead of being a mere alias for /branch, and agents start in the background as a rule. It works in interactive sessions just as in non-interactive mode and in the Agent SDK:

CLAUDE_CODE_FORK_SUBAGENT=1 claude

Agent teams go a step further: several Claude instances work side by side on a shared task list and write to each other through a mailbox. It is meant for large efforts where independent parts can run in parallel. The feature is switched on solely through the CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS environment variable — in your shell or in the env field of your settings. A stopped teammate does not need resuming first: SendMessage wakes it with the message. Since v2.1.178 there is no TeamCreate and no TeamDelete — with the switch set, every session already has a team, you spawn teammates straight through the Agent tool’s name parameter, and cleanup happens by itself when the session ends.