YouTip LogoYouTip

Claude Code Subagent

Claude Code Subagent |Tutorial

\\n\\n

Source URL

\\n\\n

Claude Code Subagent

\\n\\n

In Claude Code, you can create specialized AI subagents to handle specific types of tasks, achieving better context isolation, stronger constraint control, and higher execution efficiency.

\\n\\n

Subagents run in independent context windows. Each subagent can have its own system prompt, specified model, explicit tool access permissions, independent permission mode, and persistent memory across sessions. When Claude determines your request matches a subagent’s description, it automatically delegates the task to that subagent, which completes it independently and returns the result.

\\n\\n
\\n

Subagents only receive their own system prompt and basic environment information (e.g., working directory); they do not inherit the full Claude Code system prompt, ensuring behavior remains pure and controllable.

\\n
\\n\\n
\\n\\n

Why Use Subagents

\\n\\n

The core value of subagents lies in isolation + specialization, reflected in the following aspects:

\\n\\n
    \\n
  • \\n

    Preserve Main Conversation Context: Offload β€œheavy” tasks like exploration or log analysis to subagents, so the main conversation only receives summary conclusions, avoiding being overwhelmed by massive intermediate outputs. Research shows that running three subagents in parallel to analyze a 50,000-line project takes ~45 seconds, whereas sequential execution takes 3 minutes.

    \\n
  • \\n
  • \\n

    Enforce Constraints: Restrict subagent capabilities via tool allowlists or blocklists (e.g., read-only analysis, prohibit dangerous commands).

    \\n
  • \\n
  • \\n

    Behavior Specialization: Design dedicated AI agents for specific domains (code review, debugging, data analysis), clearly defining their capability boundaries in the system prompt to avoid unnecessary invocations.

    \\n
  • \\n
  • \\n

    Cost Control: Assign simple tasks to Haiku and complex analysis to Sonnet. Use the environment variable CLAUDE_CODE_SUBAGENT_MODEL to uniformly configure the model for all subagents.

    \\n
  • \\n
  • \\n

    Cross-Project Reusability: User-level subagents, once configured, are available across all projects.

    \\n
  • \\n
\\n\\n
\\n\\n

Subagent vs. Multi-agent

\\n\\n

These concepts are often confused. The key differences lie in task granularity and execution scope:

\\n\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
Comparison ItemSubagentMulti-agent
Execution ScopeInitiated within a single Claude Code session, handles subtasks and returns resultsMultiple Claude Code sessions run in parallel or sequentially, typically orchestrated by an orchestrator
ContextIndependent context window, isolated from the main conversationEach session has completely independent context
NestingSubagents cannot create further subagents (use Skills for nesting)Can coordinate multi-level tasks via an orchestrator
Use CasesFocused subtasks, large-output isolation, specialized analysisFull-featured development pipeline (design β†’ implementation β†’ testing β†’ release)
\\n\\n
\\n\\n

Built-in Subagents

\\n\\n

Claude Code includes several built-in subagents, which are typically used automatically without manual configuration.

\\n\\n

1. Explore (Exploration Agent)

\\n\\n

Used for read-only search and analysis of codebases. By default, it uses Haiku (fast, low latency) and only exposes read-only tools (no Edit / Write). Claude automatically invokes Explore when it needs to inspect code without modifying it. Supports different exploration depths: quick, medium, very thorough.

\\n\\n

2. Plan (Planning Agent)

\\n\\n

Collects codebase information in planning mode, helping Claude understand project structure and accumulating context for subsequent plan formulation. Only exposes read-only tools, safely gathering planning-related information without creating nested subagents.

\\n\\n

3. General-purpose (General Agent)

\\n\\n

Used for complex, multi-step tasks. Exposes all tools and inherits the model from the main conversation. Suitable for comprehensive scenarios requiring β€œread + modify + reason” and multi-step code modification tasks.

\\n\\n

4. Other Internal Agents

\\n\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
Agent NameDescription
BashRuns shell commands in an isolated context
statusline-setupConfigures terminal status line display
Claude Code GuideAnswers questions about Claude Code usage
\\n\\n
\\n\\n

Create Your First Subagent

\\n\\n

1. Open the Subagent Management Interface

\\n\\n

In Claude Code, run the following command to open the full subagent management interface:

\\n\\n
/agents\\n
\\n\\n

This interface provides all subagent management capabilities: view all available agents (built-in / user-level / project-level / plugin), create new agents, edit existing agents, and resolve naming conflicts to see which version is actually active.

\\n\\n

2. Choose to Create a User-Level Subagent

\\n\\n

In the interface, select Create new agent:

\\n\\n

Image 1

\\n\\n

Then select Project (.claude/agents/). The agent file will be saved to the current directory’s .claude/agents/ folder. If you select ~/.claude/agents/, it applies to all projects:

\\n\\n

Image 2

\\n\\n

Use Claude’s recommended option:

\\n\\n

Image 3

\\n\\n

3. Describe the Agent’s Responsibilities

\\n\\n

You can directly tell Claude in natural language what this agent should do; Claude will automatically generate the system prompt and initial configuration. For example:

\\n\\n

A code improvement agent that scans project files, suggests improvements in readability, performance, and best practices, and provides concrete improvement examples.

\\n\\n

Image 4

\\n\\n

After generation, press e to manually edit all configuration content.

\\n\\n

4. Configure Tool Permissions and Model

\\n\\n
    \\n
  • Only doing code review β†’ Check only read-only tools (Read, Grep, Glob)
  • \\n
  • Need to modify code β†’ Keep Edit / Write tools
  • \\n
  • Recommended model: Sonnet (balanced analysis capability and execution speed)
  • \\n
\\n\\n

Click Continue then press Enter:

\\n\\n

Image 5

\\n\\n

Accept defaults for the next prompts by pressing Enter.

\\n\\n

5. Select Memory Scope (Optional)

\\n\\n
    \\n
  • Select User: Creates persistent memory in ~/.claude/agent-memory/, accumulating experience across all projects
  • \\n
  • Select None: No learning retained; each task starts from scratch
  • \\n
\\n\\n

Image 6

\\n\\n

6. Use the Newly Created Agent

\\n\\n

Use the code-improver subagent to propose improvements for this project:

\\n\\n

Image 7

\\n\\n

The agent runs in an independent context and returns a summary of results to the main conversation upon completion.

\\n\\n
\\n\\n

Subagent Scope of Effect

\\n\\n

Subagents are essentially Markdown files with YAML frontmatter. Their location determines their scope and priority:

\\n\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
LocationScope of EffectPriority
CLI --agents flagCurrent session onlyHighest
.claude/agents/Current projectHigh
~/.claude/agents/All projects (global)Medium
Plugin agentsPlugin scopeLowest
\\n\\n

When a subagent with the same name exists in multiple locations, the higher-priority version overrides lower-priority ones. You can use the /agents command to see which version is currently active.

\\n\\n

Suggestions for choosing location:

\\n\\n
    \\n
  • Project agents (.claude/agents/) can be committed alongside code, enabling team sharing.
  • \\n
  • User agents (~/.claude/agents/) store personal habits and general-purpose tools, effective across all projects.
  • \\n
  • CLI agents (--agents) are for temporary testing or automation scripts and are not persisted to disk.
  • \\n
\\n\\n
\\n\\n

Configuration File Structure

\\n\\n

Each subagent configuration file consists of two parts: YAML frontmatter (metadata and configuration) and Markdown body (system prompt).

\\n\\n

Example

\\n\\n
---\\nname: code-reviewer # Required: unique identifier, lowercase + hyphens\\n\\ndescription: Reviews code for quality, best practices, and security issues.\\n\\ninvokeWhen: "User asks to review, audit, or check code quality."\\n\\ntools: Read, Grep, Glob # Tool allowlist (only these tools allowed)\\n\\nmodel: sonnet # Specify model: haiku / sonnet / opus / inherit\\n\\npermissionMode: default # Permission mode (see section below)\\n\\nmemory: project # Persistent memory scope (see Memory section)\\n---\\n\\nYou are a senior code reviewer.\\n\\nAnalyze code and provide actionable feedback organized by severity: Critical / Major / Minor.\\n\\nUpdate your agent memory with recurring patterns, conventions, and known issues you discover.\\n
\\n\\n

Full Field Reference

\\n\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
FieldRequiredDescription
nameYesUnique identifier; also used as the explicit invocation name. Format: lowercase + hyphens, e.g., code-reviewer
descriptionYesMost critical field. Claude’s decision to automatically invoke the agent depends entirely on this. Clearly describe usage scenarios.
toolsNoTool allowlist; only listed tools are allowed. MCP tools are excluded.
disallowedToolsNoTool blocklist; inherits all tools from the main conversation except those listed. MCP tools are preserved.
modelNoSpecify model: haiku, sonnet, opus, full model ID, or inherit (default, inherits main conversation’s model)
permissionModeNoPermission behavior control; see Permission Mode section below
memoryNoPersistent memory scope: user / project / local; see Memory section below
backgroundNoSet to true to always run the agent in background mode (non-blocking main conversation)
isolationNoSet to worktree to run in a temporary git worktree, fully isolated from the main repo
skillsNoList of Skills to auto-load when this agent starts
hooksNoLifecycle hooks: SubagentStart / SubagentStop / PreToolUse / PostToolUse
\\n\\n

Difference Between tools and disallowedTools

\\n\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
ConfigurationBehaviorTypical Use Case
Neither setInherits all tools from main conversation, including MCP toolsGeneral-purpose agent, no restrictions needed
Only tools setOnly allowlisted tools can be used; MCP tools excludedRead-only analysis agent, strictly constrained scenarios
Only disallowedTools setInherits all tools, excludes blocklisted tools; MCP tools preservedRetain MCP capabilities but prohibit write operations
Both setApply disallowedTools first, then filter remaining tools via toolsFine-grained tool access control
\\n\\n

Examples

\\n\\n

Example 1: Only Read-Only Operations (Using tools Allowlist)

\\n\\n
---\\nname: safe-researcher\\n\\ndescription: Research agent with read-only access. Use when analyzing code without making changes.\\n\\ntools: Read, Grep, Glob, Bash # Only these four tools allowed; Write and Edit are excluded\\n---\\n
\\n\\n

Example 2: Inherit All Tools Except File Writes (Using disallowedTools Blocklist)

\\n\\n
---\\nname: no-writes\\n\\ndescription: Analysis agent that inherits all tools except file writes.\\n\\ndisallowedTools: Write, Edit # Retains MCP tools; only Write and Edit are excluded\\n---\\n
← Pytorch Torch AngleClaude Code Basic β†’