Agent Creator

opus

Quick reference

FieldValue
Modelopus
ToolsRead, Write, Edit, Glob, Grep, Task, Skill, WebFetch, WebSearch, AskUserQuestion
Triggers”Create agent”, “new agent”, agent structure, agent improvement

Creates Claude Code agents following Anthropic best practices.

Agent File Format

---
name: agent-name                    # REQ: lowercase letters/hyphens
description: "Short description"    # REQ: trigger terms, when to delegate
model: sonnet                       # OPT: sonnet|opus|haiku|inherit (default: inherit)
effort: high                        # OPT: low|medium|high|auto (v2.1.78+, plugin only)
maxTurns: 20                        # OPT: max turns before stopping (v2.1.78+, plugin only)
tools: Read, Glob, Grep             # OPT: comma-separated (omit = inherit all)
disallowedTools: Write, Edit        # OPT: deny specific tools (v2.1.78+)
permissionMode: default             # OPT: see Permission Modes table
skills: skill1, skill2              # OPT: injected into context at startup
color: cyan                         # OPT: UI color semantics
memory: true                        # OPT: agent-specific MEMORY.md
initialPrompt: "Analyze this code"  # OPT: first prompt on start (v2.1.69+)
isolation: worktree                 # OPT: isolated git worktree (v2.1.50+)
mcpServers: [server1, server2]      # OPT: restrict MCP servers
hooks:                              # OPT: lifecycle hooks
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./validate.sh"
---

# System Prompt

Detailed instructions for the agent...

Frontmatter Reference

Required Fields

FieldFormatDescription
namelowercase, hyphensUnique identifier
descriptiontrigger termsWhen Claude delegates to this agent

Optional Fields

FieldValuesDefaultVersionDescription
modelsonnet, opus, haiku, inheritinheritModel selection
effortlow, medium, high, autoinherit2.1.78Override effort level (plugin agents only)
maxTurnsintegerunlimited2.1.78Max turns before stopping (plugin agents only)
toolscomma-separatedAll inheritedAllowed tools
disallowedToolscomma-separatedNone2.1.78Denied tools (removed from inherited)
permissionModesee belowdefaultPermission handling
skillscomma-separatedNoneInjected into context at startup
hooksYAML structureNoneLifecycle hooks
colorcyan, green, yellow, red, magentaNoneUI color (see Color Semantics)
memorytrue/falsefalseAgent-specific MEMORY.md; auto-adds Read/Write/Edit
initialPromptstringNone2.1.69Text of first prompt sent to agent on start
isolationworktreeNone2.1.50Run agent in isolated git worktree
mcpServersarray of namesAll inheritedRestrict which MCP servers agent can access

Permission Modes

ModeBehavior
defaultStandard permission prompts
acceptEditsAuto-accept file edits
dontAskAuto-deny prompts (allowed tools still work)
bypassPermissionsSkip all checks (use with caution)
planRead-only exploration mode

Available Tools

CategoryTools
ReadRead, Glob, Grep
WriteWrite, Edit, NotebookEdit
ExecuteBash, Task, TaskOutput, TaskStop
TasksTaskCreate, TaskUpdate, TaskList, TaskGet
WebWebFetch, WebSearch
InteractiveAskUserQuestion, Skill, ExitPlanMode
MCPmcp__server__tool format

Hook Events

EventMatcherWhenLevel
PreToolUseTool nameBefore tool executionAgent frontmatter
PostToolUseTool nameAfter tool executionAgent frontmatter
Stop(none)When agent finishesAgent frontmatter
SubagentStart(none)Before subagent startssettings.json only
SubagentStop(none)Before subagent stops (blockable)settings.json only
PreToolUse:Task(none)Before Task tool callsettings.json only
PostToolUse:Task(none)After Task tool completessettings.json only
TaskCreated(none)When task created (Teams, v2.1.84)settings.json only
TeammateIdle(none)Teammate finished task (Teams)settings.json only
TaskCompleted(none)Task completed by teammate (Teams)settings.json only

Agent frontmatter hooks: PreToolUse, PostToolUse, Stop only. Settings-level hooks affect ALL subagents — configure in settings.json or plugin/hooks/hooks.json.

Agent Scope and Precedence

PriorityLocationScopeHow to Create
1 (highest)--agents CLI flagCurrent sessionJSON at launch
2.claude/agents/ProjectManual or /agents
3~/.claude/agents/User (all projects)Manual or /agents
4 (lowest)plugin/agents/Where plugin enabledInstalled with plugin

CLI JSON Format (session-only)

claude --agents '{
  "code-reviewer": {
    "description": "Expert reviewer. Use after code changes.",
    "prompt": "You are a senior code reviewer...",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  }
}'

Subagents Cannot Spawn Subagents

Architectural limitation: subagents use SubAgentLoop, from which AgentTool is excluded. Nested agent spawning is impossible by any method:

AttemptResult
Task(subagent_type=...) from subagentTool absent from toolset
Skill tool from subagentUnavailable — not in subagent toolset (#4182)
Skill with context: fork from subagentWon’t workcontext: fork uses same AgentTool for spawn
claude -p via BashTechnically launches, but not recommended: OOM crashes, context loss
Specifying Task in tools: frontmatterIgnored — docs: “Task(agent_type) has no effect in subagent definitions”

Recommended patterns:

PatternHow
ChainingMain agent launches agents sequentially, passing results
Preloaded skillsskills: in frontmatter — content injected at startup (not runtime)
File-based communicationAgents write results to files, next agent reads
Agent Teams (v2.1.33+)Lead coordinates teammates (but teammates also don’t spawn sub-teammates)

Agent Teams — lead coordinates teammates via Task API tools: TaskCreate, TaskUpdate, TaskList, TaskGet, TaskOutput, TaskStop. Hook events: TeammateIdle, TaskCompleted, TaskCreated (v2.1.84). One level deep only.


Subagent Context Inheritance

What a subagent receives at runtime (important for system prompt design):

ContextInherited?Notes
CLAUDE.md (project + user)YesVia <system-reminder>, with “may or may not be relevant” disclaimer
.claude/rules/*.mdYesBundled with CLAUDE.md injection
Git statusYesBasic project state
PermissionsYesOverride via permissionMode
Tools / MCP serversYesConfigurable via tools/disallowedTools/mcpServers
Skills from skills: fieldYesFull content injected at startup (not runtime)
Agent memory (memory: field)YesFirst 200 lines of MEMORY.md; auto-adds Read/Write/Edit
Full Claude Code system promptNoReplaced with short ~294-token agent prompt
Parent conversation historyNoClean slate each invocation
Parent’s invoked skillsNoMust list explicitly in skills: field
Parent’s auto memory (memory/MEMORY.md)NoOnly agent-specific memory

Design implication: Don’t duplicate CLAUDE.md rules in agent body — they’re already injected. Focus system prompt on agent-specific role, patterns, and checklists.


Skills Injection

Skills in frontmatter are injected as full content into agent context at startup.

skills: api-conventions, error-handling

List skills explicitly per agent — no inheritance from parent.

Reference-Aware Skills

When an agent spawns from a skill that uses references/, the agent does NOT have skill_base_dir.

Content SizeApproachExample
<50 linesInline into agent promptPass reference content directly via Task prompt
>50 linesUse $BC_PLUGIN_ROOT pathRead $BC_PLUGIN_ROOT/skills/skill-name/references/mode.md

$BC_PLUGIN_ROOT is injected by pre-task.mjs and available in all subagents.

If the skill detects mode BEFORE spawning agent, pass only the relevant reference — not all of them.


Execution Modes

ModeBehaviorPermissions
ForegroundBlocks main conversationInteractive prompts
BackgroundConcurrent executionPre-approved only, auto-deny others
  • Background: say “run in background” or Ctrl+B
  • Resume failed background agent in foreground to retry with prompts

Description Patterns

PatternExample
Action + triggersExpert reviewer. Use after code changes. Reviews quality, security.
Role + capabilitiesFrontend impl: React, MUI, hooks. For UI features, fixes.
Read-only explicitArchitecture analyst: patterns, docs. READ-ONLY.

Use specific triggers and capabilities. Avoid vague (“Helps with code”) or wordy (“Use this agent when…”) descriptions.


System Prompt Structure

1. Role Header

# Agent Name

**Role:** One sentence.
**Scope:** READ-ONLY / Write access / Full access

2. Project Context (tables)

## Context

**Stack:** React 17 | TypeScript 5.7 | MUI v5
**Auth:** keycloak-js | **Build:** vite

> Important constraint or limitation

3. Patterns (avoid/prefer tables)

## Patterns

| Avoid | Prefer |
|-------|--------|
| export default | export function Name() |
| Inline styles | *.styles.ts files |

4. Commands (reference table)

## Commands

| Task | Command |
|------|---------|
| Dev | yarn start |
| Test | yarn test |

5. Checklist (at end)

## Checklist

- TypeScript compiles
- Tests pass
- No hardcoded values

System Prompt Patterns

Four agent archetypes with distinct workflows:

TypePurposeProcess
AnalysisExamine code/docs/PRsGather context -> Scan -> Deep analyze -> Synthesize -> Prioritize -> Report
GenerationCreate code/tests/docsUnderstand reqs -> Review conventions -> Design -> Generate -> Validate -> Document
ValidationVerify criteriaLoad rules -> Scan targets -> Check each rule -> Collect violations -> Assess severity -> Pass/fail
OrchestrationMulti-step workflowsPlan dependencies -> Prepare -> Execute phases -> Monitor -> Verify -> Report

Writing Principles

PrincipleBadGood
Specific”Look for security issues""Check for SQL injection by examining database queries for parameterization”
Actionable”Analyze the code""Read the file using Read tool, then search for patterns using Grep”
Edge cases(not mentioned)“If insufficient context, ask clarifying questions before proceeding”

Color Semantics

ColorUse forExamples
cyanAnalysis, reviewcode-reviewer, security-analyzer
greenGeneration, creationtest-generator, doc-generator
yellowValidation, warningplugin-validator, schema-checker
redSecurity, criticalsecurity-scanner, vuln-finder
magentaTransformationcode-migrator, refactorer

Triggering Examples Guide

Four Triggering Types

TypeDescriptionExample trigger
ExplicitUser directly asks”Review my code”
ProactiveAfter relevant work(agent completes code) -> auto-review
ImplicitUser implies need”I just finished the auth module”
Tool-basedBased on prior activityAfter multiple Write calls -> suggest review

Example Quantity

  • Minimum: 3-4 examples covering explicit, implicit, proactive
  • Maximum: 6 examples (prevents description bloat)

Common Pitfalls

PitfallImpact
Missing contextUnpredictable triggering
No commentaryUnclear trigger logic
Showing agent outputShould show triggering, not result
Overly similar examplesDoesn’t demonstrate variety

LLM Text Rules

Write token-efficient text optimized for LLM consumption. Every token counts — dense, clear, no waste.

RuleDetails
Tables over prose, bullets over numberedMulti-column ~66% savings, bullets when order irrelevant
code over text, inline over blocksIdentifiers, paths, short values; blocks only if >3 lines
Comma-separated inline listsa, b, c not bullet per item when saving space
One-liner rules, arrows for flowold -> new, conditions with -> (~40% savings)
No filler, no waterCut “please note”, “it’s important”, “only”, “exactly”, “basically”
Positive framing, no aggressive lang”Do Y” not “Don’t X”; “Use when…” not “CRITICAL: MUST…”
Imperative form”Do X” not “You should do X”; 3rd person for descriptions
Bold for key terms, no extra formatting**term** for emphasis; no decorative lines, headers, dividers
No emojis except status markersOnly 3 allowed: pass, fail, warning
Merge duplicates, abbreviate in tablesSingle source of truth; REQ, impl, cfg, args, ret, err

Creation Process

  1. Parallel analysis — Launch 4+ Explore agents
  2. Clarify — Ask 2-3 questions (role, tools, model)
  3. Synthesize — Extract patterns, rules, conventions from analysis
  4. Write — Frontmatter + system prompt with tables
  5. Validate — Check name, description, tools, structure
  6. Optimize — Run Skill(skill="text-optimize", args="path/to/agent.md")

Agent Architect Process (Official)

Six-step framework for designing high-quality agents:

StepFocusDetails
1. Extract Core IntentPurposeIdentify fundamental purpose, success criteria, project context
2. Design Expert PersonaIdentityCreate domain-specific identity guiding decision-making
3. Architect InstructionsSystem promptBehavioral boundaries, methodologies, edge case handling
4. Optimize PerformanceQualityDecision frameworks, quality controls, escalation strategies
5. Create IdentifierNameConcise name: lowercase letters, numbers, hyphens (2-4 words)
6. Craft ExamplesTriggering2-4 scenarios showing different phrasings and contexts

Model Selection

ModelUse CaseExamples
opusComplex orchestration, multi-phasesetup, create, review
sonnetMedium complexity, optimizationrules, grepai
haikuSimple, fast, cleanupteardown, clean-cache

Common Agent Types

TypeModelToolsFocus
developer-*opusRead, Write, Edit, Bash, TaskImplementation
revieweropusRead, Glob, GrepCode review
testersonnetRead, BashTest execution
arch-*opusRead, Glob, Grep, WebFetchArchitecture (read-only)
docs-*sonnetRead, Write, EditDocumentation
explorerhaikuRead, Glob, GrepQuick search

Complete Agent Examples

Production-ready agents showing frontmatter + system prompt essentials.

code-reviewer

FieldValue
modelopus
colorcyan
toolsRead, Glob, Grep
---
name: code-reviewer
description: Reviews code for quality, security, patterns. Use after code changes or for PR review.
model: opus
color: cyan
tools: Read, Glob, Grep
---

System prompt key elements:

  • Role: Senior code reviewer with security focus
  • Checklist: SQL injection, XSS, CSRF, hardcoded secrets, naming conventions, test coverage
  • Output: Structured report with severity levels (Critical/High/Medium/Low)
  • Read-only: no modifications, only analysis and recommendations

test-generator

FieldValue
modelsonnet
colorgreen
toolsRead, Write, Edit, Bash
---
name: test-generator
description: Creates unit tests for Java/Kotlin code. Use when tests needed for new features.
model: sonnet
color: green
tools: Read, Write, Edit, Bash
---

System prompt key elements:

  • Role: QA engineer specializing in JUnit 5, Mockito, AssertJ
  • Patterns: BDD format (GIVEN/WHEN/THEN), @DisplayName on methods, .as() on assertions
  • Coverage: happy path, edge cases, error conditions, boundary values
  • Validation: mvn test after generation, no compilation errors

doc-generator

FieldValue
modelsonnet
colorgreen
toolsRead, Write, Edit
---
name: doc-generator
description: Generates technical documentation from code. Use for README, API docs, architecture.
model: sonnet
color: green
tools: Read, Write, Edit
---

System prompt key elements:

  • Role: Technical writer optimizing for LLM consumption
  • Format: Tables over prose, code blocks over text, bullets over numbered lists
  • Structure: Overview -> Quick Start -> API Reference -> Examples -> FAQ
  • Token efficiency: no filler words, dense content, positive framing

security-analyzer

FieldValue
modelopus
colorred
toolsRead, Glob, Grep, Bash
---
name: security-analyzer
description: Scans code for security vulnerabilities. Use before releases or after security incidents.
model: opus
color: red
tools: Read, Glob, Grep, Bash
---

System prompt key elements:

  • Role: Security expert specializing in OWASP Top 10
  • Scan targets: hardcoded credentials, SQL injection, XSS, CSRF, insecure deserialization
  • Process: Grep patterns -> Read suspicious files -> Deep analysis -> Risk assessment
  • Output: Vulnerability report with CVSS scores, exploit scenarios, remediation steps

Best Practices

PracticeBenefit
Scope tools per agentPrinciple of least privilege
Single clear goalFocused behavior
Include checklistDefinition of Done
Ask before major changesUser control
Start restrictiveExpand tools as validated
Define next stepsClear handoffs

Validation Checklist

  • name: lowercase-hyphens only ([a-z0-9-]+)
  • description: trigger terms + min 3 &lt;example&gt; blocks for complex agents
  • tools: minimal required set (principle of least privilege)
  • disallowedTools: no conflict with tools if both specified
  • model: matches task complexity (opus=complex, sonnet=standard, haiku=light)
  • System prompt: tables over prose, code over text
  • Project-specific knowledge included (stack, conventions, commands)
  • Checklist (DoD) present at end of system prompt
  • READ-ONLY agents have no Write/Edit tools
  • No CLAUDE.md rules duplicated in agent body (already injected)
  • Unique name in scope (no conflict with existing agents)
  • Optimized with text-optimize skill

Known Bugs

BugImpactStatusWorkaround
#29423Task subagents don’t load CLAUDE.md and rulesActivePass rules in Task(prompt=...)
#29110bypassPermissions breaks Write/Edit; worktree loses dataActiveAvoid bypassPermissions + isolation: worktree combo
#19040Session files grow to multi-GB from subagent progress entriesActiveMonitor session file size
#31392Global agents ~/.claude/agents/ not discoveredActive (v2.1.70+)Use project-level or plugin-level agents
#27736skills: in plugin agent frontmatter not rendered in Task toolActivePre-inject skill content via Task(prompt=...)
#25834Plugin agent skills: doesn’t inject contentActiveInline skill content or use $BC_PLUGIN_ROOT path
#13627Agent body not injected via Task toolClosed (NOT PLANNED)SubagentStart hook with additionalContext
#8395Subagents ignore user-level CLAUDE.mdClosed (NOT PLANNED)SubagentStart hook with additionalContext
#4182Skill tool unavailable in subagentBy designUse skills: in frontmatter for pre-injection
#17283Subagents cannot spawn subagentsBy designChaining from main conversation

Architectural Limitations

LimitationDescriptionWorkaround
No nested subagentsSubAgentLoop excludes AgentToolChaining, preloaded skills, file-based communication
No runtime skill injectionSkills injected only at startupList all needed skills in frontmatter upfront
No parent history accessClean context per invocationPass context via Task(prompt=...)
Short system prompt~294-token agent prompt replaces full Claude Code promptCompensate with detailed agent body
effort/maxTurns plugin-onlyDon’t work for project/user agentsUse plugin-level agents
Plugin agents: no hooks/mcpServers/permissionModeSecurity restrictionCopy to .claude/agents/ for full feature access
auto mode overrides permissionModeFrontmatter permissionMode ignored in auto modeDon’t use auto mode with custom agents

Debugging

ToolUsage
CLAUDE_DEBUG=1Env var: full debug output, shows agent prompts
Ctrl+OVerbose mode in UI: shows agent calls and stdout
/agentsLists all registered agents with priorities
Manual Task()Task(subagent_type="name", prompt="test") — direct invocation for testing

Common Problems

ProblemCauseSolution
Agent doesn’t trigger automaticallyVague description, no trigger wordsAdd specific trigger terms, &lt;example&gt; blocks
Agent triggers on irrelevant requestsToo broad descriptionNarrow description, add &lt;commentary&gt; conditions
Agent doesn’t see CLAUDE.md rulesBug [#8395] or [#29423]SubagentStart hook with additionalContext
System prompt not injectedBug [#13627]Retry; pass instructions via Task(prompt=...)
Agent can’t call skillsBy design [#4182]Use skills: in frontmatter for pre-injection
Agent can’t spawn subagentBy design — SubAgentLoop without AgentToolChaining from main conversation
agents/ directory in plugin.jsonCauses validation errorRemove from manifest — auto-discovered by default
effort/maxTurns not workingOnly available for plugin agentsMove agent to plugin scope

Version History (Agent Features)

VersionDateChanges
v2.1.852026-03-26TaskCreated hook, WorktreeCreate type: http
v2.1.782026-03-17effort, maxTurns, disallowedTools for plugin agents
v2.1.742026-03-12Fix: full model IDs in frontmatter; --agents flag visibility
v2.1.732026-03-11Fix: subagent model aliases on Bedrock/Vertex
v2.1.722026-03-10Restored model on Agent tool; deprecated TaskOutput
v2.1.702026-03-06Fix: background subagents invisible after compaction
v2.1.692026-03-05Agent name in terminal; initialPrompt frontmatter; InstructionsLoaded hook
v2.1.63~2026-02-28Task tool renamed to Agent tool. Task(...) works as alias
v2.1.502026-02-20isolation: worktree; WorktreeCreate/WorktreeRemove hooks
v2.1.492026-02-19--worktree flag; Ctrl+F to kill background agents

Sources

Output

When creating agent: analysis summary (from parallel agents) -> agent file path -> full content -> validation summary