Sub-agent là gì?
Sub-agent = AI assistant chuyên biệt trong Claude Code, chạy với:
- Context window RIÊNG
- System prompt RIÊNG
- Tool access RIÊNG (giới hạn theo nhu cầu)
Khi gặp task match description, Claude delegate cho sub-agent → sub-agent chạy độc lập → trả về summary.
Vì sao cần?
- Preserve main context — research nặng không làm bẩn conversation chính
- Enforce constraint — sub-agent chỉ có Read/Grep, không có Edit → safe
- Reuse config — share giữa nhiều project qua
~/.claude/agents/ - Specialize behavior — system prompt focused cho domain cụ thể
- Cost control — dùng Haiku cho task đơn giản, Opus cho phức tạp
Cách tạo
File .claude/agents/<name>.md:
---
name: security-reviewer
description: Review code for security vulnerabilities (injection, auth, secrets)
tools: Read, Grep, Glob, Bash
model: opus
---
You are a senior security engineer. Review code for:
- Injection vulnerabilities (SQL, XSS, command injection)
- Authentication and authorization flaws
- Secrets or credentials in code
- Insecure data handling
Provide specific line references and suggested fixes.
Sub-agent kích hoạt khi nào?
- Tự động: Claude đọc description, match đúng → delegate
- Thủ công: nói rõ "use subagent security-reviewer to check auth.ts"
Ví dụ thực tế
> Use a subagent to research how rate limiting is done across our codebase.
Then come back with a 1-paragraph summary.
→ Sub-agent đọc 20 file, dùng 50K token trong context riêng → main agent chỉ nhận 200-word summary.
→ Tiết kiệm context, focus chính giữ sạch.
Khi nào KHÔNG nên dùng?
- Task ngắn (1-2 file) — overhead delegation không bù lại
- Task cần thấy reasoning chi tiết — summary mất nuance
- Task yêu cầu nhiều round-trip user — sub-agent không hỏi lại được
Patterns thường gặp
| Pattern | Sub-agent type |
|---|---|
| Research before coding | codebase-explorer (Read, Grep, Glob) |
| Code review | security-reviewer (Read, Grep) |
| Test gen | test-writer (Read, Write, Bash) |
| Doc gen | doc-generator (Read, Write) |
| Refactor at scale | migration-bot (Read, Edit, Bash) |
Lưu ý
Sub-agent trong cùng session. Nếu muốn nhiều session song song → xem background agents + agent teams (concept khác).
Khác MCP server, hook, skill ở đâu?
| Trigger | Persist data? | Tool subset? | |
|---|---|---|---|
| Sub-agent | Match description | No | Yes |
| Skill | Match description | No | No |
| Hook | Pre/post action | Optional | No |
| MCP server | Tool call | Yes (own process) | Yes |
Nguồn chính thống: code.claude.com/docs/en/sub-agents