SkillCreator
Back to Journal
Claude CodeClaude CodeAgentsTutorialDeveloper Tools
Journal

Claude Code Agents: The Complete Guide to Subagents, Custom Agents, and Parallel Execution

How Claude Code agents work, from the Task tool to custom agents, parallel execution, and the Agent SDK. Architecture, practical recipes, and reusable agent patterns.

Author

SkillCreator Team

Published

February 19, 2026

Reading time

18 min read

Reading view

Claude Code18 min read

Use the progress bar to track your place, then jump to any section from the table of contents.

Claude Code Agents: The Complete Guide to Subagents, Custom Agents, and Parallel Execution

Claude Code can delegate work to isolated Claude instances called subagents. Each agent gets its own context window, works independently, and returns a summary when done. The main session stays lean. The agents handle the heavy lifting.

This is the complete guide to the system: how the Task tool spawns agents, the four built-in types, parallel and background execution, custom agent creation, and how it all connects to the Agent SDK. Every section includes architecture details and practical recipes you can use immediately.

If you build custom agents regularly, SkillCreator generates production-ready agent definitions from natural language prompts or documentation URLs. The same Markdown-plus-frontmatter format that powers Claude Code agents is the foundation of the agent skills standard, and a library of 47 curated agents is available via npx ai-agent-skills install <skill-name>.

How Agent Spawning Works

When Claude Code receives a task too large for a single context window, it delegates to subagents through the Task tool. Each subagent is a fresh Claude instance with its own context, its own tool access, and zero knowledge of the main conversation.

The architecture:

Main Claude Code Session (orchestrator)
  │
  ├── Task tool call ──► Agent A (own context window)
  ├── Task tool call ──► Agent B (own context window)
  └── Task tool call ──► Agent C (own context window)
                              │
                              ▼
                         Summaries (~200 tokens each)
                         return to main session

The main session asks a question or assigns a task. The agent reads files, makes edits, runs commands, and then sends back a summary of what it did. The main context does not grow by thousands of tokens from file reads and tool calls. It receives a 100-300 token summary instead.

This is the core insight behind agents: context management at scale. Five agents returning 200-token summaries add 1,000 tokens to the main session. Doing the same work inline could consume 10,000+ tokens.

The Task Tool: How Agents Get Spawned

Every subagent in Claude Code is created through the Task tool. There is no other mechanism. When you see agents spinning up in the terminal, the Task tool is making it happen.

Parameters

The Task tool accepts these parameters:

| Parameter | Required | Purpose | |-----------|----------|---------| | prompt | Yes | The task for the agent to perform | | description | Yes | Short 3-5 word summary (shown in UI) | | subagent_type | Yes | Which agent type to use | | model | No | Override model (sonnet, opus, haiku) | | max_turns | No | Limit API round-trips | | run_in_background | No | Run without blocking the session | | resume | No | Agent ID to continue from |

Execution Flow

  1. Claude calls the Task tool with a prompt and subagent type
  2. A new Claude instance spins up with a fresh, empty context window
  3. The instance receives the prompt as its first message
  4. Tools are restricted based on the subagent type
  5. The agent works autonomously, reading files, editing code, running commands
  6. When done, it returns a summary to the main session
  7. The main session receives approximately 200 tokens instead of the full work transcript

What the main session sees:

Task tool call → [agent works for 30 seconds] → Result:

"Created 3 files:
 - src/auth/middleware.ts (JWT validation)
 - src/auth/types.ts (token interfaces)
 - tests/auth.test.ts (12 test cases, all passing)
 Agent ID: abc123"

That is the entire cost to the main context window.

Built-in Subagent Types

Claude Code ships four agent types, each with different tool access and cost profiles.

Explore Agent

The fastest and cheapest option. Read-only tools: Glob, Grep, Read, WebFetch, WebSearch. No file writing or editing. Defaults to Haiku for speed.

Use for codebase search, understanding how a module works, finding all files that match a pattern. Supports thoroughness levels: "quick," "medium," or "very thorough."

"Find all files that handle authentication"
→ Spawns Explore agent
→ Returns file list and structure summary

Plan Agent

Also read-only. Same tools as Explore but inherits the parent model instead of defaulting to Haiku. Designed for pre-implementation research and architectural analysis.

Use when you need a deeper analysis that should match the quality of the main session's model.

General-Purpose Agent

Full tool access: Read, Write, Edit, Bash, Grep, Glob, and everything else. Inherits the parent model. The most capable and most expensive option.

Use for multi-step tasks that require both reading and writing. Feature implementation, refactoring, test creation.

Bash Agent

Bash only. Nothing else. Inherits the parent model. Lightweight isolation for command execution.

Use when you need to run commands whose output would bloat the main context. Test suites, build processes, long command chains.

Agent Types at a Glance

| Type | Tools | Default Model | Cost | Speed | Best For | |------|-------|---------------|------|-------|----------| | Explore | Read-only | Haiku | Low | Fast | Search, understand | | Plan | Read-only | Inherit | Medium | Medium | Architecture, design | | General | All | Inherit | High | Medium | Full implementation | | Bash | Bash only | Inherit | Low | Fast | Command isolation | | Custom | You define | You pick | Varies | Varies | Specialized tasks |

How Claude Decides When to Spawn Agents

Claude follows a decision tree influenced by both built-in instructions and any custom rules you define:

  1. Trivial task (single line fix, quick config) → Do it directly in the main context
  2. Matches a specific agent's description → Spawn that agent
  3. Research or exploration only → Spawn Explore agent (read-only, fast, cheap)
  4. Implementation across multiple files → Spawn general-purpose agent
  5. Parts can run independently → Spawn multiple agents concurrently
  6. Needs human feedback → Stay in the main context

You can shift this behavior with custom rules in ~/.claude/rules/ or .claude/rules/. For example, a rule that says "always use agents for implementation tasks" biases Claude toward delegation, preserving the main conversation's context for coordination.

Parallel Agent Execution

When Claude identifies independent subtasks, it spawns multiple agents in a single message. All agents run concurrently and return results together.

How It Works

User: "Research the auth system, the database layer, and the API routes"

Claude spawns three Task tool calls simultaneously:
  1. Task(Explore, "Research auth system...")
  2. Task(Explore, "Research database layer...")
  3. Task(Explore, "Research API routes...")

All three run concurrently.
All three return results.
Claude synthesizes into a unified response.

Parallelization Rules

| Scenario | Pattern | Why | |----------|---------|-----| | Independent tasks | Parallel | No dependencies, no shared state | | Dependent tasks | Sequential | One needs another's output | | Same-file edits | Never parallelize | Last write wins, race condition | | Read-only tasks | Safe to parallelize freely | No mutation conflicts |

When agents run in parallel, you see multiple spinner indicators in the terminal. Each shows the agent's description (the 3-5 word summary from the Task call).

Background Agents

Agents can run in the background while you continue interacting with the main session.

Foreground vs Background

| Aspect | Foreground | Background | |--------|-----------|------------| | Blocks main session | Yes | No | | Permission prompts | Interactive | Pre-approved only | | Can ask questions | Yes | No (fails gracefully) | | MCP tools | Yes | No | | Check output | Automatic | Read output file or tail |

How to Background an Agent

Three ways:

  1. Request it directly: "Run the test suite in the background while I work on something else"
  2. Press Ctrl+B while a foreground agent is running
  3. Set run_in_background: true in the Task tool parameters

When a background agent starts, the Task tool returns an output_file path. Read that file to check progress or results.

Agent Communication and Results

What Flows Between Agents and the Main Session

Main → Agent:

  • The prompt (task description)
  • That is it. No conversation history. The agent reads its own files and figures out context.

Agent → Main:

  • A summary of work done
  • Agent ID (for resuming)
  • Any errors or blockers encountered

What Agents Inherit

Agents automatically receive:

  • Full read/write access to project files (based on tool permissions)
  • Your CLAUDE.md instructions
  • Project rules from .claude/rules/*.md
  • MCP servers configured in .mcp.json

What Agents Cannot See

  • Your conversation with the main session
  • Other agents' work (unless reading shared files)
  • Previous agent results (unless explicitly resumed)

Resuming Agents

Every agent invocation gets a unique agent ID. You can resume an agent to continue its work with full context preserved.

"Continue the code review agent from earlier"
→ Claude uses Task tool with resume: "agent-id-here"
→ Agent picks up with full previous context

What is preserved on resume:

  • Full conversation history within the agent
  • All previous tool calls and their results
  • The agent's reasoning state
  • Any file modifications it tracked

Practical use case: an agent does partial work, hits a question, and returns to the main session. You provide guidance. Claude resumes the agent with new instructions appended. The agent continues with full prior context plus your feedback.

Agent transcripts live at:

~/.claude/projects/{project-hash}/{sessionId}/subagents/agent-{agentId}.jsonl

Creating Custom Agents

This is where the system becomes extensible. You can define your own agent types that Claude Code discovers and routes to automatically.

The Markdown File Method

Create a file at .claude/agents/my-agent.md (project-level) or ~/.claude/agents/my-agent.md (global):

---
name: code-reviewer
description: Expert code review specialist. Use after writing code to check quality.
tools: Read, Grep, Glob, Bash
model: sonnet
maxTurns: 10
---

You are a senior code reviewer. When invoked:

1. Run `git diff` to see recent changes
2. Check for:
   - Security vulnerabilities
   - Performance issues
   - Missing error handling
   - Style inconsistencies
3. Report findings organized by severity (critical/warning/info)
4. Suggest specific fixes with code snippets

Frontmatter Fields

| Field | Required | Purpose | |-------|----------|---------| | name | Yes | Lowercase identifier | | description | Yes | When Claude should use this agent | | tools | No | Tool allowlist: "Read, Grep, Glob, Bash" | | disallowedTools | No | Tool denylist: "Write, Edit" | | model | No | "sonnet", "opus", "haiku", or "inherit" | | maxTurns | No | Max API round-trips before stopping | | permissionMode | No | "default", "acceptEdits", "bypassPermissions" | | skills | No | Skills to preload | | mcpServers | No | MCP servers available to this agent |

File Location Precedence

  1. --agents CLI flag (session-only, highest priority)
  2. .claude/agents/ (project-level, version controlled)
  3. ~/.claude/agents/ (user-level, all projects)

The Connection to Agent Skills

Custom agents use the same Markdown-plus-frontmatter format as the agent skills standard. A .claude/agents/code-reviewer.md is structurally identical to a SKILL.md file. The frontmatter declares metadata and constraints. The body contains instructions.

This means every custom agent you create is effectively a skill. And every skill from the SkillCreator registry can inform how you structure your agents.

Browse 47 curated agent definitions at skillcreator.ai/discover, or install them directly:

npx ai-agent-skills install code-review

If you need to create agents from documentation or internal runbooks, SkillCreator generates production-ready Markdown agent files from any URL or natural language description.

Customizing Agent Behavior

Beyond creating custom agent types, you can shape how all agents behave.

Via CLAUDE.md

Agents inherit your project's CLAUDE.md. Anything you put there applies to agents too:

## Implementation Standards

- All new functions must have JSDoc comments
- Use TypeScript strict mode
- Tests required for any new feature

Via .claude/rules/

Rules files are inherited by agents. Write rules that specifically target agent behavior:

# .claude/rules/agent-behavior.md

When operating as a subagent:
- Always verify file existence before editing
- Run tests after any code change
- Report which files you modified in your summary

Via settings.json

Control permissions and hooks:

{
  "permissions": {
    "deny": ["Task(risky-agent)"]
  }
}

Files That Control Agent Behavior

~/.claude/rules/*.md          → Global rules all agents inherit
.claude/rules/*.md            → Project rules all agents inherit
.claude/agents/*.md           → Custom agent type definitions
.claude/settings.json         → Permissions, hooks, environment
CLAUDE.md                     → Project instructions agents inherit
.mcp.json                     → MCP servers agents can access

Claude Agent SDK vs Claude Code Agents

The Claude Agent SDK is a separate Python/TypeScript framework for building standalone autonomous agents. It is fundamentally different from Claude Code's built-in subagents.

| | Claude Code Subagents | Claude Agent SDK | |---|---|---| | Where they live | Inside a Claude Code session | Standalone programs you deploy | | How they start | Spawned by the Task tool | Run independently | | Human in the loop | Always | Optional | | Tools | Claude Code built-in (Read, Write, Bash) | You define custom tools via code | | Configuration | Markdown agent definitions | Python/TypeScript code | | Lifespan | Ephemeral (session only) | Persistent (run as long as you want) | | Deployment | Local terminal | Services, bots, CI/CD pipelines |

When to Use What

  • "Help me implement this feature" → Claude Code subagents
  • "Review this PR in my terminal" → Claude Code subagents
  • "Build a bot that monitors my repo 24/7" → Agent SDK
  • "Create a CI pipeline that auto-fixes lint errors" → Agent SDK
  • "Run a cron job that summarizes daily PRs" → Agent SDK

Bridging the Two

You can use Agent SDK agents from Claude Code by wrapping them as custom agents:

# .claude/agents/my-sdk-agent.md
---
name: my-custom-agent
description: Runs my custom Agent SDK agent for specialized analysis
tools: Bash
---

Run the custom agent:
cd $CLAUDE_PROJECT_DIR && uv run python agents/my_agent.py --task "$TASK_DESCRIPTION"

Or expose Agent SDK agents as MCP servers that Claude Code discovers natively through .mcp.json.

Practical Recipes

Recipe 1: Parallel Research with Explore Agents

"Research these three areas in parallel using Explore agents:
1. How authentication works in src/auth/
2. How the database models are structured in src/models/
3. How the API routes are organized in src/routes/"

Claude spawns three Explore agents simultaneously. Total cost to main context: approximately 600 tokens of summaries instead of 15,000+ tokens of file content.

Recipe 2: Custom Code Review Agent

# .claude/agents/reviewer.md
---
name: reviewer
description: Code review specialist. Use after writing code.
tools: Read, Grep, Glob, Bash
model: haiku
maxTurns: 8
---

Review the code changes. Run `git diff` to see what changed.

Check for:
1. Security vulnerabilities (injection, XSS, auth bypass)
2. Performance issues (N+1 queries, unnecessary re-renders)
3. Missing error handling at system boundaries
4. Style inconsistencies with surrounding code

Output format:
- CRITICAL: [issue] at [file:line]
- WARNING: [issue] at [file:line]
- INFO: [suggestion] at [file:line]

Recipe 3: Test Runner Agent

# .claude/agents/test-runner.md
---
name: test-runner
description: Run tests and report results. Use after implementation.
tools: Bash, Read, Grep
model: haiku
maxTurns: 5
---

Run the project's test suite and report results.

1. Find the test command (check package.json, Makefile, pyproject.toml)
2. Run the tests
3. If failures, read the failing test files and summarize what went wrong
4. Report: X passed, Y failed, Z skipped

Recipe 4: Background Agent While You Work

"Run the full test suite in the background while I work on the next feature"

Check status later:

"What did the test run find?"

Recipe 5: Building a Library of Reusable Agents

Instead of creating agents one at a time, build a library. The ai-agent-skills npm package ships 47 curated agent definitions you can install and customize:

npx ai-agent-skills list          # Browse available agents
npx ai-agent-skills install code-review  # Install one

Every installed agent is a plain Markdown file you own. Edit it to fit your team's standards, add your company's style guide rules, remove categories you do not care about. The installed agent is a starting point, not a locked dependency.

Or generate custom agents from any documentation URL at skillcreator.ai. Paste your internal API docs or deployment runbook and get a production-ready agent definition.

Key Commands

| Action | Command | |--------|---------| | Manage custom agents | /agents | | Background a running agent | Ctrl+B | | Invoke specific agent | "Use the reviewer agent to check the auth module" | | Hint for parallel agents | "Do X and Y in parallel" | | Resume agent | "Continue the [agent] from earlier" |


Frequently Asked Questions

What are Claude Code agents?

Claude Code agents (subagents) are isolated Claude instances spawned by the Task tool to handle specific subtasks. Each agent gets its own context window, runs independently, and returns a summary to the main session. This keeps the main conversation lean while agents handle file reads, code implementation, testing, and other heavy operations. The main session receives approximately 200 tokens of summary instead of the thousands of tokens the work would consume inline.

How does the Claude Code Task tool work?

The Task tool is the single mechanism that spawns all subagents. You provide a prompt, a short description, and a subagent type (Explore, Plan, general-purpose, or Bash). The tool spins up a fresh Claude instance with its own context window, restricted tools based on the agent type, and the specified model. When the agent finishes, only a summary returns to the main session. Optional parameters include model override, max turns, background execution, and agent ID for resumption.

What subagent types are available in Claude Code?

Four built-in types: Explore (read-only, defaults to Haiku, fastest and cheapest), Plan (read-only, inherits parent model, for architectural analysis), general-purpose (all tools, inherits parent model, for full implementation), and Bash (command execution only, for isolating command output). You can extend this with custom agent types defined in .claude/agents/ using Markdown files with YAML frontmatter.

How do I create a custom agent in Claude Code?

Create a Markdown file at .claude/agents/my-agent.md (project-level) or ~/.claude/agents/my-agent.md (global). Add YAML frontmatter with name, description, tools, and optionally model and maxTurns. The body contains the agent's instructions in Markdown. Claude Code discovers these automatically and routes matching tasks to them. You can also use the /agents command for an interactive setup, or generate agents from documentation URLs using SkillCreator.

Can Claude Code run agents in parallel?

Yes. When Claude identifies independent subtasks, it spawns multiple agents simultaneously using multiple Task tool calls in a single message. All agents run concurrently and return results together. The rules: independent tasks run in parallel, dependent tasks run sequentially, same-file edits should never be parallelized, and read-only tasks are always safe to parallelize.

What is the difference between Claude Code subagents and Agent Teams?

Subagents are isolated workers that report back to the main session only. They do not communicate with each other. Agent Teams are coordinated groups where multiple agents share a task list and can message each other directly. Subagents work well for focused, independent tasks. Agent Teams are better for complex work that requires cross-agent coordination, like a frontend agent and backend agent working on the same feature.

How do background agents work in Claude Code?

Background agents run without blocking your main session. Trigger them by requesting background execution, pressing Ctrl+B on a running agent, or setting run_in_background: true in the Task tool. Background agents cannot ask interactive questions or use MCP tools. When a background agent starts, you receive an output file path to check progress. Read that file or use tail to see recent output.

What is the Claude Agent SDK and how does it differ from Claude Code agents?

The Claude Agent SDK is a Python/TypeScript framework for building standalone autonomous agents that run independently of Claude Code. Claude Code subagents live inside a session, are spawned by the Task tool, and always have a human in the loop. Agent SDK agents are programs you build and deploy as services, bots, or CI/CD pipelines with full control over the agent loop. You can bridge the two by wrapping Agent SDK agents as Claude Code custom agents via Bash, or by exposing them as MCP servers.

Keep reading

Previous and next from the journal.

Next step

Want the workflow behind the article?

Download the desktop app, read the docs, and follow the changelog to see how the public system evolves release by release.