지식위키

Claude Code · 확장점: Subagents (위임 에이전트)

Claude Code · 확장점: Subagents (위임 에이전트)

한 줄 요약

Subagent는 “특정 작업만 전담하는 분신 AI”다. 지저분한 작업을 별도 컨텍스트 창에서 처리한 뒤 요약만 본문 대화로 돌려보낸다. 왜 배우나: 테스트 로그·검색 결과·대량 파일처럼 다시 안 볼 정보로 메인 대화가 더러워지는 걸 막아, 긴 작업에서도 본문을 깨끗하게 유지하기 위해서다.


그림

flowchart TD
  A["세션 시작: agents 폴더의 md 파일 스캔 + 머리말 읽기"] --> B[사용 가능한 분신 목록 만들기]
  B --> C{"주 에이전트: 사용자 요청과 description/example 비교"}
  C -->|매칭되거나 이름으로 불림| D[Task 도구로 작업 위임]
  D --> E["격리된 별도 창 생성<br/>본문=지시문, tools/model/권한 적용"]
  E --> F["분신이 혼자 실행: 도구 호출·작업 수행"]
  F --> G["작업 종료: 결과 요약만 반환"]
  G --> H["주 대화가 요약 받음 → 다음 단계 진행"]

쉽게 풀기

비유: 전문 외주 직원에게 일감을 통째로 맡기기.

당신(주 에이전트)이 “이 코드에 숨은 에러 처리 실수가 없는지 검토”하는 일을 만났다고 하자. 직접 하면 수십 개 파일을 다 펼쳐봐야 하고, 그 어수선한 내용이 전부 당신 책상(메인 대화) 위에 쌓여 정작 본 프로젝트에 집중할 공간이 사라진다.

그래서 **전담 외주 직원(subagent)**을 부른다. 직원은 **자기 사무실(별도 컨텍스트 창)**에서 파일을 다 펼쳐 검토한 뒤, 당신에게는 A4 한 장짜리 요약만 들고 온다. 당신 책상은 깨끗하게 유지된다.

flowchart LR
  M["주 에이전트<br/>책상 = 메인 대화"] -->|일감 위임| S["외주 직원<br/>자기 사무실 = 별도 창"]
  S -.->|"수십 개 파일 펼침<br/>어수선한 작업"| S
  S -->|요약 1장만 반환| M

이 직원은 어떻게 만드나? agents/ 폴더에 마크다운 파일 하나(예: code-reviewer.md)를 둔다.

  • 파일 맨 위 YAML 머리말: 직원 신상명세 — 이름(name), 언제 부를지(description), 쓸 도구(tools), 모델 두뇌(model).
  • 그 아래 본문: “너는 누구이고 어떻게 일해라”는 업무 지시문(시스템 프롬프트).

정의해두면 주 에이전트가 description을 보고 부를 타이밍을 알아서 판단하거나, 사용자가 직접 이름을 불러 맡긴다.

안전장치 두 가지.

  • 외주 직원은 또 다른 외주 직원을 부를 수 없다 → 무한 중첩 차단.
  • 직원에게 꼭 필요한 도구만 쥐여줄 수 있다 → “검증 전용 직원”에게 읽기·검색만 주고 쓰기·편집을 빼서 사고 방지.

핵심 정리

Subagent는 YAML 머리말 + 마크다운 본문(=지시문) 형식의 .md 파일이다. 머리말에서 name·description 두 개만 필수, 나머지는 선택이다.

필드필수무엇을 정하나
name소문자·하이픈 고유 ID(파일명과 무관)
description언제 부를지 판단 기준. “use proactively”로 적극 위임 유도
tools아니오허용 도구 목록. 생략 시 주 대화 전 도구 상속
model아니오sonnet·opus·haiku·inherit(기본=주 대화 동일)

[!note]- 펼쳐보기: 전체 선택 필드 목록

  • disallowedTools: 거부 도구. tools와 함께 쓰면 거부가 먼저 적용
  • permissionMode: default·acceptEdits·auto·dontAsk·bypassPermissions·plan (플러그인 subagent에선 무시)
  • maxTurns: 멈추기 전 최대 작업 횟수
  • skills: 시작 시 본문에 통째로 끼워 넣을 Skill(호출화가 아니라 내용 삽입)
  • mcpServers: 전용 MCP 서버 (플러그인 subagent에선 무시)
  • hooks: 이 직원이 사는 동안만 도는 라이프사이클 hooks (플러그인 subagent에선 무시)
  • memory: 지속 메모리 범위 user·project·local (세션 간 학습 누적)
  • background: true면 항상 백그라운드 실행 (기본 false)
  • effort: low·medium·high·xhigh·max
  • isolation: worktree면 임시 git 복사본에서 격리 실행
  • color: UI 표시색(red/blue/green/yellow/purple/orange/pink/cyan)
  • initialPrompt: --agent로 세션 띄울 때 첫 발화로 자동 제출

[!warning] 플러그인 배포 시 보안 제약 플러그인 배포 subagent는 hooks·mcpServers·permissionMode지원하지 않는다. 필요하면 파일을 .claude/agents/~/.claude/agents/로 복사해야 한다.

같은 이름이 여러 곳에 있으면 위에 있을수록 우선순위가 높다.

flowchart TD
  P1["1 관리 설정 .claude/agents — 조직 전체"] --> P2["2 --agents CLI 플래그 — 현재 세션"]
  P2 --> P3["3 프로젝트 .claude/agents"]
  P3 --> P4["4 사용자 ~/.claude/agents"]
  P4 --> P5["5 플러그인 agents 폴더 — 최저"]

[!note]- 펼쳐보기: 폴더 정리·ID 규칙 .claude/agents/~/.claude/agents/는 하위 폴더까지 재귀 스캔되지만, 하위 경로는 ID에 영향 없음(ID=name). 단 플러그인 하위 폴더는 범위명에 포함됨: my-pluginagents/review/security.mdmy-plugin:review:security.


실제 예시

네 가지 정의 방식을 비교한다: ①description에 트리거 예시 삽입, ②tools로 권한 제한, ③CLI JSON, ④직접 만들 템플릿.

[!note]- 펼쳐보기: 예시 1 — 분석형(description 안에 트리거 example 삽입)

// .../plugins/pr-review-toolkit/agents/silent-failure-hunter.md
---
name: silent-failure-hunter
description: Use this agent when reviewing code changes in a pull request to identify silent failures, inadequate error handling, and inappropriate fallback behavior. This agent should be invoked proactively after completing a logical chunk of work that involves error handling, catch blocks, fallback logic, or any code that could potentially suppress errors. Examples:\n\n<example>\nContext: Daisy has just finished implementing a new feature that fetches data from an API with fallback behavior.\nDaisy: "I've added error handling to the API client. Can you review it?"\nAssistant: "Let me use the silent-failure-hunter agent to thoroughly examine the error handling in your changes."\n<Task tool invocation to launch silent-failure-hunter agent>\n</example>\n\n<example>\nContext: Daisy has created a PR with changes that include try-catch blocks.\nDaisy: "Please review PR #1234"\nAssistant: "I'll use the silent-failure-hunter agent to check for any silent failures or inadequate error handling in this PR."\n<Task tool invocation to launch silent-failure-hunter agent>\n</example>
model: inherit
color: yellow
---

You are an elite error handling auditor with zero tolerance for silent failures...
## Core Principles
...

읽는 법: description 안에 <example> 트리거 블록을 직접 끼워 넣었다. 한 example은 상황(Context)→사용자 발화→Assistant 응답→Task 호출로 구성되며, 이게 “지금이 위임 타이밍”임을 학습시키는 신호다.

[!note]- 펼쳐보기: 예시 2 — tools로 권한 제한한 검증 전용

// .../plugins/plugin-dev/agents/plugin-validator.md
---
name: plugin-validator
description: Use this agent when the user asks to "validate my plugin", ...  Examples:

<example>
Context: User explicitly requests validation
user: "Validate my plugin before I publish it"
assistant: "I'll use the plugin-validator agent to perform comprehensive validation."
<commentary>
Explicit validation request triggers the agent.
</commentary>
</example>

model: inherit
color: yellow
tools: ["Read", "Grep", "Glob", "Bash"]
---

You are an expert plugin validator...
**Your Core Responsibilities:**
1. Validate plugin structure and organization
2. Check plugin.json manifest for correctness
...

읽는 법: tools: ["Read","Grep","Glob","Bash"]읽기·검색·Bash만 허용(쓰기·편집 불가 → 검증 전용 안전 에이전트). <commentary>는 “왜 이때 트리거되는지”를 메타로 설명하는 블록.

[!note]- 펼쳐보기: 예시 3 — —agents CLI(JSON), 본문 대신 prompt 키

# CLI 정의 subagent (디스크 미저장, 해당 세션 한정)
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"
  }
}'

JSON은 파일 머리말과 동일 필드를 받되, 지시문은 본문 대신 prompt 키로 준다.

[!note]- 펼쳐보기: 예시 4 — 직접 만들 때 템플릿(code-improver) ~/.claude/agents/code-improver.md(또는 <project>/.claude/agents/)로 저장 → 세션 재시작(또는 /agents로 만들면 즉시 적용).

---
name: code-improver
description: Use this agent when the user asks to improve, refactor, or clean up code... Examples:

<example>
Context: User just finished a function and wants it reviewed for quality.
user: "I wrote this parser, can you make it cleaner?"
assistant: "I'll use the code-improver agent to suggest readability and performance improvements."
<commentary>
User asks for code cleanup — trigger code-improver to analyze and propose diffs.
</commentary>
</example>

model: sonnet
color: blue
tools: ["Read", "Grep", "Glob"]
---

You are an expert software engineer specializing in code quality improvement.

**Your Core Responsibilities:**
1. Analyze recently changed code for readability, performance, best-practice issues
2. Explain each issue with a file:line reference
3. Show current code and provide an improved version

**Analysis Process:**
1. Read files with Read; locate patterns with Grep/Glob
2. Identify concrete issues (naming, complexity, dead code, inefficiency)
3. For each: state severity, show current snippet, show improved snippet
4. Summarize prioritized recommendations

**Quality Standards:**
- Every finding includes a file:line reference
- Suggestions are specific and actionable
- No behavior change unless explicitly justified

**Output Format:**
## Summary / ## Issues (`file.ts:42` — issue — fix) / ## Recommendations

**Edge Cases:**
- No issues: confirm clean and explain why
- Too many: group, show top 10 by impact

만들 때 체크리스트

  • name: 소문자+하이픈, 트리 안 고유 (충돌 시 경고 없이 하나 버려짐)
  • description: “Use this agent when…” 시작 + <example> 2~4개(명시/proactive 둘 다, Task 호출 표시) + 필요시 <commentary>
  • tools: 최소 권한 원칙(읽기 전용이면 Write/Edit 제외). 생략 시 전 도구 상속 주의
  • model: 단순=haiku, 복잡=sonnet/opus, 또는 inherit
  • 본문: 역할 → Core Responsibilities → Process → Quality Standards → Output Format → Edge Cases (권장 ~500–2,000단어, 2인칭 “You are…“)
  • 격리 필요 시 isolation: worktree, 세션 간 학습 필요 시 memory: project
  • 디스크에 직접 추가/편집 후엔 세션 재시작 (또는 /agents로 생성)
  • 플러그인 배포면 hooks/mcpServers/permissionMode 못 씀 → 필요 시 로컬 .claude/agents/

AI 내부에서 일어나는 일

언제 부르나(트리거). ① 자동 위임 — 주 에이전트가 요청을 description/<example>과 대조해 알아서 위임. ② 명시 호출 — 자연어, @-mention(@"code-reviewer (agent)"), 또는 세션 전체용 claude --agent code-reviewer.

어떻게 들어가나. 머리말은 런타임 구성(도구 풀·모델·권한·MCP·hooks)으로 해석되고, 본문은 그 subagent의 시스템 프롬프트가 된다. 중요: subagent는 이 지시문 + 작업 디렉토리 같은 기본 환경만 받고 Claude Code 전체 시스템 프롬프트는 받지 않는다(Explore/Plan 제외 subagent는 CLAUDE.md·git 상태도 로드).

flowchart LR
  F["agents/*.md"] --> FM[YAML 머리말]
  F --> BD[마크다운 본문]
  FM -->|해석| RT["런타임 구성<br/>도구·모델·권한·MCP·hooks"]
  BD -->|해석| SP["시스템 프롬프트<br/>= 업무 지시문"]
  RT --> SUB((격리된 subagent))
  SP --> SUB

왜 컨텍스트를 아끼나. subagent가 자기 창에서 돌기 때문에 대량 출력(테스트 로그·문서 fetch)이 그 창 안에 갇히고 주 대화에는 요약만 돌아온다. 또 subagent는 다른 subagent를 만들 수 없어 무한 중첩이 막힌다.

[!note]- 펼쳐보기: 우선순위 해결 순서(헷갈리기 쉬움)

  • 모델 해결: ① CLAUDE_CODE_SUBAGENT_MODEL 환경변수 → ② 호출별 model 인자 → ③ 머리말 model → ④ 주 대화 모델
  • 도구 해결: disallowedTools 먼저 → 남은 풀에 tools allowlist 적용. (Agent/AskUserQuestion/ExitPlanMode 등은 tools에 적어도 subagent에선 못 씀)
  • Hooks 연동: 주 세션 settings.jsonSubagentStart/SubagentStop(matcher=에이전트 유형명)을, 머리말 hooks는 그 subagent가 사는 동안의 PreToolUse/PostToolUse/Stop(→런타임에 SubagentStop으로 변환)을 건다

요약 & 셀프체크

  • Subagent는 별도 컨텍스트 창을 가진 “전담 외주 직원”이라, 지저분한 작업을 격리 처리하고 본문엔 요약만 돌려준다.
  • name·description만 필수인 .md 파일이며, tools로 권한을 줄이고 model로 두뇌를 고른다.
  • 자동 위임은 description/<example> 매칭으로 일어나고, subagent는 또 다른 subagent를 부를 수 없다.

스스로 답해보기:

  1. 컨텍스트가 더러워지는 작업을 subagent에게 넘기면 무엇이 좋아지나?
  2. 검증만 하는 안전한 subagent를 만들려면 머리말 어떤 필드를 어떻게 설정하나?
  3. 같은 이름이 프로젝트 .claude/agents/~/.claude/agents/ 양쪽에 있으면 어느 쪽이 이기나?

근거 파일

  • /mnt/d/6study/10_프레임워크분석/_원문아카이브/claude-code/sub-agents.md (1차 출처: frontmatter·범위 표·모델/도구 해결·권한 모드·hooks·메모리·--agents JSON)
  • /home/seunghyeong/harness-work/claude-code/plugins/pr-review-toolkit/agents/silent-failure-hunter.md (분석형: description 내 <example>+<Task>)
  • /home/seunghyeong/harness-work/claude-code/plugins/plugin-dev/agents/plugin-validator.md (검증형: tools 제한+<commentary>)
  • /home/seunghyeong/harness-work/claude-code/plugins/plugin-dev/agents/agent-creator.md (메타: 생성 규칙·color 매핑·example 작성법)
  • /home/seunghyeong/harness-work/claude-code/plugins/plugin-dev/skills/agent-development/references/system-prompt-design.md (본문 4대 패턴: 분석/생성/검증/오케스트레이션, 길이 가이드)
  • (참고) /home/seunghyeong/harness-work/claude-code/plugins/code-review/ — agents 없음(commands 전용)

연결

CC_개요 · _분석축_루브릭