Tutorial10 min read

Subagents, Agent Teams and the Agent SDK

SFEIR Institute

TL;DR

Claude Code offers four ways to put multiple agents to work: subagents defined in .claude/agents, agent teams that coordinate several sessions in parallel around a lead, background agents that run full sessions in the background, and the Agent SDK that lets you build your own agents programmatically. This guide explains when to use each and how to configure them.

Claude Code offers four ways to put multiple agents to work: subagents defined in .claude/agents, agent teams that coordinate several sessions in parallel around a lead, background agents that run full sessions in the background, and the Agent SDK that lets you build your own agents programmatically. This guide explains when to use each and how to configure them.

These four mechanisms answer distinct needs. Subagents preserve your main conversation's context by isolating side tasks. Agent teams add direct communication between agents. Background agents free up your terminal. The Agent SDK steps outside Claude Code to embed the same agent loop in your own applications. To place these tools within the full set of Claude Code extensions, see the custom commands and skills guide.

What is a subagent in Claude Code?

A subagent is a specialized AI assistant that handles a specific type of task. Each subagent runs in its own context window, with its own system prompt, specific tool access, and independent permissions. When Claude encounters a task that matches a subagent's description, it delegates the work, and the subagent returns only its summary to the main conversation.

According to the official documentation, subagents help you:

  • Preserve context by keeping exploration and implementation out of your main conversation
  • Enforce constraints by limiting which tools a subagent can use
  • Reuse configurations across projects with user-level subagents
  • Specialize behavior with focused system prompts for specific domains
  • Control costs by routing tasks to faster, cheaper models like Haiku

Claude Code includes built-in subagents such as Explore, Plan, and general-purpose. Explore is a read-only agent on the Haiku model, optimized for searching codebases. One important constraint: subagents cannot spawn other subagents (no nesting).

Key takeaway: a subagent handles a side task in its own context and returns only its summary. It works within a single session.

Where do subagents live and which frontmatter fields matter?

Subagents are Markdown files with YAML frontmatter. You store them in different locations depending on scope. Project subagents live in .claude/agents/ (checked into version control with your code), and user subagents in ~/.claude/agents/. Claude Code scans both directories recursively, so you can organize them into subfolders such as agents/review/.

Here is a minimal subagent file, exactly as shown in the documentation:

---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Glob, Grep
model: sonnet
---

You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.

The body of the file becomes the subagent's system prompt. Only name and description are required. The main frontmatter fields are:

FieldRole
nameUnique identifier using lowercase letters and hyphens
descriptionTells Claude when to delegate to this subagent
toolsList of allowed tools (inherits all if omitted)
disallowedToolsTools to remove from the inherited list
modelsonnet, opus, haiku, a full model ID, or inherit (default: inherit)
maxTurnsMaximum number of agentic turns before the subagent stops
permissionModedefault, acceptEdits, auto, dontAsk, bypassPermissions, or plan

Other fields exist: skills, mcpServers, hooks, memory, background, effort, isolation, and color. To understand the permission modes mentioned here, see the permissions and security guide. Subagents are loaded at session start: if you edit a file directly on disk, restart your session for it to take effect.

Key takeaway: a subagent is a .md file in .claude/agents/ (project) or ~/.claude/agents/ (user), with frontmatter where only name and description are required.

How do you create and manage subagents with the /agents command?

The /agents command opens a tabbed interface for managing your subagents. Run it inside a session:

/agents

The Running tab shows active subagents and lets you open or stop them. The Library tab lets you view all available subagents (built-in, user, project, and plugin), create new ones with guided setup or Claude generation, edit their configuration and tool access, and delete custom subagents.

To create a subagent, switch to the Library tab, select Create new agent, then choose Personal (saved to ~/.claude/agents/) or a project location. The Generate with Claude option writes the identifier, description, and system prompt for you from a plain natural-language description. Subagents created through the /agents interface are available immediately, with no restart.

You can also define subagents on the fly for a single session with the --agents flag, which accepts JSON using the same fields as the frontmatter:

claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  }
}'

Once the subagent is defined, invoke it simply by naming it in your prompt:

Use the code-reviewer agent to review this project

Key takeaway: /agents is the recommended way to create and manage your subagents. The --agents flag lets you define them on the fly in JSON for a session.

How do agent teams work and what is the lead's role?

Agent teams coordinate multiple Claude Code instances working together. One session acts as the lead: it creates the team, spawns teammates, assigns tasks, and synthesizes results. Unlike subagents, which only report results back to the main agent, teammates in a team communicate directly with each other, and you can interact with any of them individually.

Agent teams are experimental and disabled by default. Enable them by setting the CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS environment variable to 1, either in your shell or through settings.json:

{
  "env": {
    "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
  }
}

Once enabled, simply ask Claude to create a team, describing the task and the structure you want in natural language:

Create an agent team to review PR #142. Spawn three reviewers:
- One focused on security implications
- One checking performance impact
- One validating test coverage
Have them each review and report findings.

An agent team consists of four components: the team lead (the main session that coordinates), the teammates (separate Claude Code instances, each in its own context window), a shared task list (teammates claim and complete tasks), and a mailbox (messaging system between agents). The lead can assign a task explicitly, or a teammate can self-claim the next available, unblocked task.

The documentation recommends starting with 3 to 5 teammates for most workflows, because token costs scale linearly with the number of active agents. You can reuse a subagent definition as a teammate role by mentioning its name to the lead. For advanced multi-agent setups, see the advanced best practices for Claude Code.

Key takeaway: an agent team runs several sessions in parallel around a lead, with direct communication between teammates. The feature is experimental and enabled via CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1.

What are background agents and the claude agents command?

Background agents (agent view) let you drive several full Claude Code sessions from a single screen. Open agent view from your shell:

claude agents

This screen lists all your background sessions: what's running, what needs your input, and what's done. Each background session is a full Claude Code conversation that keeps running without a terminal attached, so you can open it, reply, and leave whenever you want.

The loop is simple. Type a prompt and press Enter: a new session starts on that task and appears as a row. Every prompt starts its own session, which lets you run several in parallel. Select a row and press Space to open the peek panel, which shows the session's most recent output or the question it's waiting on. Press Enter or to attach to the full conversation, and to detach and return to the table.

Sessions are grouped by state: Working, Needs input, Idle, Completed, Failed, and Stopped. A separate supervisor process runs these sessions, which lets them keep going even after you close agent view or your shell. To move an interactive session you already have open into the background, run /bg inside it.

Key takeaway: claude agents opens a single screen to dispatch and monitor several full sessions in parallel, which keep running without a terminal attached.

How do you build your own agents with the Agent SDK?

The Agent SDK gives you the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript. With it, you build agents that read files, run commands, search the web, and edit code, all inside your own application.

Install the SDK for your language:

# TypeScript
npm install @anthropic-ai/claude-agent-sdk

# Python (3.10 or later)
pip install claude-agent-sdk

Then set your API key and run a first agent. Here is the TypeScript example from the official documentation:

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Find and fix the bug in auth.ts",
  options: { allowedTools: ["Read", "Edit", "Bash"] }
})) {
  console.log(message); // Claude reads the file, finds the bug, edits it
}

And the Python equivalent:

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions


async def main():
    async for message in query(
        prompt="Find and fix the bug in auth.py",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),
    ):
        print(message)


asyncio.run(main())

The SDK ships built-in tools (Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch, and more), so your agent starts working immediately without you implementing tool execution. It also supports hooks, subagents (via the agents option and the Agent tool), MCP servers, permission control, and resumable sessions. It loads Claude Code's filesystem configuration too: skills, commands, and CLAUDE.md. To connect external tools, see the MCP (Model Context Protocol) guide, and for CI/CD usage, the headless mode and CI/CD guide.

Key takeaway: the Agent SDK embeds Claude Code's agent loop in your Python or TypeScript applications, with tool execution already handled.

Subagents, agent teams, background agents, or the Agent SDK: which one to choose?

These four approaches complement each other. The table below summarizes the key distinctions from the official documentation:

ApproachWhen to use
SubagentsFocused tasks where only the result matters, within a single session
Agent teamsComplex work where teammates need to discuss, challenge, and coordinate
Background agentsSeveral independent tasks to run in parallel without watching every step
Agent SDKBuilding custom agents programmatically, in CI/CD or production

Subagents and agent teams both parallelize work, but they differ on communication: subagents only report their results back to the main agent and never talk to each other, whereas teammates in a team share a task list and communicate directly. Choose based on whether your workers need to coordinate.

To teach your conventions to all these agents, the CLAUDE.md file remains central: teammates and subagents read it when they start. See the CLAUDE.md memory system guide to structure these instructions.

To master multi-agent orchestration in real conditions, SFEIR's Claude Code course offers a day of hands-on labs. The AI-Augmented Developer course digs deeper into subagents and the Agent SDK within production architectures.

Key takeaway: choose subagents for focused tasks, agent teams for coordination, background agents for unwatched parallelism, and the Agent SDK for custom agents in production.


Recent articles about Claude

Claude Code Training

This topic is covered in Module 5 of our Claude Code training

Sub-agents and Skills

1-day training • 60% hands-on labs • Expert instructors

View full program