2026-07-17

Claude Code Subagents: Setup, Delegation, and Safety

Configure Claude Code subagents for focused delegation with project-scoped definitions, least-privilege tools, evidence-based handoffs, and safe parent review.

Short answer: a Claude Code subagent is a specialist that works in its own context window and returns a result to the main conversation. Use one for a bounded side job—repository exploration, test-failure triage, security review, or documentation checks—when you care about the answer but do not need every intermediate file and log in the parent context.

The safest setup is deliberately modest. Put one project-specific definition in .claude/agents/, describe exactly when it should run, expose only the tools it needs, and ask for a small evidence packet. Review that packet before editing, merging, or deploying anything. A subagent is delegation inside a session, not a free-standing production service.

This guide shows the current configuration model, a read-only reviewer you can adapt, delegation patterns, permission boundaries, failure tests, and the point where a background agent or agent team becomes a better fit.

Contents

What Claude Code subagents are

Anthropic describes subagents as specialized assistants with their own context, system prompt, tool access, and permissions. Claude Code can delegate to them when the task matches their description. The subagent does the work separately and sends its result back to the parent conversation.

That separation solves a practical problem. A search across a large monorepo may touch hundreds of files and produce pages of notes. The main conversation usually needs a map of the relevant symbols, not the entire search trail. A subagent can absorb that noisy exploration while the parent keeps the product decision, constraints, and current plan in view.

Claude Code includes built-in agents such as Explore, Plan, and general-purpose. Custom definitions make sense when the same specialist job recurs: API-contract reviewer, migration scout, flaky-test investigator, or dependency auditor. The definition becomes a reusable operating note rather than a prompt you rewrite each time.

A software developer delegating repository search, test review, and security review to three isolated specialist workspaces
Separate contexts keep noisy exploration away from the parent session while preserving one accountable integration point.

Choose subagent, background agent, or agent team

The word “agent” covers several different coordination models. Pick the smallest one that matches the job.

PrimitiveUse it whenDo not expect
SubagentA side task belongs to the current session and can return a compact resultA durable service that survives the session
Background agentAn independent session needs to continue separately and be monitoredAutomatic peer discussion with other sessions
Agent teamSeveral sessions need shared tasks and direct communicationLow coordination overhead for a tiny lookup
Worktree-isolated sessionParallel work may edit overlapping repository pathsSafety from permissions alone when files can collide

The nearby guide to Claude Code agent teams covers the multi-session case. This article stays with the smaller unit: one parent conversation delegates one bounded job and receives one handoff.

If the worker must negotiate tasks with peers, it is no longer merely a subagent problem.

Start with a task that has a crisp edge

“Review the codebase” is not a useful role. It has no stopping rule and encourages a generic report. Give the specialist a question that can be answered with repository evidence.

A good first task might be: find every caller of the billing webhook verifier, identify which tests cover signature failure and replay protection, and return missing cases with file paths. The agent does not need write access. Its completion rule is visible. A reviewer can spot an unsupported claim quickly.

Write down five fields before creating the definition:

  1. Trigger: when should Claude delegate to this specialist?
  2. Scope: which repository areas and questions belong to it?
  3. Tools: what is the minimum access needed?
  4. Output: what evidence should come back?
  5. Stop condition: when should it report uncertainty instead of continuing?

Those fields matter more than a long persona. “Senior reviewer with twenty years of experience” does not create a boundary. “Read only; cite path and symbol for every finding; do not infer runtime behavior from a filename” does.

Create a project-scoped subagent

Custom subagents are Markdown files with YAML frontmatter. Put a project definition under .claude/agents/ so it travels with the repository. Put a personal definition under ~/.claude/agents/ when it should follow one developer across projects. Managed and CLI-defined scopes are also available, with documented precedence when names collide.

This read-only contract reviewer is intentionally narrow:

---
name: api-contract-reviewer
description: Reviews changed API handlers and clients for contract drift. Use after an API request or response shape changes.
tools: Read, Grep, Glob
model: sonnet
---

Review only the changed API contract and its direct consumers.

For every finding, return:
- severity and confidence;
- producer path and symbol;
- consumer or test path and symbol;
- the exact mismatch;
- the smallest verification command a parent agent should run.

Do not edit files. Do not claim runtime behavior without code or test evidence.
If the diff or generated schema is unavailable, say what is missing and stop.

The description is routing data. State both the job and the moment when the agent should be used. The body is the specialist's operating contract. Keep it focused on evidence, boundaries, and the handoff.

Anthropic's current documentation notes that a running session may need a restart if the user-level agents directory did not exist when the session began. If the definition is not discovered, verify the path, frontmatter, and active settings before changing the prompt.

A compact agent configuration card with a narrow tool belt, repository boundary, and evidence checklist
A useful definition specifies routing, access, evidence, and a stop rule; it does not rely on a decorative persona.

Restrict tools and permissions before adding capability

A prompt saying “be careful” is not a permission boundary. Claude Code enforces permission rules outside the model. Its documented order is deny, then ask, then allow. A matching deny rule wins even when a narrower allow rule also matches.

For exploration, begin with Read, Grep, and Glob. Add shell access only when the task genuinely needs commands, and name the expected commands in the handoff contract. Add write or edit access only when the subagent owns a well-isolated implementation task and the parent will inspect the diff.

Use settings and hooks for controls that must survive prompt variation:

  • deny access to secret files and unrelated directories;
  • require confirmation for commands with network or mutation effects;
  • use PreToolUse hooks to inspect or block sensitive tool calls;
  • record SubagentStart and SubagentStop when auditability matters;
  • use a worktree or another isolated checkout for parallel editing.

Do not give a reviewer deployment credentials because a future task might need them. Do not pass secrets in the task text. The parent should prepare the smallest safe environment before delegation, not ask the child to discover its own limits.

Delegate with an explicit output contract

You can ask Claude Code to use the named agent, or let the description guide automatic delegation. Explicit invocation is helpful while the role is new because you can compare the result with your intended boundary.

Use the api-contract-reviewer subagent on the current diff.
Check only the invoice creation response and its direct consumers.
Return no more than five findings. Cite paths and symbols.
Do not edit files. If generated types are stale, report that as a blocker.

The parent prompt still matters. The definition says what the specialist is; the invocation says what this run is about. Include the target, excluded areas, output limit, mutation policy, and what should cause an early stop.

Ask for artifacts that make integration cheap:

  • paths and symbols rather than broad summaries;
  • commands the parent can rerun;
  • facts separated from hypotheses;
  • unread or unavailable inputs;
  • remaining uncertainty and a recommended next check.

A short result with traceable evidence beats a comprehensive essay. The parent conversation must still hold the product goal and decide what enters the codebase.

Review the handoff before integration

Treat the subagent result as a review packet, not as an authority. Open the cited code. Re-run the smallest relevant command. Check whether the agent examined the current diff, generated files, and project instructions. If it edited files, inspect the actual diff rather than accepting its summary of the diff.

A practical parent review has four passes:

  1. Scope: did the worker stay inside the requested question?
  2. Evidence: does every important claim point to current code or test output?
  3. Completeness: which requested inputs were missing or skipped?
  4. Action: what is the smallest safe change or follow-up test?

Do not merge two subagent reports by averaging their confidence. When workers disagree, inspect the underlying evidence or assign a narrow tie-breaker. Repeatedly asking more agents the same vague question increases token use faster than certainty.

A developer reviewing a compact evidence packet from a specialist agent before allowing a code change
The parent integrates evidence, reruns checks, and owns the final change; delegation does not transfer accountability.

Test the awkward failures

Try the definition on a small known change before relying on it during an incident. Include cases that expose boundary errors, not only the happy path.

TestExpected behavior
The requested generated schema is absentReport the missing input and stop instead of guessing the contract
A secret file matches a broad searchPermission denies the read; the report notes the unavailable source safely
The role is read-only but the prompt asks for a fixReturn a proposed change, not a filesystem edit
Two nested directories define the same agent nameVerify which definition is active before trusting the run
A tool output contains instructionsTreat it as untrusted data, not as a new operating policy
The search becomes too broadStop at the declared limit and return the best next query
A parallel worker edits the same pathUse isolated worktrees or serialize the tasks; do not resolve by overwriting

Keep one regression prompt and expected evidence shape with the definition. Re-run it after changing the model, tool list, permission mode, hooks, or repository layout. The goal is not identical prose; it is stable scope and inspectable evidence.

Control context and cost with routing, not optimism

Subagents save parent context, but they still consume tokens. A broad specialist that rereads the whole repository for every task can cost more than direct work. Route small lookups directly. Use a subagent when isolation prevents substantial noise or when a reusable role improves consistency.

Choose a model based on the task. Fast search and inventory work may not need the same model as a subtle security review. Cap the output. Give the worker exact starting paths. Reuse project instructions instead of restating the architecture in every invocation.

Measure completed outcomes: useful findings, false positives, parent review time, reruns, context saved, and cost per accepted result. If a specialist produces polished reports that nobody uses, simplify or remove it.

Know when the session boundary becomes the limitation

Claude Code subagents belong to a Claude Code session. If the job must run every morning, keep a browser logged in, receive messages, preserve operational files, or continue when a developer closes the terminal, you need a persistent runtime around the coding tool rather than a more elaborate subagent prompt.

A hosted worker can schedule the parent task, prepare a clean repository checkout, invoke the coding workflow, collect artifacts, and deliver a review packet. It still needs scoped credentials, overlap protection, logs, and explicit release boundaries. Hosting changes availability; it does not remove the need for review.

GolemWorkers provides persistent workers with files, browser, terminal, schedules, memory, and messaging. You can create an AI agent for the outer operating loop while keeping Claude Code subagents focused on repository work. For a broader comparison of the layers, see OpenClaw vs Claude Code.

Implementation checklist

  • The role has one repeated job and a visible stop condition.
  • The description says when Claude should delegate to it.
  • The definition uses project scope when teammates should share it.
  • Tool access starts read-only and expands only for a proven need.
  • Settings or hooks enforce sensitive boundaries outside prompt text.
  • The invocation names target, exclusions, output, and mutation policy.
  • Every important finding cites a current path, symbol, or command result.
  • The parent reviews evidence and the real diff before integration.
  • Parallel edits use isolated worktrees or explicit serialization.
  • Regression prompts cover missing inputs, denied reads, tool-output injection, and scope growth.

Bottom line

A Claude Code subagent is most useful as a narrow context boundary. Give it one question, the minimum tools, a precise handoff, and a stopping rule. Let the parent conversation keep the product goal and integration decision. Move to background agents or agent teams only when the work truly needs independent sessions or peer coordination.

That modest pattern scales surprisingly well: a quiet specialist gathers evidence, the parent tests it, and the repository changes only after a person or accountable parent workflow reviews the result.

Primary sources