Skip to main content

How to Use Agents and Subagents in Claude Code

Michael 12 min read
How to Use Agents and Subagents in Claude Code

When I first started working with Claude Code, I couldn't imagine myself ever needing to work with agents. There was no way I could conceive in my brain that anything I wanted to do would ever be handed off to some computer code to go process and return a result.

That was, until, I truly understood the flexibility of agents in Claude Code. And today I'm writing this Claude Code tutorial on agents and subagents to help you understand their usefulness.

But let's start at the beginning with the most familiar agent - Claude Code itself. When you start Claude Code, you have initialized the main agent, the main window, the main interface. Whatever you want to call it, it's still the main agent. And this agent has all the tools necessary for you to accomplish your desired tasks. From the ability to pull together C# code for your backend, to scripting HTML, CSS, and Javascript used in your frontend, to creating database tables in your data layer, it can do just about anything you want.

Great. If the main agent can do it all, that about wraps up this post, right? Not entirely. You see, agents in Claude Code are capable of so many other things, so let's talk about what they can do.

Agents vs Subagents

First, let's make a distinction between an agent and a subagent because you'll hear those terms used frequently. A subagent is just an agent that's been called by an agent. (At the time of this writing, subagents can't call subagents). If the Claude Code main window calls an agent, that called agent is now a subagent. But in terms of creating them and configuring them, they're agents. Only when you call them from the main agent do they become subagents.

Context Benefits of Subagents

Secondly, when you're in the main agent and you call an agent (thus, a subagent), it preserves context in the main agent because the subagent spawns a separate session from your main agent, preventing you from filling the context of the main agent so quickly and having to go through another compression or lose context. Also, the subagent sends back a summary of its work to the main agent, saving you tokens.

Subagents Do Not Share Information Horizontally

Subagents are prevented from sharing information with each other. They can only report back to the calling agent. This means subagents are best for independent tasks that do not rely on other concurrently-running subtasks.

Shared Codebase

Multiple subagents can work in the same codebase as your agent. However, you do run the risk of conflicts because the subagents could modify the same parts of your code. This can be mostly remediated by the use of the Git Worktree, but that's a topic for another time.

If you don't want to set up a Git Worktree, but you still want your agents to modify code in the same codebase, Claude Code does have somewhat of a solution for you: subagents can be configured to only be able to work on specific parts of your codebase.

Now when I said it's somewhat of a solution, it's not guaranteed. Your ability to configure agents to only work on a portion of the codebase is based on a prompt, not a technical boundary. In other words, you will prompt Claude Code in the subagent's configuration to only work in the /backend folder or only in the database. But just like any other prompt, Claude Code has some level of autonomy and may do what it wants to do irrespective of your desires. If this is a significant concern for you, keep reading.

Subagent Permissions

Subagents, by default, inherit the permissions of the agent that called them. Those permissions can only get more restrictive, not less. That means if your main agent only has read permission in the project folder, the subagent, by default, only has read access to the project folder as well. The only allowable change to the subagent's permission, in this example anyway, would be to remove access altogether. You would not able to, for example, add write permission to the subagent when it also isn't a permission of the calling agent.

But when it comes to working on parts of a project, you can set a technical boundary for the agent so that it only has the rights you've granted it. And since it's a technical boundary and not a prompt, Claude Code has to obey. "Where you work" is is a prompt. "What you can do there" is a technical boundary. If you remove the ability to edit, Claude Code literally cannot edit files. If you remove the Bash ability, Claude Code literally cannot execute commands. But if you tell it to only work in specific folders, Claude Code may or may not obey.

Subagent Models

When configuring a subagent, you can specify which model to use, and it can use a model that's different from the calling agent, which makes perfect sense. What if your subagent is working on a document that would benefit from reasoning skills instead of coding skills? What if you wanted your subagent to employ a model that uses fewer credits? The model can be set in the agent configuration, which has the features your subagent needs to best accomplish its task.

Creating an Agent

There are a couple of different ways to create a Claude Code agent. The first is to use the /agents skill inside Claude code. The second is to create it from scratch in a markdown file. For this post, we'll be using the guided /agents skill. To begin open a Claude Code session and type /agents at the prompt. You are given an option to create a new agent:

│ ❯ Create new agent                                                                         
│                                                                                            
│ No agents found. Create specialized subagents that Claude can delegate to.                 
│ Each subagent has its own context window, custom system prompt, and specific tools.        
│ Try creating: Code Reviewer, Code Simplifier, Security Reviewer, Tech Lead, or UX          
│ Reviewer.                                                                                  
│                                                                                            
│                                                                                            
│   Built-in (always available):                                                             
│   claude-code-guide · haiku                                                                
│   Explore · haiku                                                                          
│   general-purpose · inherit                                                                
│   Plan · inherit                                                                           
│   statusline-setup · sonnet   

Once you've decided to create a new agent, you'll need to pick the scope of the agent, either project (this would apply to everyone working on the project) or personal (available in all your projects). Remember the path of the option you choose so you can find the agent markdown file later.

╭───────────────────────────
│ Create new agent                                                  
│ Choose location                                                     
│                                                                                     
│ ❯ 1. Project (.claude/agents/)                            
│   2. Personal (~/.claude/agents/)                      
╰───────────────────────────

Next, you can either generate the agent with Claude Code or configure it manually. Let's let Claude Code generate it for us, then we'll go look at the finished configuration when complete:

╭──────────────────────────────
│ Create new agent                                                         
│ Creation method                                                          
│                                                                                            
│ ❯ 1. Generate with Claude (recommended)        
│   2. Manual configuration                                          
╰─────────────────────────────

Now, enter the prompt you want to use to generate the agent:

╭─────────────────────────────────────────────────────────
│ Create new agent                                                                           
│ Describe what this agent should do and when it should be used (be comprehensive for best   
│ results)                                                                              
│                                                                                            
│ This agent should only work on code in the project's /backend folder                                             
╰──────────────────────────────────────────────────────────

Now the /agent skill asks you which types of tools you'd like for the agent to possess. I want read-only access, so I chose the Read-only tools, which will give us five read only tools (Glob, Grep, Read, WebFetch, WebSearch):

╭───────────────────────────
│ Create new agent                                                 
│ Select tools                                                             
│                                                                                     
│   [ Continue ]                                                            
│ ───────────────────────────
│   ☐ All tools                                                             
│ ❯ ☒ Read-only tools                                             
│   ☐ Edit tools                                                          
│   ☐ Execution tools                                               
│   ☐ Other tools                                                       
│ ───────────────────────────
│   [ Show advanced options ]                               
│                                                                                     
│ 5 of 16 tools selected                                          
╰───────────────────────────

Next, you can select your model:

╭────────────────────────────────────────────
│ Create new agent                                                                       
│ Select model                                                                               
│ Model determines the agent's reasoning capabilities and speed.              
│                                                                                            
│ ❯ 1. Sonnet ✔             Balanced performance - best for most agents            
│   2. Opus                 Most capable for complex reasoning tasks                         
│   3. Haiku                Fast and efficient for simple tasks                              
│   4. Inherit from parent  Use the same model as the main conversation    
╰────────────────────────────────────────────

You can then choose the background color of your agent:

╭──────────────────────
│ Create new agent                                  
│ Choose background color                   
│                                                                      
│ ❯ Automatic color                                  
│     Red                                                         
│     Blue                                                        
│     Green                                                     
│     Yellow                                                    
│     Purple                                                    
│     Orange                                                  
│     Pink                                                        
│     Cyan                                                       
│                                                                      
│                                                                      
│ Preview:  @backend-code-reader     
╰──────────────────────

Next pick the scope of the agent's memory. The recommended option is project memory and can be shared to everyone on the project. The second option doesn't enable any type of memory persistence. The third option, User scope, applies the agent's learned items across all projects. And the last option, Local scope, is project-specific but something not committed to source control, so it would not be shared with other team members.

╭───────────────────────────────────
│ Create new agent                                                                          
│ Configure agent memory                                                            
│                                                                                            
│ ❯ 1. Enable (.claude/agent-memory/) (Recommended)     
│   2. None (no persistent memory)                                             
│   3. User scope (~/.claude/agent-memory/)                            
│   4. Local scope (.claude/agent-memory-local/)                    
╰───────────────────────────────────

Now you're presented with a preview of the contents of the agent's configuration file and given the option to save, edit, or cancel:

╭──────────────────────────────────────────────────────────
│ Create new agent                                                                           
│ Confirm and save                                                                           
│                                                                                            
│ Name: backend-code-reader                                                                  
│ Location: .claude/agents/backend-code-reader.md                                            
│ Tools: Glob, Grep, Read, WebFetch, and WebSearch                                           
│ Model: Sonnet                                                                              
│ Memory: Project (.claude/agent-memory/)                                                    
│                                                                                            
│ Description (tells Claude when to use this agent):                                         
│                                                                                            
│   Use this agent when you need to analyze, understand, inspect, or answer questions about  
│   code within the project's /backend folder without making any modifications. This         
│   includes understanding backend architecture, tracing code paths, inves…                  
│                                                                                            
│ System prompt:                                                                             
│                                                                                            
│   You are an expert backend code analyst with deep knowledge of server-side architectures, 
│    APIs, databases, and backend design patterns. You have extensive experience reading and 
│    understanding complex codebases across multiple languages and …                         
│
│                                                                                            
│ Press s or Enter to save, e to save and edit                                               
╰──────────────────────────────────────────────────────────

And now you'll see that you agent has been created:

╭────────────────────────
│ Agents                                                             
│ 6 agents                                                          
│                                                                            
│ Created agent: backend-code-reader 
│ ...
╰────────────────────────

Now go open the backend-code-reader.md file under yourprojectfolder/.claude/agents/. Here is the YAML frontmatter for the agent we just created:

---
name: backend-code-reader
description: "Use this agent when you need to analyze, understand, inspect, or answer questions about code within the project's /backend folder without making any modifications. This includes understanding backend architecture, tracing code paths, investigating bugs, explaining functionality, or gathering information needed for decision-making.\\n\\nExamples:\\n\\n- User: \"Can you explain how the authentication middleware works?\"\\n  Assistant: \"Let me use the backend-code-reader agent to analyze the authentication middleware in the /backend folder.\"\\n  (Since the user is asking about backend code understanding, use the Task tool to launch the backend-code-reader agent to inspect and explain the relevant code.)\\n\\n- User: \"What database models are defined in the backend?\"\\n  Assistant: \"I'll use the backend-code-reader agent to scan the /backend folder for database model definitions.\"\\n  (Since the user wants to understand backend data models, use the Task tool to launch the backend-code-reader agent to read and catalog the model files.)\\n\\n- User: \"I'm getting an error in the user registration endpoint. Can you trace through the code to help me understand what might be going wrong?\"\\n  Assistant: \"Let me use the backend-code-reader agent to trace through the registration endpoint code in /backend and identify potential issues.\"\\n  (Since the user needs code analysis for debugging, use the Task tool to launch the backend-code-reader agent to read and analyze the relevant code paths.)\\n\\n- User: \"What API endpoints are available and what do they do?\"\\n  Assistant: \"I'll use the backend-code-reader agent to examine the route definitions in the /backend folder.\"\\n  (Since the user is asking about backend API structure, use the Task tool to launch the backend-code-reader agent to read route/controller files.)"
tools: Glob, Grep, Read, WebFetch, WebSearch
model: sonnet
memory: project
---

As you can see, since we didn't explicitly name the agent when giving its purpose, Claude Code gave it a name of backend-code reader. Also, since we didn't give the agent much of a purpose in our prompt when creating it, Claude Code created a description for us. We did, however, choose the Read-Only tools, so the agent was given five read-only tools: Glob, Grep, Read, WebFetch, and WebSearch.

We chose Sonnet as the model, so that option appears correctly in the markdown file and we did choose the Project memory option, which also appears in the frontmatter.

And as you scroll further in the file, you can see the markdown portion:

You are an expert backend code analyst with deep knowledge of server-side architectures, APIs, databases, and backend design patterns. You have extensive experience reading and understanding complex codebases across multiple languages and frameworks.

**CRITICAL CONSTRAINTS — You must follow these at all times:**

1. **READ-ONLY**: You must NEVER create, modify, write, delete, or rename any files. You must not use any tool or command that would alter the filesystem in any way. Do not use write-oriented tools, do not run scripts that modify files, and do not suggest or execute any destructive commands. Your only permitted operations are reading files, listing directories, searching/grepping code, and analyzing what you find.

2. **SCOPE RESTRICTION — /backend ONLY**: You must ONLY read and analyze files within the project's `/backend` folder (and its subdirectories). Do NOT read, reference, or analyze code from any other directory such as `/frontend`, `/web`, `/mobile`, `/shared`, `/infra`, or the project root (unless a file in the project root is clearly a backend configuration file like a backend-specific docker-compose or backend package.json). If asked about code outside `/backend`, politely explain that your scope is limited to the `/backend` folder.

**Your Responsibilities:**

- Read and analyze backend source code to answer questions about functionality, architecture, and implementation details
- Trace code paths through controllers, services, middleware, models, and utilities
- Identify patterns, dependencies, and relationships between backend components
- Explain how specific features, endpoints, or processes work by reading the actual code
- Catalog and summarize structures such as API routes, database models, middleware chains, and configuration
- Identify potential bugs, anti-patterns, or areas of concern through static analysis
- Provide clear, well-structured explanations with references to specific files and line numbers

**Methodology:**

1. Start by understanding the project structure within `/backend` — list directories to get an overview
2. Identify key entry points (e.g., main server file, route definitions, configuration files)
3. Follow the code path relevant to the user's question, reading files systematically
4. When analyzing, reference specific file paths and line numbers so the user can follow along
5. Summarize findings clearly, distinguishing between what the code definitively does vs. your inferences

**Quality Standards:**

- Always cite the specific file and line when making claims about the code
- If you're uncertain about something, say so explicitly rather than guessing
- If the codebase is too large to fully analyze for a question, explain what you did review and what remains unexamined
- Provide structured output (bullet points, numbered lists, code references) for complex analyses
- If a question requires modifying code, explain what changes would be needed conceptually but do NOT make any changes yourself

**Self-Verification:**

Before responding to any request, verify:
- Am I only reading files? (Never writing/modifying)
- Are all files I'm accessing within /backend? (Never outside)
- Am I citing specific files and lines for my claims?
- Have I clearly distinguished facts from inferences?

**Update your agent memory** as you discover backend code patterns, architectural decisions, key file locations, API endpoint mappings, database schemas, middleware chains, and configuration conventions. This builds up institutional knowledge across conversations. Write concise notes about what you found and where.

Examples of what to record:
- Key file locations (e.g., "Routes defined in /backend/src/routes/, controllers in /backend/src/controllers/")
- Architectural patterns (e.g., "Uses repository pattern for data access", "Middleware chain: auth -> validate -> controller")
- Database models and their relationships
- Configuration patterns and environment variable usage
- Naming conventions and code organization patterns observed in the backend

# Persistent Agent Memory

You have a persistent Persistent Agent Memory directory at `/home/claude/projects/full-stack-project/.claude/agent-memory/backend-code-reader/`. Its contents persist across conversations.

As you work, consult your memory files to build on previous experience. When you encounter a mistake that seems like it could be common, check your Persistent Agent Memory for relevant notes — and if nothing is written yet, record what you learned.

Notice in the critical constraints portion of the markdown how permissions (read-only) and scope (/backend) are prompts, not technical limitations.

Now that you better understand agents, you can see their potential: from having multiple agents run in parallel on a project, to having different agents be experts at different technologies in your stack, to context savings, and, of course, to time savings, there are many real-world use cases.

Preparing for the CCA exam? Start with our overview: What Is Anthropic's Claude Certified Architect Exam?

Exam Prep

Preparing for the Claude Certified Architect Foundations exam? See what's covered and browse the full tutorial library mapped to all five exam domains.

Related Posts

The Best Way to Get Claude Code to Find and Fix Its Own Bugs

How to Use the Claude Message Batches API (And When Not To)

How to Integrate Claude Code into CI/CD Pipelines

← Back to all posts