architecture

Custom Subagents: Build Your Own

Define specialized subagents with their own tools, prompts, and personalities. Examples for code-review, security audit, and design-blueprint roles.

13 min read·

Most Claude Code users treat every task the same: one model, one context window, one shot. Custom subagents break that pattern. They let you spin up isolated workers with their own model, tools, memory, and personality, then return only the result to your main session. The result: cheaper runs, cleaner context, and purpose-built intelligence for every sub-task.

This breakdown covers what a subagent actually is, how its definition file works, three production-ready examples, when spawning makes sense, and the pitfalls that trip people up the first time.

Subagent vs Agent vs Skill

These three words get mixed up constantly. Here is the precise distinction:

Skill
Injected knowledge

A Markdown file loaded into the current model's context. No separate process. No separate model. Just extra instructions and patterns your main session can read.

Agent
Your main session

The interactive Claude Code process you talk to. It has full tool access, your project context, and carries the whole conversation history.

Subagent
Isolated worker

A separate Claude process spawned by your main agent. Runs in its own context window, uses its own model and tools, then returns only the result. Context stays isolated. No bleed.

Your main session
Sonnet · full context
↓ spawns
security-agent
Haiku · Read+Grep only
perf-agent
Haiku · Read+Grep only
style-agent
Haiku · Read only
↓ returns result only
main session receives: summary (clean, no bloat)

Subagent definition file structure

A subagent is a single Markdown file placed in .claude/agents/. The frontmatter configures the worker; everything below the closing ---is its system prompt.

---
name:        security-reviewer          # ID used when spawning
description: <one-liner about what it does and WHEN to use it>
             # Claude reads this to decide whether to call this agent
model:       claude-haiku-4-5           # cheaper model - 10x less cost
tools:       ["Read", "Grep"]           # read-only - can't break anything
skills:      ["security-guide"]         # preload a skill into this agent
memory:      user                       # persistent memory across sessions
context:     fork                       # isolated context window (recommended)
---

You are a security-focused code reviewer. Your job is to:

1. Check every file for SQL injection, XSS, command injection
2. Flag hardcoded secrets or API keys
3. Review auth logic for privilege escalation risks
4. Rate each issue: critical / high / medium / low

Be brief. List issues only. No compliments.
name

Identifier used when spawning or referencing the agent.

description

Claude reads this to auto-select the right agent. Be specific about when to use it.

model

Any Claude model. Haiku for cheap reads; Sonnet for reasoning; Opus for high-stakes output.

tools

Limit tools to what the task actually needs. Read-only agents can never accidentally write or delete.

skills

Skills to inject before the system prompt. Useful for domain knowledge.

context: fork

Runs in an isolated context window. The only sane default; it prevents context bleed back to main.

3 worked example subagent definitions

Drop these into .claude/agents/ and they are immediately available.

Engineeringcode-reviewer

Pull-request reviewer that checks for logic errors, unclear naming, and missing edge-case handling. Returns a bullet list, nothing more.

---
name: code-reviewer
description: >
  Review changed files for logic errors, naming clarity, and missing edge cases.
  Use when a PR or diff is ready for review before merge.
model: claude-haiku-4-5
tools: ["Read", "Grep", "Glob"]
context: fork
---

You review code diffs. Do not rewrite code. Do not explain what the code does.

For each file, list:
- Logic errors or off-by-one bugs
- Confusing variable or function names
- Missing null/error/edge-case handling
- Anything that would fail silently in production

Format: one bullet per issue. File name as sub-header.
Stop when you've covered every changed file.
Securitysecurity-audit

OWASP-focused auditor. Scans API routes, auth logic, and input handling. Only reads; it can never modify anything.

---
name: security-audit
description: >
  Audit code for OWASP Top 10 vulnerabilities, hardcoded secrets, and broken auth.
  Use when reviewing new API routes, auth changes, or before deploying to production.
model: claude-haiku-4-5
tools: ["Read", "Grep"]
context: fork
---

You are a security auditor. Check for:

1. SQL injection, NoSQL injection, command injection
2. XSS: reflected, stored, DOM-based
3. Broken authentication or missing authorization checks
4. Hardcoded secrets, API keys, or credentials
5. Insecure deserialization or prototype pollution
6. Missing rate limiting on sensitive endpoints

For every finding output:
  Severity: critical | high | medium | low
  File: <path>
  Line: <approximate>
  Issue: <one sentence>
  Fix: <one sentence>

If nothing found, output: PASS
Designdesign-blueprint

Reads existing component files and produces a structured design spec (layout, spacing, color tokens, and component hierarchy) ready for a rebuild or handoff.

---
name: design-blueprint
description: >
  Read existing UI components and produce a structured design spec.
  Use when reverse-engineering a UI, preparing a redesign brief, or doing a design handoff.
model: claude-sonnet-4-6
tools: ["Read", "Glob"]
context: fork
---

You analyse UI code and produce a design blueprint. Do not edit files.

Your output must include:
1. Layout: grid system, breakpoints, container widths
2. Colour tokens: background, foreground, accent, border, muted values
3. Typography: font families, weights, sizes used
4. Component inventory: list every distinct component with its variants
5. Spacing system: base unit and scale observed
6. Interaction notes: hover states, transitions, animations found
7. Inconsistencies: places where the design system breaks

Format as structured Markdown with headers. Be precise, not verbose.

When to spawn vs work directly

Spawning has overhead. Use it when one or more of these conditions apply:

Spawn
  • Task is read-only research or audit; isolate it
  • You want a different model (Haiku for cheap scans)
  • The sub-task would bloat the main context by 5k+ tokens
  • Multiple sub-tasks can run in parallel
  • You need a specialist personality (security mindset, design eye)
Work directly
  • Task needs the full conversation history to proceed
  • You need to write files; main session is safer
  • Sub-task is short (under 10 tool calls)
  • You need iterative back-and-forth with the user mid-task
  • Latency matters more than context cleanliness

Pitfalls

Vague description = agent never gets picked

Claude decides which agent to call by reading the description field. If it says "helps with code" it will almost never trigger. Write it like a routing rule: "Use when reviewing a PR or analysing auth logic before merge."

Forgetting context: fork

Without fork, the subagent shares context with the parent. The whole point of a subagent is isolation. Always set context: fork unless you have a deliberate reason not to.

Giving write tools to audit agents

A security auditor with Write access is a liability. Explicitly restrict tools to ["Read", "Grep"] for any agent that doesn't need to modify files. The agent can't break what it can't touch.

Using Sonnet for everything

Haiku is 10× cheaper than Sonnet and fast enough for search, summarise, classify, and extract. Reserve Sonnet for agents that write code or need multi-step reasoning.

Spawning when you need iteration

Subagents run to completion and return a result. If you need to ask follow-up questions mid-task, stay in the main session. Spawning is fire-and-collect, not a dialogue.

Claude Code subagentscustom agentsTask toolagent definitions

Want this running in your stack?

AY Automate builds agent systems, RAG pipelines, and Claude Code setups for production teams.