Web Dev Drops

Claude Code Subagents and Custom Slash Commands

avatar
Douglas Matoso
Updated at 10/26/2026
Reading time: 18 min.

A long session with an AI coding agent has a cost that's easy to miss: every file Claude reads, every test log and every search result stays in the context window. After a while, the conversation is full of output you no longer need. Claude Code subagents solve this. In this post I will show you what they are, how to create your own, and how to write custom slash commands that run them. The short answer: a subagent is a Markdown file in .claude/agents/ with a name, a description and a system prompt. Claude hands a task to it, the subagent works in its own context window (with its own tools and model), and only a summary comes back to your conversation. A custom slash command is a Markdown file in .claude/commands/ that becomes /file-name, and with two lines of frontmatter it can run inside a subagent.

Claude logo on a white badge next to a delegation tree icon, with the title Claude Code Subagents below

Note: Everything here was checked against the official docs on October 26, 2026, and the examples were tested with Claude Code 2.1.310 on Windows 11.

What are Claude Code subagents?

A subagent is a specialized assistant that Claude starts to do one task. Each subagent has:

  • its own context window, separate from your conversation;
  • its own system prompt, the instructions you write in the file;
  • its own tools and permissions, so a reviewer can be read-only, for example;
  • its own model, so you can send simple tasks to a faster, cheaper model.

Claude decides when to delegate by comparing the task with the description of each subagent. The subagent reads files, runs commands, and when it finishes, only its final answer goes back to the main conversation. All the intermediate output stays in the subagent's context.

Diagram: the main context sends a task to a subagent full of documents and receives back only a summary

This helps in three situations:

  1. Tasks with a lot of output, like running the test suite, reading logs or searching a big codebase, where you only want the conclusion.
  2. Tasks that need limits: a code reviewer that can't edit files, a database agent that can only run SELECT.
  3. Tasks you repeat. You write the role once, commit it to the repository, and the whole team gets it.

A subagent starts fresh. It doesn't get your conversation history or the Claude Code system prompt. It gets its own prompt, the task message Claude writes for it, your CLAUDE.md files and a git status snapshot. So the task message needs to stand on its own, and Claude writes it with that in mind.

Important! Subagents count toward the same usage limits as your main conversation.

Built-in subagents

Claude Code already comes with some subagents, and you've probably seen them working without noticing:

SubagentWhat it doesNotes
ExploreSearches and reads the codebase (quick, medium or very thorough)Read-only
PlanResearches the code while you're in plan modeRead-only
general-purposeComplex tasks with several stepsAll tools
claude-code-guideAnswers questions about Claude Code itselfRuns on Haiku

When you ask "where is the authentication handled in this project?", Claude usually sends Explore to search, and you get the answer without dozens of file reads in your context.

How to create a custom subagent

Let's create a subagent that reviews uncommitted changes. It can read files and run git diff, but it can't edit anything.

1. Create the file

Subagents live in an agents folder. Where you put it decides who can use it:

LocationApplies to
.claude/agents/This project (commit it and the team gets it)
~/.claude/agents/All your projects
--agents flag (JSON)Only the current session
Plugin agents/ folderWhere the plugin is enabled

When two subagents have the same name, the CLI flag wins over the project, and the project wins over your personal folder. On Windows, ~ is your user folder: C:\Users\<you>\.claude\agents.

Save this to .claude/agents/code-reviewer.md:

---
name: code-reviewer
description: Reviews uncommitted code changes for bugs, security issues and readability. Use proactively after writing or changing code.
tools: Read, Grep, Glob, Bash
model: sonnet
---

You are a senior code reviewer. You don't edit files.

When invoked:
1. Run `git diff` to see the uncommitted changes (and `git diff --cached` for staged ones).
2. Read the changed files when you need more context.
3. Review only what changed.

Report your findings grouped by priority:
- **Critical** (must fix): bugs, security issues, data loss
- **Warning** (should fix): error handling, edge cases
- **Suggestion** (nice to have): naming, readability

For each finding, give the file and line, explain the problem in one or two sentences and show the fix.
If there's nothing to report, say so in one line.

What each part does:

  • name: the identifier, in lowercase with hyphens.
  • description: what Claude reads to decide when to delegate. Phrases like "use proactively" make Claude more likely to call it on its own.
  • tools: the allowlist. Without Edit and Write, this subagent can't change files. If you leave tools out, it inherits all the tools available to subagents.
  • model: sonnet, opus, haiku, a full model ID, or inherit (the same model as your conversation).
  • The body: the subagent's system prompt. Write it the way you'd brief a teammate who has never seen the project.

Tip: You don't need to restart Claude Code after editing the file: changes are picked up within seconds. You only need a restart when you create the first file in an agents folder that didn't exist before.

2. Use it

Make some change in the code and ask:

Use the code-reviewer subagent to review my changes

To test, I added this function to a project, with three problems on purpose:

export async function deleteUser(db, id) {
  const apiKey = 'sk-live-12345'
  await fetch(`https://api.example.com/users/${id}?key=${apiKey}`, { method: 'DELETE' })
  return db.query(`DELETE FROM users WHERE id = ${id}`)
}

The subagent ran git diff, read the file, and returned the review grouped by priority: the hardcoded API key, the key going in the URL (where it ends up in logs), the SQL injection, and, as a warning, that fetch doesn't throw on 4xx/5xx, so the row is deleted locally even when the remote delete fails. Only this report came back to my conversation; the diff and the files it read stayed in the subagent's context.

Claude Code subagent frontmatter: the fields you will use

Only name and description are required. These are the other fields that are most useful:

FieldWhat it does
tools / disallowedToolsTools the subagent can use (allowlist) or can't use (denylist)
modelsonnet, opus, haiku, a full model ID or inherit
effortReasoning effort: low to max
permissionModedefault, acceptEdits, auto, dontAsk, plan...
skillsSkills loaded into the subagent's context when it starts
mcpServersMCP servers only this subagent can use
hooksHooks that run only while this subagent is active
memoryPersistent memory across sessions: user, project or local
isolation: worktreeRuns the subagent in a temporary git worktree, so its edits don't touch your checkout
backgroundtrue always runs it in the background
maxTurnsMaximum number of turns before it stops

The hooks field is good for rules that the prompt alone can't guarantee. The official docs show a db-reader subagent with a PreToolUse hook that blocks any INSERT, UPDATE or DELETE before the command runs. If you haven't used hooks yet, I explained how they work in Claude Code Hooks: A Practical Guide with Examples.

Note: Field names are case-sensitive (disallowedTools, not disallowed-tools), and unknown fields are ignored without any error. If a subagent doesn't show up, check the YAML first.

How to use subagents in Claude Code

There are a few ways to start a subagent:

  • Let Claude decide. If the description matches the task, Claude delegates on its own.
  • Ask in plain language: "use the code-reviewer subagent to...". This is the most reliable way.
  • @-mention: type @ and pick the agent from the list, or type @agent-code-reviewer followed by the task.
  • Run the whole session as the agent: claude --agent code-reviewer. The agent's prompt, tools and model apply to the main conversation. To make it the default in a project, add "agent": "code-reviewer" to .claude/settings.json.
  • Define it on the command line, for a single session or a script:
claude --agents '{
  "code-reviewer": {
    "description": "Reviews code changes. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on bugs and security.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  }
}'

Tip: The /agents command used to open a wizard to create subagents. In current versions it only prints a reminder: ask Claude to create the subagent for you ("create a subagent in .claude/agents that runs the tests and reports only the failures"), or write the file yourself.

Forks: a subagent that knows the conversation

A regular subagent starts with an empty context. A fork is a subagent that inherits the whole conversation up to that point, so you don't have to explain the situation again. Its tool calls still stay out of your context, and only the result comes back. Start one with /subtask:

/subtask draft unit tests for the parser changes so far

The fork runs in the background while you keep working, and its result arrives as a message when it finishes. Since it shares the prompt cache with your conversation, it's cheaper than a fresh subagent for tasks that need the same context.

Running Claude Code subagents in parallel

By default, a subagent that Claude starts from your conversation runs in the background: you can keep talking to Claude while it works. You can also ask for several at once:

Research the authentication, database and API modules in parallel using separate subagents

Some details worth knowing:

  • Running subagents show up in a panel below the prompt. Use the arrows and Enter to open one's transcript and send it a message.
  • /tasks lists the background work of the session, including subagents that already finished.
  • If a task is running in the foreground, Ctrl+B moves it to the background.
  • Up to 20 subagents can run at once (CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS changes it), and a subagent can start its own subagents up to three levels deep (CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH).

Important! Parallel subagents that edit files can step on each other. For parallel edits, use isolation: worktree (each subagent gets its own copy of the repository) or give each one a separate set of files. I explained how worktrees work in Git Worktree: Multiple Branches (and AI Agents) in Parallel.

Claude Code custom slash commands

Claude Code also has slash commands: built-in ones like /clear and /model, and custom ones that you create. A custom command is a saved prompt: you type /name and Claude Code sends the content of the file as your message.

To create one, save a Markdown file in .claude/commands/ (project) or ~/.claude/commands/ (all your projects). The file name becomes the command name.

Note: Claude Code merged custom commands into skills. A file at .claude/commands/deploy.md and a skill at .claude/skills/deploy/SKILL.md both create /deploy and work the same way. The commands folder still works and is the simplest option for a single-file prompt. When you need extra files (scripts, templates) or want Claude to load the command on its own, use a skill. I covered skills in Claude Code Skills: How to Create Your Own.

Example: a command with arguments and command output

Let's create a command that summarizes what changed since the last commit. Save it to .claude/commands/git/summary.md:

---
description: Summarizes what changed since the last commit
argument-hint: [focus]
allowed-tools: Bash(git diff *) Bash(git status *)
---

## Changes

!`git status --short`

!`git diff --stat`

Summarize these changes in 3 bullet points for a teammate. $ARGUMENTS

What's in it:

  • The subfolder becomes a namespace: git/summary.md is called as /git:summary. This keeps related commands together.
  • description shows up in the / menu.
  • argument-hint shows what the command expects while you type it.
  • The !`command` lines run before the prompt is sent, and their output replaces the line. Claude gets the git status ready, without spending a step to run it. If one of these commands fails, the whole command is cancelled.
  • allowed-tools lets these git commands run without a permission prompt. The injected commands go through your permission rules, so without this line (or a matching allow rule) the command doesn't run.
  • $ARGUMENTS is replaced with everything you type after the command name.

Running it:

/git:summary focus on security

In my test project, Claude listed the new deleteUser function, the hardcoded key and the SQL built with string interpolation, all in three bullets.

Arguments in custom commands

PlaceholderReplaced with
$ARGUMENTSEverything you typed after the command
$0, $1...Each argument by position, starting at 0 (quotes group words: "hello world" is one argument)
$nameA named argument declared in the arguments frontmatter field, like arguments: [issue, branch]

If the file has no placeholder at all, Claude Code adds ARGUMENTS: <what you typed> at the end of the prompt, so the arguments aren't lost.

A slash command that runs in a subagent

With context: fork in the frontmatter, a command runs outside your conversation. Claude Code starts a subagent and gives it the command's content as the task. The agent field picks which subagent. It can be a built-in one (Explore, Plan, general-purpose) or one of yours.

Save this to .claude/commands/review-changes.md:

---
description: Reviews the uncommitted changes in a separate context with the code-reviewer subagent
context: fork
agent: code-reviewer
---

Review the uncommitted changes in this repository. $ARGUMENTS

Now /review-changes always runs the review with the code-reviewer we created earlier: its prompt, its read-only tools and its model.

Flow diagram: the /review-changes command starts the code-reviewer subagent, which returns a report

I ran it in non-interactive mode to look at the events:

claude -p "/review-changes" --output-format stream-json --verbose

The output showed the task going to subagent_type: "code-reviewer", running on claude-sonnet-5-5 (the model: sonnet from the subagent file), and the final answer was the same prioritized report from before. The whole run took 13 seconds and cost US$ 0.03 in API terms.

A few things to keep in mind:

  • The subagent doesn't see your conversation, so write the command as a complete task. A command that only says "follow these conventions" gives the subagent nothing to do.
  • The forked command runs in the background by default. Add background: false if you want Claude to wait for the result in the same turn.
  • In Git Bash, claude -p "/review-changes" gets the / converted to a Windows path. Run it with MSYS_NO_PATHCONV=1 in front, or use PowerShell.

Useful built-in Claude Code commands

Type / in Claude Code to see the full list. These are the ones that relate to subagents and context:

CommandWhat it does
/agentsReminds you where subagent files live and how to create them
/tasksLists and manages background work, including subagents
/subtask <task>Starts a fork that knows the whole conversation
/btw <question>Asks a side question without adding it to the conversation
/contextShows how much of the context window is in use, and by what
/compactSummarizes the conversation to free up context
/clearStarts a new conversation with an empty context
/reviewReviews the current diff, a branch or a PR (alias of /code-review)
/simplifyRuns four review agents in parallel on the changed code and applies the fixes
/skillsLists the available skills and custom commands
/initCreates a CLAUDE.md for the project

MCP servers can also expose prompts that show up as commands in the same / menu.

Subagents vs agent teams vs skills

Claude Code has a few features that sound alike. This is how they compare:

FeatureHow it worksUse it for
SubagentSeparate context, reports back only to the agent that started itFocused tasks where only the result matters
Agent teamSeveral full Claude Code sessions with a shared task list, messaging each otherWork that needs discussion: parallel review, competing hypotheses for a bug
SkillInstructions loaded into the current context when usedProcedures and knowledge: "how we do X here"
Custom commandA saved prompt you run with /namePrompts you type often; with context: fork, a shortcut to a subagent

Agent teams are still experimental and disabled by default. To try them, set CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS to 1 in the env of your settings.json and ask Claude for teammates. They use a lot more tokens than subagents, because each teammate is a separate Claude instance, and they only work in interactive sessions. The docs recommend starting with 3 to 5 teammates. Your subagent files can be reused as teammate roles ("spawn a teammate using the code-reviewer agent type").

Tips for writing subagents that work

  • Give each subagent one job. A "reviewer" and a "test runner" work better than a "helper" that does everything.
  • Make the description specific, since it's what Claude uses to pick the subagent. Say what it does and when to use it, with the words you use when you ask.
  • Give it only the tools it needs. A reviewer doesn't need Edit, and fewer tools means fewer permission prompts.
  • Ask for a short result. The subagent's answer goes into your context, so "report only the failing tests" is better than "run the tests".
  • Pick the model by task. Searching and summarizing work fine on haiku or sonnet; keep opus or inherit for reviews and design.
  • Keep small things in the main conversation. For quick edits and back-and-forth work it's faster, because a subagent has to rebuild context from scratch every time.
  • Commit .claude/agents/ and .claude/commands/, so the whole team uses the same reviewer and the same commands.

FAQ

Where are Claude Code subagents stored?

Project subagents are in .claude/agents/*.md inside the repository, and personal ones in ~/.claude/agents/*.md (on Windows, C:\Users\<you>\.claude\agents). Subfolders are scanned too, and the subagent's identity comes from the name field, not from the file name.

Can Claude Code subagents run in parallel?

Yes. Subagents that Claude starts from your conversation run in the background by default, and up to 20 can run at the same time. Ask for it explicitly ("in parallel, using separate subagents"), and keep subagents that edit files away from each other's files, or use isolation: worktree.

Can a subagent use a different model?

Yes. Set model in the frontmatter to sonnet, opus, haiku, a full model ID, or inherit. To force every subagent onto one model, set CLAUDE_CODE_SUBAGENT_MODEL together with CLAUDE_CODE_SUBAGENT_MODEL_FORCE=1 in the env of your settings.

Do custom slash commands still work after the merge with skills?

Yes. Files in .claude/commands/ and ~/.claude/commands/ keep working and accept the same frontmatter as skills, except name and paths. If a skill and a command have the same name, the skill wins.

Conclusion

Subagents are how you keep a long Claude Code session clean: the heavy work happens in a separate context and only the result comes back. Start with one subagent for a task you repeat (a reviewer, a test runner), limit its tools, and ask for a short report. Then wrap it in a custom slash command with context: fork and agent, and the whole workflow becomes a single /command.

If you want to go further, see how skills package procedures and scripts, and how hooks enforce rules that must run every time.