DS DevShelfHub Projects · AI tools
Articles / Claude Code Agents and Sub-Agents: The Complete Guide to Built-In and Custom Agents

AI Engineering

Claude Code Agents and Sub-Agents: The Complete Guide

By DevShelfHub

Everything you need to know about Claude Code sub-agents — what they are, the built-in agents (Explore, Plan, General Purpose, Claude Code Guide), how to create a custom code-review agent, scoping, tools, model selection, and best practices.

Claude Code Agents and Sub-Agents: The Complete Guide

Introduction

If you’ve been using Claude Code for more than a week, you’ve probably noticed that the model often spawns mysterious helper instances—tasks labelled Explore, Plan, or General Purpose—that go off, do something, and come back with a tidy summary. Those are sub-agents, and they’re one of the most under-rated features of the Claude Code ecosystem.

This article unpacks what agents and sub-agents are inside Claude Code, why you should care, how to use the built-in ones, and—most importantly—how to build your own custom agent from scratch with its own tools, memory, and system prompt. By the end, you’ll have a clear mental model and a working “code improvement advisor” agent in your own project.

📚 Table of contents

  • What is an agent (and a sub-agent) in Claude Code?
  • Why sub-agents matter: context, parallelism, specialization
  • The built-in agents shipped with Claude Code
  • When NOT to spawn a sub-agent
  • How agents compare to LangChain “create agent”
  • Creating a custom agent: step-by-step
  • Project vs user vs local scope
  • The anatomy of an agent .md file
  • Running and observing your agent
  • Best practices for designing sub-agents
  • Common mistakes & pro tips
  • Frequently asked questions

🤖 What is an agent (and a sub-agent) in Claude Code?

A sub-agent in Claude Code is a separate Claude instance, spawned via the Agent tool, that handles a focused task in its own context window and returns a single summary back to the main conversation. Think of it as delegating to a co-worker: they don’t see your full conversation history, they only get the prompt you hand them, and they hand back a result.

🧱 The three core properties

  • Separate context. The sub-agent has its own memory and token budget. Its noisy intermediate work never pollutes your main window.
  • Tool scoping. You decide which tools (read, edit, execute, MCP, etc.) the sub-agent is allowed to call.
  • Single-shot output. The agent returns one summary message—not a chatty back-and-forth.

In the official terminology, “agent” and “sub-agent” are used interchangeably. Whenever the main Claude session delegates work, that delegated worker is a sub-agent.

🎯 Why sub-agents matter

🧹 Context protection

A search across hundreds of files can dump tens of thousands of tokens. A sub-agent reads it all, thinks, and returns a 200-word summary. Your main context stays clean.

⚡ Parallelism

You can spawn three agents in a single message and let them run concurrently. Independent tasks no longer have to be sequential.

🔧 Specialization

Each agent has a focused tool set, a tailored system prompt, and (optionally) its own model. It becomes the expert for a narrow domain.

👉 The biggest practical win is context. If you’ve ever had Claude Code start forgetting earlier instructions halfway through a long session, you were almost certainly past the point where a sub-agent should have absorbed the noisy work.

🧰 The built-in agents shipped with Claude Code

Claude Code ships with a handful of agents out of the box. You can see them in the agent picker (Shift+Tab in the CLI) and the model selects between them automatically based on your prompt.

  • Explore — a read-only search agent. Use it to locate code, grep for symbols, or answer “where is X defined?” questions across the repo.
  • Plan — a software-architect agent. It takes a fuzzy goal and returns a step-by-step implementation plan, identifies critical files, and flags trade-offs.
  • General Purpose — the all-rounder. When a task spans multiple files or you’re unsure of the right narrow agent, this one has the full toolset.
  • Claude Code Guide — the meta-agent. Ask it “how do I use hooks?” or “what are MCP servers?” and it pulls from the Claude Code docs.
  • Status Line Setup — a one-trick agent that configures your terminal status line.

Plan mode deserves special mention. When you toggle plan mode (Shift+Tab in the CLI), Claude Code runs the Plan agent in the background to assemble a plan before answering. It’s a sub-agent invocation under a different name.

🚫 When NOT to spawn a sub-agent

Sub-agents are not free. Every spawn starts cold—it re-derives context you already have—and burns tokens. Skip them when:

  • You already know the file path—just read it directly.
  • You know the exact symbol or string—just grep for it.
  • The task is a one-line retrieval and spawning is pure overhead.
  • The work needs to stay visible in your main context (e.g. iterating on the same file with the user).

👉 Rule of thumb: if you can describe the task to a competent intern in two sentences and you don’t need to peek at their work, a sub-agent is appropriate. Otherwise, do it inline.

🔗 How agents compare to LangChain “create agent”

If you’ve built agents with LangChain’s create_agent or LangGraph, Claude Code sub-agents will feel familiar. Both share the same core idea: spawn an independent LLM instance with a constrained toolset and a system prompt, hand it a task, get a result back.

🧪 LangChain “create agent”

  • You write code: imports, prompt templates, tool bindings
  • Runs anywhere Python runs
  • Maximum flexibility, more boilerplate
  • Good for production services

⚙️ Claude Code sub-agent

  • You declare YAML/Markdown in .claude/agents/
  • Runs inside the Claude Code session
  • Less code, opinionated defaults
  • Good for developer workflow inside the CLI

Treat Claude Code sub-agents as the productised, developer-friendly version of the same idea. If you already understand the LangChain pattern, you understand this—just expressed as a Markdown file.

🛠️ Creating a custom agent: step-by-step

Let’s walk through building a Code Improvement Advisor—an agent that scans your project and suggests readability, performance, and best-practice improvements without touching the code.

1️⃣ Open the agent library

In Claude Code, type /agents to list existing agents and open the library. You’ll see all built-in agents (Claude Code Guide, General Purpose, Plan, Status Line Setup) and any custom ones already registered.

2️⃣ Choose a scope

Hit Create new agent. Claude Code first asks where to save it:

  • Project — saved under .claude/agents/ in the current repo. Shared via git with your team.
  • User — saved under ~/.claude/agents/. Available in every project you open, but only on your machine.
  • Local — machine-specific, not synced. Useful for experiments.

For a team-shared agent, pick Project. For a personal tool you use everywhere, pick User.

3️⃣ Describe the agent

Pick “Generate with Claude (recommended)” and provide a comprehensive description, for example:

Code improvement agent that scans files and suggests improvements
for readability, performance, and best practices. It should explain
each issue, show the current code, and provide an improved version.

Be specific. The richer the description, the better the system prompt Claude will generate for the agent.

4️⃣ Pick the tools

Claude Code asks which tool families to enable:

  • All tools — widest surface, biggest blast radius.
  • Read-only — Read, Grep, Glob, WebFetch, WebSearch. Ideal for advisors and reviewers.
  • Edit tools — Edit, Write, NotebookEdit. Use only if the agent should change files.
  • Execution tools — Bash and friends. Necessary for running tests, builds, deploys.
  • MCP tools — tools exposed by your MCP servers.

For the Code Improvement Advisor, read-only is exactly right. It should look but not touch.

5️⃣ Pick the model

You can choose Sonnet, Opus, Haiku, or inherit from the parent session. Sonnet is the sweet spot for most analysis work—cheap enough to run liberally, strong enough to produce useful suggestions. Opus is worth the cost when the agent has to do deep reasoning across many files. Haiku shines on simple, narrow scans.

6️⃣ Configure memory and color

Pick a background colour (purely cosmetic—helps you spot the agent in the UI) and the memory scope. Memory scopes mirror the agent scopes: project, user, or local. For a project-shared advisor, project memory is the right call.

7️⃣ Save it

Claude Code generates a (possibly very long) system prompt—often 10,000+ characters of carefully crafted instructions—and writes everything to a Markdown file under .claude/agents/code-improvement-advisor.md. That’s your agent, ready to run.

🧬 The anatomy of an agent .md file

Every Claude Code agent is a Markdown file with YAML front matter. Knowing the structure lets you author agents by hand, version them in git, and review pull requests that change agent behaviour.

---
name: code-improvement-advisor
description: Use this agent when the user asks for code improvement
  suggestions, readability fixes, performance tuning, or best-practice
  feedback across the project.
tools: Read, Grep, Glob, WebFetch, WebSearch
model: sonnet
---

You are a senior code improvement advisor. Your job is to scan the
project, identify issues across readability, performance, and best
practices, and produce a prioritised list of suggestions.

Methodology:
1. Read the entire file before suggesting changes.
2. Group findings by severity (high / medium / low).
3. For each finding, show the current code and an improved version.
4. Do NOT modify files; you are an advisor only.

Project-aware behaviour:
- Respect existing patterns even if they aren't your favourite.
- Prefer minimal diffs over rewrites.
- Cite line numbers using file_path:line.
  • name — the slug Claude Code uses to identify the agent.
  • description — the “when to use this agent” hint shown to the main Claude session.
  • tools — explicit allow-list of tool names.
  • model — the model to run the agent on.
  • System prompt body — everything below the front matter is the agent’s system prompt.

🏃 Running and observing your agent

With the agent saved, run it from Claude Code by mentioning it explicitly:

Use the code-improvement-advisor to review the entire project and
provide prioritised suggestions.

The main session will spawn the sub-agent, which runs in its own context. You’ll see live progress in the UI: tools called, files read, token usage. When the agent finishes, it hands back a single summary organised by severity:

  • High severity — correctness bugs, crashing inputs, security issues.
  • Medium severity — performance hotspots, design smells, dead code.
  • Low severity — readability tweaks, stylistic improvements.

Critically, if you stay in plan mode, the advisor won’t touch anything—it will only output the plan. From there you can either pick a subset and ask the main session to act on them, or write them into a plan.md for later.

👉 Run /context after the agent finishes to see how much of your main context budget you spent. Spoiler: if you delegated correctly, almost none.

✅ Best practices for designing sub-agents

🎯 One job per agent

Resist building “mega agents”. A reviewer should review; a refactorer should refactor. Specialisation makes prompts shorter and behaviour predictable.

🔐 Minimum necessary tools

Grant the smallest tool set that still lets the agent do its job. Read-only is the safest default; opt into Edit/Bash only when needed.

📝 Write a clear “when to use”

The description field doubles as a discovery hint. Make it specific—“when the user asks for X, Y, or Z”—so the main session knows when to delegate.

📐 Demand structured output

Ask the agent to return findings in a fixed shape (e.g. severity, file, line, fix). Predictable outputs make the main session’s next step trivial.

🗂️ Commit project agents

Check .claude/agents/ into git so the whole team picks up the same advisors, planners, and reviewers.

📊 Pick the right model

Haiku for tiny scans, Sonnet for daily work, Opus when reasoning quality genuinely matters. Mixing models keeps cost under control.

Common mistakes & pro tips

❌ Common mistakes

  • Spawning agents for one-line tasks (just grep!)
  • Giving every agent the full toolset by default
  • Vague descriptions like “helps with code”—the main session can’t tell when to use it
  • Treating sub-agents as chat partners; they’re one-shot workers
  • Forgetting to version agent files in git—the team can’t reproduce your setup
  • Editing the system prompt without testing on a small task first

✅ Pro tips

  • Use plan mode + a custom planner agent for non-trivial features
  • Add a “return under 200 words” instruction to keep summaries tight
  • Run multiple agents in parallel from one prompt for big audits
  • Cite file_path:line in agent output so the user can jump straight there
  • Have a meta-agent that audits your other agents quarterly
  • Pin frequently-used agents to the top of the picker with descriptive emoji prefixes

Conclusion

Sub-agents are how Claude Code scales beyond “one big context window”. They let you delegate noisy, exploratory, or specialised work to a focused worker, keep your main session clean, and run multiple lines of reasoning in parallel. The built-in agents (Explore, Plan, General Purpose, Claude Code Guide) cover the common cases, and custom agents let you encode your team’s conventions, reviewer style, and project quirks into reusable Markdown files.

Start small. Build one advisor agent for your current project, commit it to .claude/agents/, and use it for a week. You will very quickly stop wondering why anyone codes without sub-agents.

Related reading: Claude Code vs Cursor AI comparisonwhen an AI agent deleted the production database

Claude Code Agents and Sub-Agents: The Complete Guide to Built-In and Custom Agents FAQ

What’s the difference between an agent and a sub-agent?

Nothing meaningful—they’re used interchangeably in Claude Code. “Sub-agent” emphasises that the worker is spawned from another Claude instance; “agent” emphasises that it’s an independent LLM run.

Does a sub-agent see the main conversation?

No. It only sees the prompt the main session hands it. That’s why descriptions and prompts must be self-contained—the agent walked in cold.

Can sub-agents call other sub-agents?

Yes, if you grant them the Agent tool. In practice, two levels of nesting is usually enough; deeper chains get hard to debug and burn tokens fast.

How are agents different from slash commands or skills?

Slash commands run inline in your main session—they don’t spawn a new context. Skills are reusable instruction packs the main session loads. Agents are full independent Claude instances with their own context window. Use slash commands for quick actions, skills for shared instructions, agents for delegated work.

Can I share custom agents with my team?

Yes—commit .claude/agents/*.md to git. Anyone who clones the repo and opens Claude Code in it gets the same agents automatically.

Do sub-agents use more tokens than inline work?

Per agent run, yes—there’s a fresh system prompt and the agent has to re-derive context. But across a long session, sub-agents typically save tokens because they prevent your main context from filling up with intermediate noise.

Can I edit the generated system prompt by hand?

Absolutely. The Markdown file is the source of truth—open it in your editor and tweak. Test on a small task before committing, since system prompt changes can shift behaviour significantly.

Should I always use Sonnet for sub-agents?

Sonnet is the right default. Drop to Haiku for cheap scans (security regex audits, lint passes); reach for Opus only when you need deeper reasoning, like architectural reviews of large refactors.