Claude Code Subagent |Tutorial
\\n\\n\\n\\nClaude Code Subagent
\\n\\nIn 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\\nSubagents 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\\n\\nSubagents 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
Why Use Subagents
\\n\\nThe 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
\\nCLAUDE_CODE_SUBAGENT_MODELto uniformly configure the model for all subagents. \\n - \\n
Cross-Project Reusability: User-level subagents, once configured, are available across all projects.
\\n \\n
\\n\\n
Subagent vs. Multi-agent
\\n\\nThese concepts are often confused. The key differences lie in task granularity and execution scope:
\\n\\n| Comparison Item | \\nSubagent | \\nMulti-agent | \\n
|---|---|---|
| Execution Scope | \\nInitiated within a single Claude Code session, handles subtasks and returns results | \\nMultiple Claude Code sessions run in parallel or sequentially, typically orchestrated by an orchestrator | \\n
| Context | \\nIndependent context window, isolated from the main conversation | \\nEach session has completely independent context | \\n
| Nesting | \\nSubagents cannot create further subagents (use Skills for nesting) | \\nCan coordinate multi-level tasks via an orchestrator | \\n
| Use Cases | \\nFocused subtasks, large-output isolation, specialized analysis | \\nFull-featured development pipeline (design β implementation β testing β release) | \\n
\\n\\n
Built-in Subagents
\\n\\nClaude Code includes several built-in subagents, which are typically used automatically without manual configuration.
\\n\\n1. Explore (Exploration Agent)
\\n\\nUsed 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.
2. Plan (Planning Agent)
\\n\\nCollects 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\\n3. General-purpose (General Agent)
\\n\\nUsed 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\\n4. Other Internal Agents
\\n\\n| Agent Name | \\nDescription | \\n
|---|---|
| Bash | \\nRuns shell commands in an isolated context | \\n
| statusline-setup | \\nConfigures terminal status line display | \\n
| Claude Code Guide | \\nAnswers questions about Claude Code usage | \\n
\\n\\n
Create Your First Subagent
\\n\\n1. Open the Subagent Management Interface
\\n\\nIn Claude Code, run the following command to open the full subagent management interface:
\\n\\n/agents\\n\\n\\nThis 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\\n2. Choose to Create a User-Level Subagent
\\n\\nIn the interface, select Create new agent:
\\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:

Use Claudeβs recommended option:
\\n\\n
3. Describe the Agentβs Responsibilities
\\n\\nYou 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\\nA code improvement agent that scans project files, suggests improvements in readability, performance, and best practices, and provides concrete improvement examples.
\\n\\n
After generation, press e to manually edit all configuration content.
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/Writetools \\n - Recommended model: Sonnet (balanced analysis capability and execution speed) \\n
Click Continue then press Enter:
\\n\\n
Accept defaults for the next prompts by pressing Enter.
\\n\\n5. 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

6. Use the Newly Created Agent
\\n\\nUse the code-improver subagent to propose improvements for this project:

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\\nSubagents are essentially Markdown files with YAML frontmatter. Their location determines their scope and priority:
\\n\\n| Location | \\nScope of Effect | \\nPriority | \\n
|---|---|---|
CLI --agents flag | \\n Current session only | \\nHighest | \\n
.claude/agents/ | \\n Current project | \\nHigh | \\n
~/.claude/agents/ | \\n All projects (global) | \\nMedium | \\n
| Plugin agents | \\nPlugin scope | \\nLowest | \\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.
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
Configuration File Structure
\\n\\nEach subagent configuration file consists of two parts: YAML frontmatter (metadata and configuration) and Markdown body (system prompt).
\\n\\nExample
\\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\\nFull Field Reference
\\n\\n| Field | \\nRequired | \\nDescription | \\n
|---|---|---|
name | \\n Yes | \\nUnique identifier; also used as the explicit invocation name. Format: lowercase + hyphens, e.g., code-reviewer | \\n
description | \\n Yes | \\nMost critical field. Claudeβs decision to automatically invoke the agent depends entirely on this. Clearly describe usage scenarios. | \\n
tools | \\n No | \\nTool allowlist; only listed tools are allowed. MCP tools are excluded. | \\n
disallowedTools | \\n No | \\nTool blocklist; inherits all tools from the main conversation except those listed. MCP tools are preserved. | \\n
model | \\n No | \\nSpecify model: haiku, sonnet, opus, full model ID, or inherit (default, inherits main conversationβs model) | \\n
permissionMode | \\n No | \\nPermission behavior control; see Permission Mode section below | \\n
memory | \\n No | \\nPersistent memory scope: user / project / local; see Memory section below | \\n
background | \\n No | \\nSet to true to always run the agent in background mode (non-blocking main conversation) | \\n
isolation | \\n No | \\nSet to worktree to run in a temporary git worktree, fully isolated from the main repo | \\n
skills | \\n No | \\nList of Skills to auto-load when this agent starts | \\n
hooks | \\n No | \\nLifecycle hooks: SubagentStart / SubagentStop / PreToolUse / PostToolUse | \\n
Difference Between tools and disallowedTools
\\n\\n| Configuration | \\nBehavior | \\nTypical Use Case | \\n
|---|---|---|
| Neither set | \\nInherits all tools from main conversation, including MCP tools | \\nGeneral-purpose agent, no restrictions needed | \\n
Only tools set | \\n Only allowlisted tools can be used; MCP tools excluded | \\nRead-only analysis agent, strictly constrained scenarios | \\n
Only disallowedTools set | \\n Inherits all tools, excludes blocklisted tools; MCP tools preserved | \\nRetain MCP capabilities but prohibit write operations | \\n
| Both set | \\nApply disallowedTools first, then filter remaining tools via tools | \\n Fine-grained tool access control | \\n
Examples
\\n\\nExample 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\\nExample 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
YouTip