Creating Custom Subagents for Specific Tasks in Claude Code: A Complete Guide
Claude Code lets you split complex workflows into focused, reusable AI assistants called subagents, each running with isolated context, custom system prompts, and restricted tool access to handle specific domains like security review or data analysis.
Creating custom subagents for specific tasks in Claude Code transforms monolithic AI interactions into modular, scalable workflows. According to the luongnv89/claude-howto repository, these specialized assistants live in your project's .claude/agents/ directory and run with clean context windows to prevent pollution of your main conversation while enforcing least-privilege tool access.
How Subagents Are Structured
Every subagent definition is a Markdown file with two distinct sections: YAML front-matter for configuration and a prose system prompt for behavior definition.
Front-Matter Configuration
The YAML block declares the subagent's identity and runtime parameters. As defined in the repository's examples under 04-subagents/, valid fields include name, description, tools, model, memory, background, and maxTurns.
---
name: data-scientist
description: Data analysis assistant. Use PROACTIVELY when a request mentions "SQL", "data", or "analysis".
tools: Bash, Read, Write
model: sonnet
memory: project
maxTurns: 15
---
System Prompt Definition
Immediately following the front-matter, plain Markdown defines the subagent's persona, task scope, and output format. This text loads into a fresh conversation window (approximately 20,000 tokens) every time the subagent spawns, ensuring no carryover from previous sessions unless memory is configured.
Tool Access Control
By default, subagents inherit all available tools. You restrict capabilities by enumerating only required tools in the tools field, reducing attack surface and execution time. For example, a read-only security auditor should declare tools: Read, Grep rather than granting write access.
Persistence and Memory Options
The memory field accepts three values: user (global across all projects), project (scoped to current repository), or local (session-only). This allows subagents to maintain state—such as vulnerability lists or analysis patterns—across Claude Code sessions without cluttering the main agent context.
Subagent Lifecycle and Execution Flow
The execution model follows four distinct phases that enable parallel processing and domain specialization.
Step 1: Delegation Decision — Claude evaluates the description field of all installed subagents against the user request. If a description contains "use PROACTIVELY" and matches keywords, Claude automatically delegates; otherwise, the user must explicitly invoke the agent.
Step 2: Context Initialization — A new context window opens, the system prompt loads, and any declared memory files pre-load into the subagent's environment.
Step 3: Isolated Execution — The subagent operates using only its allowed tools, carrying out the task and returning structured output (markdown tables, JSON blocks, or file diffs).
Step 4: Result Synthesis — The main Claude session ingests the subagent's output and integrates it into the broader workflow, presenting final results to the user.
When to Create a Custom Subagent
- Domain-Specific Expertise — You need specialized knowledge not covered by built-in agents, such as a data-science analyst that executes SQL queries via MCP servers.
- Security Isolation — Tasks require restricted tool access, like a read-only security reviewer that cannot modify files.
- Persistent State — You require cross-session memory, such as maintaining a list of known vulnerabilities or project conventions.
- Workflow Reusability — You plan to reuse the same automation logic across multiple repositories, bundling it as a subagent eliminates copy-paste maintenance.
Creating Your First Custom Subagent
Step 1: Define the Agent Configuration
Create a Markdown file in the 04-subagents/ directory of the luongnv89/claude-howto repository (or your local .claude/agents/). The file data-scientist.md demonstrates a complete configuration:
---
name: data-scientist
description: Data analysis assistant. Use PROACTIVELY when a request mentions "SQL", "data", or "analysis".
tools: Bash, Read, Write
model: sonnet
memory: project
maxTurns: 15
---
You are a data-science expert.
**Task**: Run the requested SQL query against the project's database (configured via the `DATABASE_URL` MCP server).
**Output**:
- A markdown table with the query results.
- A short interpretation of the data trends.
When you cannot run a query, explain why and suggest a fix.
Source: 04-subagents/data-scientist.md in the luongnv89/claude-howto repository.
Step 2: Install in Your Project
Deploy the subagent by copying the definition file to your project's agent directory:
mkdir -p .claude/agents
cp 04-subagents/data-scientist.md .claude/agents/
Run the /agents command in Claude Code to verify the new agent appears in the registry.
Step 3: Invocation Patterns
Explicit Invocation — Directly reference the agent name in your prompt:
Use the data-scientist subagent to find the top 5 customers by revenue last month.
Proactive Invocation — When the description field includes "use PROACTIVELY", Claude automatically spawns the subagent for matching queries without explicit instructions:
Can you show me a sales trend for the past quarter?
Background Execution — For long-running tasks, add background: true to the front-matter. The subagent runs asynchronously, allowing you to continue other work and resume later with Resume agent <id>.
Best Practices for Subagent Design
Name clearly — Use lowercase hyphenated names (e.g., security-auditor) to ensure unique identification and CLI compatibility.
Signal proactive delegation — Include the exact phrase "use PROACTIVELY" in the description field when you want Claude to auto-delegate based on keywords.
Restrict tool scopes — Only grant tools the subagent strictly requires. A documentation generator needs Read and Write, but never Bash or Edit.
Define stable output formats — Require consistent markdown tables or JSON blocks in the system prompt. This makes downstream synthesis easier for the main agent.
Version-control definitions — Store subagent files under .claude/agents/ in your repository to enable team sharing, code review, and audit trails.
Reference Files and Examples
The luongnv89/claude-howto repository provides working implementations demonstrating various subagent patterns:
04-subagents/README.md— Comprehensive architectural overview and installation guide (link)04-subagents/code-reviewer.md— Security, performance, and quality review agent with restricted read-only access (link)04-subagents/test-engineer.md— Test strategy generator with write permissions for creating test files (link)04-subagents/data-scientist.md— SQL-enabled data analysis agent with project-scoped memory (link)
Summary
- Custom subagents in Claude Code are modular AI assistants defined in Markdown files with YAML front-matter and system prompts.
- Store definitions in
.claude/agents/(project-level) or~/.claude/agents/(user-level) for automatic discovery. - Each subagent runs in an isolated ≈20k token context window with configurable
tools,memory, andmodelsettings. - Use "use PROACTIVELY" in the description field to enable automatic delegation without explicit user commands.
- Implement background mode for long-running tasks and memory for cross-session persistence.
- Reference the
04-subagents/directory inluongnv89/claude-howtofor production-ready templates.
Frequently Asked Questions
What is the difference between a subagent and the main Claude session?
A subagent operates in a clean, isolated context window (approximately 20,000 tokens) with its own system prompt and restricted tool set, while the main Claude session maintains the full conversation history. This isolation prevents context pollution and allows the subagent to specialize on a single domain without interference from unrelated parts of the codebase.
Where should I store custom subagent definitions?
Place project-specific subagents in the .claude/agents/ directory at your repository root. For agents you want available across all projects, store them in ~/.claude/agents/ (user-level). Claude Code scans both locations on startup; files must use the .md extension and contain valid YAML front-matter.
How do I make a subagent run automatically for specific tasks?
Include the exact phrase "use PROACTIVELY" in the subagent's description field, followed by trigger keywords (e.g., "Use PROACTIVELY when a request mentions 'security' or 'audit'"). When Claude detects these keywords in a user prompt, it automatically spawns the subagent without requiring explicit invocation.
Can subagents maintain state across multiple Claude Code sessions?
Yes. Set the memory field in the front-matter to user, project, or local. The project scope stores data in the current repository's memory directory, surviving across sessions for that specific codebase. The user scope maintains global state accessible to that subagent in any project, while local limits persistence to the current session only.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →