sub-agent-patterns

jezweb/claude-skills · updated Apr 8, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills add https://github.com/jezweb/claude-skills --skill sub-agent-patterns
0 commentsdiscussion
summary

Delegate specialized tasks to isolated AI assistants with custom tools, models, and system prompts.

  • Sub-agents preserve main context by isolating verbose tool outputs and intermediate reasoning, enabling longer sessions and cleaner conversations
  • Three built-in agents available: Explore (Haiku, read-only codebase search), Plan (Sonnet, plan-mode research), and General-Purpose (Sonnet, full read/write access)
  • Create custom agents in .claude/agents/ with YAML frontmatter and markdown pr
skill.md

Sub-Agents in Claude Code

Status: Production Ready ✅ Last Updated: 2026-02-02 Source: https://code.claude.com/docs/en/sub-agents

Sub-agents are specialized AI assistants that Claude Code can delegate tasks to. Each sub-agent has its own context window, configurable tools, and custom system prompt.


Why Use Sub-Agents: Context Hygiene

The primary value of sub-agents isn't specialization—it's keeping your main context clean.

Without agent (context bloat):

Main context accumulates:
├─ git status output (50 lines)
├─ npm run build output (200 lines)
├─ tsc --noEmit output (100 lines)
├─ wrangler deploy output (100 lines)
├─ curl health check responses
├─ All reasoning about what to do next
└─ Context: 📈 500+ lines consumed

With agent (context hygiene):

Main context:
├─ "Deploy to cloudflare"
├─ [agent summary - 30 lines]
└─ Context: 📊 ~50 lines consumed

Agent context (isolated):
├─ All verbose tool outputs
├─ All intermediate reasoning
└─ Discarded after returning summary

The math: A deploy workflow runs ~10 tool calls. That's 500+ lines in main context vs 30-line summary with an agent. Over a session, this compounds dramatically.

When this matters most:

  • Repeatable workflows (deploy, migrate, audit, review)
  • Verbose tool outputs (build logs, test results, API responses)
  • Multi-step operations where only the final result matters
  • Long sessions where context pressure builds up

Key insight: Use agents for workflows you repeat, not just for specialization. The context savings compound over time.


Built-in Sub-Agents

Claude Code includes three built-in sub-agents available out of the box:

Explore Agent

Fast, lightweight agent optimized for read-only codebase exploration.

Property Value
Model Haiku (fast, low-latency)
Mode Strictly read-only
Tools Glob, Grep, Read, Bash (read-only: ls, git status, git log, git diff, find, cat, head, tail)

Thoroughness levels (specify when invoking):

  • quick - Fast searches, targeted lookups
  • medium - Balanced speed and thoroughness
  • very thorough - Comprehensive analysis across multiple locations

When Claude uses it: Searching/understanding codebase without making changes. Findings don't bloat the main conversation.

User: Where are errors from the client handled?
Claude: [Invokes Explore with "medium" thoroughness]
       → Returns: src/services/process.ts:712

Plan Agent

Specialized for plan mode research and information gathering.

Property Value
Model Sonnet
Mode Read-only research
Tools Read, Glob, Grep, Bash
Invocation Automatic in plan mode

When Claude uses it: In plan mode when researching codebase to create a plan. Prevents infinite nesting (sub-agents cannot spawn sub-agents).

General-Purpose Agent

Capable agent for complex, multi-step tasks requiring both exploration AND action.

Property Value
Model Sonnet
Mode Read AND write
Tools All tools
Purpose Complex research, multi-step operations, code modifications

When Claude uses it:

  • Task requires both exploration and modification
  • Complex reasoning needed to interpret search results
  • Multiple strategies may be needed
  • Task has multiple dependent steps

Creating Custom Sub-Agents

File Locations

Type Location Scope Priority
Project .claude/agents/ Current project only Highest
User ~/.claude/agents/ All projects Lower
CLI --agents '{...}' Current session Middle

When names conflict, project-level takes precedence.

⚠️ CRITICAL: Session Restart Required

Agents are loaded at session startup only. If you create new agent files during a session:

  1. They won't appear in /agents
  2. Claude won't be able to invoke them
  3. Solution: Restart Claude Code session to discover new agents

This is the most common reason custom agents "don't work" - they were created after the session started.

File Format

Markdown files with YAML frontmatter:

---
name: code-reviewer
description: Expert code reviewer. Use proactively after code changes.
tools: Read, Grep, Glob, Bash
model: inherit
permissionMode: default
skills: project-workflow
hooks:
  PostToolUse:
    - matcher: "Edit|Write"
      hooks:
        - type: command
          command: "./scripts/run-linter.sh"
---

Your sub-agent's system prompt goes here.

Include specific instructions, best practices, and constraints.

Configuration Fields

Field Required Description
name Yes Unique identifier (lowercase, hyphens)
description Yes When Claude should use this agent
tools No Comma-separated list. Omit entirely = inherit ALL tools (including MCP)
model No sonnet, opus, haiku, or inherit. Default: sonnet
permissionMode No default, acceptEdits, dontAsk, bypassPermissions, plan, ignore
skills No Comma-separated skills to auto-load (sub-agents don't inherit parent skills)
hooks No PreToolUse, PostToolUse, Stop event handlers

MCP Tool Inheritance (CRITICAL)

To access MCP tools from a sub-agent, you MUST omit the tools field entirely.

When you specify ANY tools in the tools field, it becomes an allowlist. There is no wildcard syntax.

# ❌ WRONG - "*" is interpreted literally as a tool named "*", not a wildcard
tools: Read, Grep, Glob, "*"

# ❌ WRONG - this is an allowlist, agent cannot access MCP tools
tools: Read, Grep, Glob

# ✅ CORRECT - omit tools field entirely to inherit ALL tools including MCP
# tools field omitted
model: sonnet

Key insight: The "*" is NOT valid wildcard syntax. When parsed, it's treated as a literal tool name that doesn't exist.

Agent restart required: Changes to agent config files only take effect after restarting Claude Code session.

Available Tools Reference

Complete list of tools that can be assigned to sub-agents:

Tool Purpose Type
Read Read files (text, images, PDFs, notebooks) Read-only
Write Create or overwrite files Write
Edit Exact string replacements in files Write
MultiEdit Batch edits to single file Write
Glob File pattern matching (**/*.ts) Read-only
Grep Content search with regex (ripgrep) Read-only
LS List directory contents Read-only
Bash Execute shell commands Execute
BashOutput Get output from background shells Execute
KillShell Terminate background shell Execute
Task Spawn sub-agents Orchestration
WebFetch Fetch and analyze web content Web
WebSearch Search the web Web
TodoWrite Create/manage task lists Organization
TodoRead Read current task list Organization
NotebookRead Read Jupyter notebooks Notebook
NotebookEdit Edit Jupyter notebook cells Notebook
AskUserQuestion Interactive user questions UI
EnterPlanMode Enter planning mode Planning
ExitPlanMode Exit planning mode with plan Planning
Skill Execute skills in conversation Skills
LSP Language Server Protocol integration Advanced
MCPSearch MCP tool discovery Advanced

Tool Access Patterns by Agent Type:

Agent Type Recommended Tools Notes
Read-only reviewers Read, Grep, Glob, LS No write capability
File creators Read, Write, Edit, Glob, Grep ⚠️ No Bash - avoids approval spam
Script runners Read, Write, Edit, Glob, Grep, Bash Use when CLI execution needed
Research agents Read, Grep, Glob, WebFetch, WebSearch Read-only external access
Documentation Read, Write, Edit, Glob, Grep, WebFetch No Bash for cleaner workflow
Orchestrators Read, Grep, Glob, Task Minimal tools, delegates to specialists
Full access Omit tools field (inherits all) Use sparingly

⚠️ Tool Access Principle: If an agent doesn't need Bash, don't give it Bash. Each bash command requires approval, causing workflow interruptions. See "Avoiding Bash Approval Spam" below.

Avoiding Bash Approval Spam (CRITICAL)

When sub-agents have Bash in their tools list, they often default to using cat > file << 'EOF' heredocs for file creation instead of the Write tool. Each unique bash command requires user approval, causing:

  • Dozens of approval prompts per agent run
  • Slow, frustrating workflow
  • Hard to review (heredocs are walls of minified content)

Root Causes:

  1. Models default to bash for file ops - Training data bias toward shell commands
  2. Bash in tools list = Bash gets used - Even if Write tool is available
  3. Instructions get buried - A "don't use bash" rule at line 300 of a 450-line prompt gets ignored

Solutions (in order of preference):

  1. Remove Bash from tools list (if not needed):

    # Before - causes approval spam
    tools: Read, Write, Edit, Glob, Grep, Bash
    
    # After - clean file operations
    tools: Read, Write, Edit, Glob, Grep
    

    If the agent only creates files, it doesn't need Bash. The orchestrator can run necessary scripts after.

  2. Put critical instructions FIRST (immediately after frontmatter):

    ---
    name: site-builder
    tools: Read, Write, Edit, Glob, Grep
    model: sonnet
    ---
    
    ## ⛔ CRITICAL: USE WRITE TOOL FOR ALL FILES
    
    **You do NOT have Bash access.** Create ALL files using the **Write tool**.
    
    ---
    
    [rest of prompt...]
    

    Instructions at the top get followed. Instructions buried 300 lines deep get ignored.

  3. Remove contradictory instructions:

    # BAD - contradictory
    Line 75: "Copy images with `cp -r intake/images/* build/images/`"
    Line 300: "NEVER use cp, mkdir, cat, or echo"
    
    # GOOD - consistent
    Only mention the pattern you want used. Remove all bash examples if you want Write tool.
    

When to keep Bash:

  • Agent needs to run external CLIs (wrangler, npm, git)
  • Agent needs to execute scripts
  • Agent needs to check command outputs

Testing: Before vs after removing Bash:

  • Before (with Bash): 11+ heredoc approval prompts, wrong patterns applied
  • After (no Bash): Mostly Write tool usage, correct patterns, minimal prompts

Using /agents Command (Recommended)

/agents

Interactive menu to:

  • View all sub-agents (built-in, user, project)
  • Create new sub-agents with guided setup
  • Edit existing sub-agents and tool access
  • Delete custom sub-agents
  • See which sub-agents are active

CLI Configuration

claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  }
}'

Using Sub-Agents

Automatic Delegation

Claude proactively delegates based on:

  • Task description in your request
  • description field in sub-agent config
  • Current context and available tools

Tip: Include "use PROACTIVELY" or "MUST BE USED" in description for more automatic invocation.

Explicit Invocation

> Use the test-runner subagent to fix failing tests
> Have the code-reviewer subagent look at my recent changes
> Ask the debugger subagent to investigate this error

Resumable Sub-Agents

Sub-agents can be resumed to continue previous conversations:

# Initial invocation
> Use the code-analyzer agent to review the auth module
[Agent completes, returns agentId: "abc123"]

<
how to use sub-agent-patterns

How to use sub-agent-patterns on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your development machine
  • Node.js version 16.0+ with npm package manager (verify with node --version)
  • Active project directory or workspace where you want to add sub-agent-patterns
2

Execute installation command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills add https://github.com/jezweb/claude-skills --skill sub-agent-patterns

The skills CLI fetches sub-agent-patterns from GitHub repository jezweb/claude-skills and configures it for Cursor.

3

Select Cursor when prompted

The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ── always included ────
│ • Amp
│ • Antigravity
│ • Cline
│ • Codex
│ ●Cursor(selected)
│ • Cursor
│ • Windsurf
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/sub-agent-patterns

Reload or restart Cursor to activate sub-agent-patterns. Access the skill through slash commands (e.g., /sub-agent-patterns) or your agent's skill management interface.

Security & Verification Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

User Story & Requirements Generation

Create detailed user stories, acceptance criteria, and feature specs

Example

Generate user stories for 'password reset feature' with acceptance criteria, edge cases, and test scenarios

Reduce spec writing time by 50%, ensure comprehensive coverage

Competitive Analysis

Research competitors, compare features, identify gaps

Example

Analyze 5 competitor products, create feature comparison matrix, suggest differentiation opportunities

Complete competitive research in 2 hours instead of 2 days

Roadmap Prioritization

Evaluate features using frameworks (RICE, ICE, Kano) and create prioritized backlogs

Example

Score 20 feature ideas using RICE framework, generate prioritized roadmap with rationale

Make data-driven prioritization decisions faster

Stakeholder Communication

Draft PRDs, status updates, and stakeholder presentations

Example

Create executive summary of Q3 roadmap, monthly progress report, feature launch announcement

Save 3-5 hours/week on communication overhead

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client
  • Access to product documentation and roadmap tools (Jira, Notion, etc.)
  • Understanding of product management frameworks (RICE, Jobs-to-be-Done, etc.)
  • Stakeholder contact information and communication channels

Time Estimate

30-60 minutes to see productivity improvements

Installation Steps

  1. 1.Install product management skill
  2. 2.Start with user story generation for known feature
  3. 3.Progress to competitive analysis: research 2-3 competitors
  4. 4.Use for roadmap prioritization: apply RICE/ICE scoring
  5. 5.Draft stakeholder communications and refine based on feedback
  6. 6.Build template library for recurring PM tasks
  7. 7.Share effective prompts with product team

Common Pitfalls

  • Not validating competitive research—verify facts before sharing
  • Accepting user stories without involving engineering team
  • Over-relying on frameworks without qualitative judgment
  • Not customizing outputs to company culture and communication style
  • Skipping stakeholder validation of generated requirements

Best Practices

✓ Do

  • +Validate research and competitive analysis with real data
  • +Collaborate with engineering when generating technical requirements
  • +Customize frameworks and templates to your company context
  • +Use skill for first drafts, refine with stakeholder input
  • +Document successful prompt patterns for PM tasks
  • +Combine AI efficiency with human judgment and intuition

✗ Don't

  • Don't publish competitive analysis without fact-checking
  • Don't finalize user stories without engineering review
  • Don't make prioritization decisions solely on AI scoring
  • Don't skip customer validation of generated requirements
  • Don't ignore company-specific context and culture

💡 Pro Tips

  • Provide context: company goals, constraints, customer feedback
  • Ask for alternatives: 'Show 3 ways to prioritize this roadmap'
  • Request stakeholder-specific formatting: 'Executive summary vs. engineering spec'
  • Use skill for 70% generation + 30% customization to company needs

When to Use This

✓ Use When

Use for user story writing, competitive research, roadmap prioritization, stakeholder communication, and PRD drafting. Best for reducing repetitive documentation and research work.

✗ Avoid When

Avoid for strategic product vision (requires deep customer empathy), pricing decisions (needs market and financial expertise), or when face-to-face customer discovery is more valuable than speed.

Learning Path

  1. 1Basic: user stories, feature specs, status updates
  2. 2Intermediate: competitive analysis, prioritization frameworks, PRDs
  3. 3Advanced: product strategy, go-to-market planning, OKR setting
  4. 4Expert: product vision, market positioning, business model innovation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.671 reviews
  • Advait Ghosh· Dec 16, 2024

    sub-agent-patterns is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.

  • Dhruvi Jain· Dec 8, 2024

    sub-agent-patterns reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Zara Perez· Dec 8, 2024

    sub-agent-patterns reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Camila Malhotra· Dec 4, 2024

    sub-agent-patterns fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

  • Oshnikdeep· Nov 27, 2024

    I recommend sub-agent-patterns for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Chinedu Gupta· Nov 27, 2024

    I recommend sub-agent-patterns for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Camila Chawla· Nov 23, 2024

    sub-agent-patterns is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.

  • Zara Ramirez· Nov 11, 2024

    Solid pick for teams standardizing on skills: sub-agent-patterns is focused, and the summary matches what you get after install.

  • Advait Rahman· Nov 7, 2024

    sub-agent-patterns fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

  • Chinedu Rao· Oct 26, 2024

    We added sub-agent-patterns from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

showing 1-10 of 71

1 / 8