Skip to content

Split View: Claude Code 완전 가이드: 서브에이전트, 훅, Agent SDK — 에이전틱 코딩의 모든 것

✨ Learn with Quiz
|

Claude Code 완전 가이드: 서브에이전트, 훅, Agent SDK — 에이전틱 코딩의 모든 것

들어가며: 에이전틱 코딩의 시대

2025년은 AI 코딩 도구의 패러다임이 근본적으로 바뀐 해입니다. 단순한 코드 자동완성(autocomplete)을 넘어, AI가 스스로 코드베이스를 탐색하고, 계획을 수립하며, 파일을 편집하고, 테스트를 실행하는 에이전틱 코딩(Agentic Coding) 시대가 본격적으로 열렸습니다.

Anthropic의 Claude Code는 이 패러다임의 최전선에 있는 도구입니다. 터미널 네이티브 인터페이스로 동작하며, 프로젝트의 전체 컨텍스트를 이해하고, 개발자의 워크플로우에 자연스럽게 통합됩니다. 단순한 챗봇이 아닌, 진정한 의미의 코딩 에이전트입니다.

이 글에서는 Claude Code의 핵심 기능부터 서브에이전트, 훅 시스템, Agent SDK, MCP 서버 연동까지 — 에이전틱 코딩의 모든 것을 다룹니다.

대상 독자: AI 코딩 도구에 관심 있는 개발자, 팀 리더, DevOps 엔지니어. 기본적인 터미널 사용과 Git 지식을 전제합니다.


1. Claude Code란 무엇인가

1.1 핵심 개념

Claude Code는 Anthropic이 만든 터미널 기반 에이전틱 코딩 도구입니다. IDE 플러그인이 아니라 터미널에서 직접 실행되며, 다음 세 가지 핵심 능력을 갖추고 있습니다.

능력설명예시
코드베이스 읽기프로젝트 전체 구조와 파일을 이해의존성 분석, 아키텍처 파악
파일 편집코드 수정, 생성, 삭제 수행버그 수정, 리팩터링, 새 기능 추가
명령어 실행쉘 커맨드를 직접 실행테스트 실행, 빌드, Git 작업

핵심 차별점은 컨텍스트의 깊이입니다. Claude Code는 단일 파일이 아닌 프로젝트 전체를 이해합니다. 디렉토리 구조, 의존성 관계, 코딩 컨벤션, Git 히스토리까지 모두 파악한 상태에서 작업합니다.

1.2 터미널 퍼스트(Terminal-First) 철학

Claude Code가 터미널을 선택한 이유는 명확합니다.

  • 최대 유연성: 어떤 에디터, 어떤 워크플로우와도 결합 가능
  • 자동화 친화적: 스크립트, CI/CD 파이프라인에 통합 가능
  • 낮은 오버헤드: 추가 IDE 설치 불필요, SSH 환경에서도 동작
  • 투명성: 모든 명령어와 파일 변경이 터미널에 표시
# Claude Code 기본 실행
claude

# 특정 프롬프트로 실행
claude "이 프로젝트의 아키텍처를 분석해줘"

# 파이프라인 모드
cat error.log | claude "이 에러의 원인을 분석하고 수정해줘"

1.3 동작 원리

Claude Code의 작업 흐름은 다음과 같습니다.

  1. 컨텍스트 수집: 프로젝트 구조, CLAUDE.md 파일, Git 상태 파악
  2. 계획 수립: 사용자 요청을 분석하여 작업 계획 생성
  3. 도구 사용: 파일 읽기/쓰기, 명령어 실행, 검색 등 도구 활용
  4. 검증: 변경 사항 확인, 테스트 실행
  5. 피드백 루프: 결과에 따라 추가 수정

이 과정에서 사용자는 각 단계를 확인하고 승인할 수 있습니다. 자율성과 통제의 균형이 Claude Code의 설계 철학입니다.


2. Claude Code vs Cursor vs GitHub Copilot 비교

에이전틱 코딩 도구 시장의 세 주요 플레이어를 비교합니다.

2.1 기능 비교표

기능Claude CodeCursorGitHub Copilot
인터페이스터미널 (CLI)IDE (VS Code 포크)IDE 플러그인
코드베이스 이해프로젝트 전체프로젝트 전체파일/탭 단위
파일 편집직접 편집직접 편집제안 기반
명령어 실행가능제한적불가
에이전트 모드네이티브Composer AgentAgent 모드 (프리뷰)
서브에이전트병렬 서브에이전트미지원미지원
훅 시스템내장 훅미지원미지원
커스텀 에이전트Agent SDK미지원Extensions
MCP 지원네이티브지원제한적
자동화/CI 통합우수제한적GitHub Actions
멀티 레포워크트리 지원제한적미지원
가격API 사용량 기반월 20달러 / 40달러월 10달러 / 19달러

2.2 언제 어떤 도구를 선택할까

Claude Code가 적합한 경우:

  • 대규모 코드베이스에서 복잡한 리팩터링이 필요할 때
  • CI/CD 파이프라인에 AI를 통합하고 싶을 때
  • 여러 파일에 걸친 변경이 빈번할 때
  • 커스텀 에이전트를 만들어 팀 워크플로우를 자동화하고 싶을 때

Cursor가 적합한 경우:

  • 비주얼 IDE 환경을 선호할 때
  • 코드 작성 중 실시간 제안이 중요할 때
  • VS Code 생태계에 익숙할 때

GitHub Copilot이 적합한 경우:

  • 기존 IDE에서 가볍게 시작하고 싶을 때
  • 인라인 자동완성이 주요 용도일 때
  • GitHub 생태계와 긴밀한 통합이 필요할 때

3. 설치와 초기 설정

3.1 설치

Claude Code 설치는 npm을 통해 간단합니다.

# Node.js 18 이상 필요
npm install -g @anthropic-ai/claude-code

# 또는 특정 디렉토리에서 npx로 실행
npx @anthropic-ai/claude-code

설치 후 인증을 진행합니다.

# 처음 실행 시 인증 프로세스 시작
claude

# Anthropic 계정 또는 API 키로 인증
# 브라우저가 열리며 인증 완료

3.2 VS Code 확장 연동

Claude Code는 터미널 도구이지만 VS Code 확장도 제공합니다.

# VS Code 확장 설치
code --install-extension anthropic.claude-code

VS Code 확장의 장점:

  • 에디터 내에서 Claude Code 패널 사용
  • diff 뷰로 파일 변경 확인
  • 인라인 코멘트로 특정 코드에 대해 질문

3.3 기본 설정

# 설정 확인
claude config list

# 모델 설정 (기본: claude-sonnet-4-20250514)
claude config set model claude-sonnet-4-20250514

# 권한 설정
claude config set permissions.allow-edit true
claude config set permissions.allow-exec true

# 자동 승인 패턴 설정
claude config set permissions.auto-approve-commands "npm test,npm run lint"

3.4 터미널 환경 팁

# tmux 세션에서 Claude Code 실행 (장시간 작업에 유용)
tmux new-session -s claude
claude

# 작업 기록 저장
claude --output-dir ./claude-logs

# 비대화형 모드 (스크립트에서 사용)
claude -p "README.md를 업데이트해줘" --yes

4. CLAUDE.md 마스터하기

4.1 CLAUDE.md란

CLAUDE.md는 프로젝트의 컨텍스트, 컨벤션, 지시사항을 Claude Code에 전달하는 마크다운 파일입니다. Claude Code가 프로젝트를 시작할 때 자동으로 읽어들이며, AI가 프로젝트의 "규칙"을 이해하는 핵심 메커니즘입니다.

4.2 CLAUDE.md 계층 구조

CLAUDE.md는 여러 위치에 존재할 수 있으며, 계층적으로 적용됩니다.

위치범위용도
~/.claude/CLAUDE.md전역모든 프로젝트에 적용되는 공통 규칙
프로젝트 루트 CLAUDE.md프로젝트 전체프로젝트 아키텍처, 기술 스택, 규칙
하위 디렉토리 CLAUDE.md해당 디렉토리모듈별 특수 규칙
.claude/CLAUDE.md개인개인 설정 (Git에 포함되지 않음)

4.3 효과적인 CLAUDE.md 작성법

# 프로젝트 개요

이 프로젝트는 Next.js 14 기반의 블로그 플랫폼입니다.
TypeScript를 사용하며, Tailwind CSS로 스타일링합니다.

# 기술 스택

- Framework: Next.js 14 (App Router)
- Language: TypeScript (strict mode)
- Styling: Tailwind CSS
- Database: PostgreSQL + Prisma ORM
- Testing: Jest + React Testing Library

# 코딩 컨벤션

- 컴포넌트: 함수형 컴포넌트 + 화살표 함수 사용
- 네이밍: camelCase (변수/함수), PascalCase (컴포넌트/타입)
- import 순서: 외부 라이브러리 > 내부 모듈 > 상대 경로
- 에러 핸들링: try-catch 대신 Result 타입 패턴 사용

# 테스트 규칙

- 모든 새로운 함수에 단위 테스트 필수
- 테스트 명령: npm test
- 린트 명령: npm run lint
- PR 전 반드시 npm run build 성공 확인

# 금지 패턴

- any 타입 사용 금지
- console.log 사용 금지 (logger 사용)
- 하드코딩된 문자열 금지 (상수 파일 사용)

# 디렉토리 구조

src/
app/ - Next.js App Router 페이지
components/ - 재사용 가능한 컴포넌트
lib/ - 유틸리티, 헬퍼 함수
types/ - TypeScript 타입 정의
hooks/ - 커스텀 React 훅

4.4 CLAUDE.md 고급 패턴

조건부 지시사항:

# 파일별 규칙

- /src/api/ 아래 파일 수정 시: 반드시 API 문서도 함께 업데이트
- /src/components/ 아래 파일 수정 시: Storybook 스토리도 업데이트
- 데이터베이스 스키마 변경 시: 마이그레이션 파일 자동 생성

워크플로우 지시사항:

# 작업 순서

1. 먼저 관련 코드를 탐색하고 이해
2. 구현 계획을 설명
3. 변경 사항 구현
4. 테스트 실행 및 확인
5. 관련 문서 업데이트

4.5 CLAUDE.md 관리 명령어

# CLAUDE.md 내용을 대화 중에 추가
claude /add-memory "API 응답은 항상 snake_case를 사용합니다"

# 현재 적용된 메모리 확인
claude /memory

# 프로젝트 초기화 시 CLAUDE.md 자동 생성
claude /init

5. 핵심 워크플로우

5.1 탐색 - 계획 - 구현 - 검증 사이클

Claude Code의 기본 작업 사이클은 4단계입니다.

1단계: 탐색 (Explore)

> 이 프로젝트의 인증 시스템 구조를 분석해줘

Claude Code가 수행하는 작업:
- 프로젝트 디렉토리 구조 스캔
- auth 관련 파일 검색 (grep, glob)
- 의존성 분석 (package.json, import 추적)
- 설정 파일 확인

2단계: 계획 (Plan)

> JWT 토큰 갱신 로직에 리프레시 토큰 로테이션을 추가하고 싶어

Claude Code가 수행하는 작업:
- 현재 토큰 갱신 로직 분석
- 변경이 필요한 파일 목록 제시
- 구현 계획 설명
- 예상 영향 범위 분석

3단계: 구현 (Implement)

사용자가 계획을 승인하면 Claude Code가 코드를 직접 수정합니다. 각 파일 변경 전에 diff를 보여주고 승인을 요청합니다.

4단계: 검증 (Verify)

> 변경 사항을 테스트하고 확인해줘

Claude Code가 수행하는 작업:
- npm test 실행
- 린트 체크
- 타입 체크
- 빌드 확인

5.2 실전 시나리오: 버그 수정

# 에러 로그를 파이프로 전달
cat error.log | claude "이 에러를 분석하고 수정해줘"

# Claude Code의 작업 흐름:
# 1. 에러 메시지 분석
# 2. 관련 소스 코드 검색
# 3. 원인 파악
# 4. 수정 코드 작성
# 5. 테스트 실행으로 수정 확인

5.3 실전 시나리오: 새 기능 추가

> 사용자 프로필 페이지에 활동 히스토리 타임라인을 추가해줘.
> 최근 30일간의 활동을 시간순으로 보여주고,
> 무한 스크롤로 이전 활동을 로드할 수 있게 해줘.

Claude Code의 작업:
1. 기존 프로필 페이지 코드 분석
2. 활동 데이터 API 엔드포인트 확인/생성
3. 타임라인 컴포넌트 구현
4. 무한 스크롤 로직 구현
5. 스타일링
6. 테스트 작성 및 실행

5.4 Git 워크플로우 통합

# 현재 변경사항으로 커밋 생성
claude commit

# PR 생성
claude "현재 브랜치의 변경사항으로 PR을 만들어줘"

# 코드 리뷰
claude "PR #42의 변경사항을 리뷰해줘"

# merge conflict 해결
claude "현재 merge conflict를 해결해줘"

6. 서브에이전트 딥다이브

6.1 서브에이전트란

서브에이전트는 Claude Code의 가장 강력한 기능 중 하나입니다. 메인 에이전트가 복잡한 작업을 여러 개의 독립적인 하위 작업으로 분할하고, 이를 병렬로 실행합니다.

메인 에이전트 (오케스트레이터)
├── 서브에이전트 1: API 엔드포인트 구현
├── 서브에이전트 2: 프론트엔드 컴포넌트 작성
├── 서브에이전트 3: 데이터베이스 마이그레이션
└── 서브에이전트 4: 테스트 코드 작성

6.2 서브에이전트의 작동 방식

서브에이전트는 다음과 같은 특성을 가집니다.

특성설명
독립 컨텍스트각 서브에이전트는 자체 컨텍스트 윈도우를 가짐
병렬 실행여러 서브에이전트가 동시에 작업 수행
결과 통합메인 에이전트가 서브에이전트 결과를 종합
실패 격리하나의 서브에이전트 실패가 다른 작업에 영향 없음
읽기 전용 옵션분석/탐색용 서브에이전트는 읽기 전용으로 실행 가능

6.3 서브에이전트 활용 패턴

패턴 1: 대규모 리팩터링

> 프로젝트 전체에서 클래스 컴포넌트를 함수형 컴포넌트로 변환해줘

메인 에이전트의 작업:
1. 클래스 컴포넌트를 사용하는 모든 파일 검색
2. 파일을 그룹으로 분할
3. 각 그룹을 서브에이전트에 할당
4. 서브에이전트들이 병렬로 변환 수행
5. 결과 통합 및 테스트

패턴 2: 멀티 파일 분석

> 이 프로젝트의 보안 취약점을 분석해줘

서브에이전트 1: 인증/인가 코드 분석
서브에이전트 2: SQL 인젝션 가능성 검사
서브에이전트 3: XSS 취약점 검사
서브에이전트 4: 의존성 보안 감사

패턴 3: 코드 생성 + 테스트

> 사용자 관리 CRUD API를 만들어줘

서브에이전트 1: API 라우트 및 컨트롤러 생성
서브에이전트 2: 데이터 모델 및 마이그레이션 생성
서브에이전트 3: 통합 테스트 작성
서브에이전트 4: API 문서 생성

6.4 백그라운드 에이전트

Claude Code는 백그라운드에서 작업을 계속 수행할 수 있습니다.

# 백그라운드 에이전트 시작
claude --background "테스트 커버리지를 80% 이상으로 올려줘"

# 백그라운드 에이전트 상태 확인
claude --list-backgrounds

# 결과 확인
claude --resume <session-id>

백그라운드 에이전트의 활용 사례:

  • 장시간 걸리는 리팩터링 작업
  • 대규모 코드 마이그레이션
  • 테스트 커버리지 향상
  • 문서화 작업

6.5 워크트리(Worktree)를 활용한 병렬 작업

Git 워크트리와 결합하면 더욱 강력한 병렬 작업이 가능합니다.

# 워크트리 생성 후 독립적인 작업 수행
claude "워크트리를 만들어서 feature-auth 브랜치에서 인증 모듈을 리팩터링해줘"

# 메인 브랜치에서는 다른 작업 계속
claude "버그 수정을 계속 진행해줘"

워크트리의 장점:

  • 격리된 작업 환경: 메인 코드에 영향 없이 실험 가능
  • 병렬 개발: 여러 기능을 동시에 개발
  • 안전한 실험: 실패해도 워크트리만 삭제하면 됨

7. 훅(Hooks) 시스템

7.1 훅이란

훅은 Claude Code의 특정 이벤트에 반응하여 자동으로 실행되는 커스텀 액션입니다. 개발 워크플로우를 자동화하는 핵심 메커니즘입니다.

7.2 훅의 종류

훅 이벤트트리거 시점활용 예시
PreToolUse도구 실행 전위험한 명령어 차단, 파일 백업
PostToolUse도구 실행 후자동 포매팅, 린트 실행
Notification알림 발생 시슬랙 알림, 이메일 전송
Stop에이전트 종료 시최종 검증, 리포트 생성

7.3 훅 설정 방법

훅은 .claude/settings.json 파일에서 설정합니다.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit",
        "command": "cp \"$CLAUDE_FILE_PATH\" \"$CLAUDE_FILE_PATH.bak\" 2>/dev/null || true"
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit",
        "command": "npx prettier --write \"$CLAUDE_FILE_PATH\""
      },
      {
        "matcher": "Write",
        "command": "npx eslint --fix \"$CLAUDE_FILE_PATH\""
      }
    ],
    "Notification": [
      {
        "matcher": "",
        "command": "terminal-notifier -message \"$CLAUDE_NOTIFICATION\" -title \"Claude Code\""
      }
    ],
    "Stop": [
      {
        "matcher": "",
        "command": "npm test 2>&1 | tail -20"
      }
    ]
  }
}

7.4 실전 훅 레시피

레시피 1: 자동 테스트 실행

파일이 수정될 때마다 관련 테스트를 자동으로 실행합니다.

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit",
        "command": "if [[ \"$CLAUDE_FILE_PATH\" == *.ts ]]; then npx jest --findRelatedTests \"$CLAUDE_FILE_PATH\" --passWithNoTests; fi"
      }
    ]
  }
}

레시피 2: 자동 포매팅 파이프라인

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "command": "npx prettier --write \"$CLAUDE_FILE_PATH\" && npx eslint --fix \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
      }
    ]
  }
}

레시피 3: 보안 가드레일

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "command": "if echo \"$CLAUDE_COMMAND\" | grep -qE 'rm -rf|DROP TABLE|DELETE FROM'; then echo 'BLOCKED: 위험한 명령어가 감지되었습니다' && exit 1; fi"
      }
    ]
  }
}

레시피 4: 변경 로깅

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "command": "echo \"$(date): $CLAUDE_FILE_PATH modified\" >> .claude/change.log"
      }
    ]
  }
}

7.5 훅 디버깅

# 훅 실행 로그 확인
claude --verbose

# 특정 훅 비활성화
claude config set hooks.PostToolUse.enabled false

# 훅 건너뛰기 (일시적)
claude --no-hooks

8. Agent SDK

8.1 Agent SDK 개요

Agent SDK는 Claude Code의 핵심 기능을 프로그래밍 방식으로 사용할 수 있게 해주는 개발 키트입니다. 이를 통해 커스텀 AI 에이전트를 구축할 수 있습니다.

import { AgentSDK } from '@anthropic-ai/claude-code-sdk'

const agent = new AgentSDK({
  model: 'claude-sonnet-4-20250514',
  permissions: {
    fileRead: true,
    fileWrite: true,
    commandExec: ['npm test', 'npm run lint'],
  },
})

8.2 Agent SDK 핵심 개념

개념설명
세션(Session)에이전트와의 대화 컨텍스트
도구(Tools)에이전트가 사용할 수 있는 기능
권한(Permissions)에이전트의 작업 범위 제한
이벤트(Events)에이전트 작업 중 발생하는 이벤트

8.3 커스텀 에이전트 구축 예제

예제 1: 코드 리뷰 에이전트

import { AgentSDK } from '@anthropic-ai/claude-code-sdk'

async function createCodeReviewAgent() {
  const agent = new AgentSDK({
    model: 'claude-sonnet-4-20250514',
    systemPrompt: `당신은 시니어 코드 리뷰어입니다.
    다음 관점에서 코드를 검토합니다:
    1. 보안 취약점
    2. 성능 이슈
    3. 코딩 컨벤션 준수
    4. 테스트 커버리지`,
    permissions: {
      fileRead: true,
      fileWrite: false,
      commandExec: ['git diff'],
    },
  })

  const session = await agent.createSession()
  const result = await session.send('현재 PR의 변경사항을 리뷰해주세요')

  console.log(result.response)
  console.log('발견된 이슈:', result.issues)
}

예제 2: 자동 문서화 에이전트

async function createDocAgent() {
  const agent = new AgentSDK({
    model: 'claude-sonnet-4-20250514',
    systemPrompt: `함수와 모듈의 JSDoc/TSDoc 문서를 자동으로 생성합니다.
    기존 문서가 있으면 업데이트하고, 없으면 새로 생성합니다.`,
    permissions: {
      fileRead: true,
      fileWrite: true,
      commandExec: ['npm run build'],
    },
  })

  const session = await agent.createSession()
  await session.send('src/lib/ 디렉토리의 모든 export 함수에 문서를 추가해주세요')
}

예제 3: 데이터베이스 마이그레이션 에이전트

async function createMigrationAgent() {
  const agent = new AgentSDK({
    model: 'claude-sonnet-4-20250514',
    systemPrompt: `Prisma 마이그레이션을 관리하는 전문 에이전트입니다.
    스키마 변경을 분석하고, 안전한 마이그레이션을 생성합니다.`,
    permissions: {
      fileRead: true,
      fileWrite: true,
      commandExec: ['npx prisma migrate dev', 'npx prisma generate', 'npx prisma db push'],
    },
  })

  const session = await agent.createSession()
  await session.send('User 모델에 profileImage 필드를 추가하는 마이그레이션을 만들어주세요')
}

8.4 Agent SDK 이벤트 처리

const session = await agent.createSession()

session.on('toolUse', (event) => {
  console.log(`도구 사용: ${event.tool} - ${event.description}`)
})

session.on('fileChange', (event) => {
  console.log(`파일 변경: ${event.path} - ${event.type}`)
})

session.on('commandExec', (event) => {
  console.log(`명령어 실행: ${event.command}`)
  console.log(`결과: ${event.output}`)
})

session.on('error', (event) => {
  console.error(`에러 발생: ${event.message}`)
})

8.5 Agent SDK 권한 모델

보안은 Agent SDK의 핵심 설계 원칙입니다.

const agent = new AgentSDK({
  permissions: {
    // 파일 접근 제어
    fileRead: true,
    fileWrite: true,
    fileGlob: ['src/**/*.ts', 'tests/**/*.ts'], // 허용 패턴
    fileExclude: ['*.env', 'secrets/**'], // 차단 패턴

    // 명령어 실행 제어
    commandExec: ['npm test', 'npm run lint', 'npx prisma migrate dev'],

    // 네트워크 접근 제어
    networkAccess: false,

    // MCP 서버 접근
    mcpServers: ['filesystem', 'database'],
  },
})

9. MCP 서버 연동

9.1 MCP(Model Context Protocol)란

MCP는 AI 모델이 외부 도구와 데이터 소스에 접근할 수 있게 해주는 표준 프로토콜입니다. Claude Code는 MCP를 네이티브로 지원하여, 다양한 외부 시스템과 연동할 수 있습니다.

Claude Code <--MCP--> 데이터베이스 서버
Claude Code <--MCP--> GitHub API
Claude Code <--MCP--> Slack API
Claude Code <--MCP--> 파일 시스템
Claude Code <--MCP--> 커스텀 API

9.2 MCP 서버 설정

프로젝트 레벨에서 .claude/settings.json에 MCP 서버를 등록합니다.

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/project"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "ghp_xxxxxxxxxxxx"
      }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "postgresql://user:pass@localhost:5432/mydb"
      }
    },
    "slack": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-slack"],
      "env": {
        "SLACK_TOKEN": "xoxb-xxxxxxxxxxxx"
      }
    }
  }
}

9.3 인기 MCP 서버 목록

MCP 서버용도제공 기능
filesystem파일 시스템파일 읽기/쓰기, 디렉토리 탐색
githubGitHub 연동PR, Issue, 코드 검색, 리뷰
postgresPostgreSQL쿼리 실행, 스키마 조회
sqliteSQLite로컬 DB 작업
slackSlack 연동메시지 전송, 채널 조회
puppeteer웹 브라우저웹 스크래핑, E2E 테스트
memory영구 메모리세션 간 데이터 유지
brave-search웹 검색실시간 웹 검색
sentry에러 추적에러 로그 조회, 분석
linear프로젝트 관리이슈 추적, 스프린트 관리

9.4 커스텀 MCP 서버 만들기

자체 API나 내부 시스템을 연동하기 위해 커스텀 MCP 서버를 만들 수 있습니다.

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'

const server = new McpServer({
  name: 'my-internal-api',
  version: '1.0.0',
})

// 도구 정의
server.tool(
  'getDeployStatus',
  'Get deployment status',
  {
    environment: { type: 'string', enum: ['staging', 'production'] },
  },
  async (params) => {
    const status = await fetchDeployStatus(params.environment)
    return {
      content: [
        {
          type: 'text',
          text: JSON.stringify(status, null, 2),
        },
      ],
    }
  }
)

server.tool(
  'triggerDeploy',
  'Trigger a deployment',
  {
    environment: { type: 'string' },
    version: { type: 'string' },
  },
  async (params) => {
    const result = await triggerDeploy(params.environment, params.version)
    return {
      content: [
        {
          type: 'text',
          text: `Deployment triggered: ${result.id}`,
        },
      ],
    }
  }
)

// 서버 시작
const transport = new StdioServerTransport()
await server.connect(transport)

9.5 MCP 서버 활용 시나리오

시나리오 1: 데이터베이스 연동 개발

> users 테이블의 스키마를 확인하고, 새로운 API 엔드포인트를 만들어줘

Claude Code의 작업:
1. MCP postgres 서버로 스키마 조회
2. 기존 API 패턴 분석
3. 새 엔드포인트 코드 생성
4. 마이그레이션 파일 생성
5. 테스트 작성

시나리오 2: GitHub 연동 워크플로우

> 최근 열린 이슈 중 bug 라벨이 있는 것을 확인하고,
> 가장 우선순위가 높은 것을 수정해줘

Claude Code의 작업:
1. MCP github 서버로 이슈 목록 조회
2. 우선순위 분석
3. 관련 코드 탐색 및 수정
4. PR 생성

10. 고급 패턴

10.1 멀티 레포 작업

여러 리포지토리에 걸친 작업을 수행할 수 있습니다.

# 모노레포 환경에서
claude "packages/shared 라이브러리의 변경이 packages/web과 packages/api에
미치는 영향을 분석하고, 필요한 업데이트를 모두 수행해줘"

10.2 Git 워크트리 활용

# 여러 기능을 동시에 개발
claude "워크트리를 만들어서 다음 작업들을 병렬로 수행해줘:
1. feature/auth - 인증 모듈 리팩터링
2. feature/dashboard - 대시보드 성능 최적화
3. fix/memory-leak - 메모리 누수 수정"

10.3 예약 작업(Scheduled Tasks)

Claude Code로 반복적인 작업을 스케줄링할 수 있습니다.

# 매일 아침 코드 품질 리포트 생성
claude schedule --cron "0 9 * * *" "코드 품질 리포트를 생성하고 Slack에 공유해줘"

# 매주 월요일 의존성 업데이트 확인
claude schedule --cron "0 10 * * 1" "npm outdated를 확인하고 안전한 업데이트를 적용해줘"

10.4 헤드리스 모드와 CI/CD 통합

# GitHub Actions 예시
name: Claude Code Review
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run Claude Code Review
        run: |
          npx @anthropic-ai/claude-code -p \
            "이 PR의 변경사항을 리뷰하고 코멘트를 남겨줘" \
            --yes --output-format json
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

10.5 컨텍스트 윈도우 최적화

대규모 프로젝트에서 컨텍스트를 효율적으로 사용하는 전략입니다.

  1. CLAUDE.md로 프로젝트 컨텍스트 사전 제공: 매번 탐색할 필요 없이 핵심 정보를 미리 제공
  2. 서브에이전트로 컨텍스트 분산: 큰 작업을 작은 독립 작업으로 분할
  3. /compact 명령으로 대화 압축: 긴 대화에서 핵심만 유지
  4. 파일 필터링: 불필요한 파일을 .claudeignore로 제외
# .claudeignore 예시
node_modules/
dist/
.next/
coverage/
*.lock
*.log

11. 실제 사례와 생산성 데이터

11.1 Anthropic 내부 사용 데이터

Anthropic 내부 개발팀이 공유한 Claude Code 사용 데이터입니다.

지표수치
코드 작성 시간 단축약 40-60%
코드 리뷰 시간 단축약 30-50%
버그 수정 평균 시간기존 대비 50% 감소
테스트 커버리지 향상평균 15-20% 증가
일일 커밋 수평균 2-3배 증가

11.2 사례 1: 대규모 마이그레이션

상황: React 클래스 컴포넌트 200개를 함수형 컴포넌트로 마이그레이션

  • 수동 작업 예상: 2-3주 (1명 기준)
  • Claude Code 활용: 2일 (서브에이전트 병렬 처리)
  • 전환 성공률: 95% (나머지 5%는 수동 검토)

11.3 사례 2: API 통합 개발

상황: 외부 결제 API 통합 (Stripe)

  • Claude Code가 수행한 작업:
    • API 문서 분석 (MCP brave-search 활용)
    • 인터페이스 타입 정의
    • 서비스 레이어 구현
    • 웹훅 핸들러 구현
    • 에러 핸들링
    • 단위/통합 테스트 80% 작성
  • 소요 시간: 4시간 (수동 대비 2-3일)

11.4 사례 3: 레거시 코드 현대화

상황: jQuery + PHP 앱을 Next.js + TypeScript로 현대화

  • CLAUDE.md에 마이그레이션 규칙 정의
  • 서브에이전트로 컴포넌트별 병렬 변환
  • 훅으로 자동 타입 체크 및 테스트
  • 총 6주 프로젝트를 2주로 단축

11.5 생산성 극대화 팁

  1. CLAUDE.md를 상세하게 작성하세요: 투자 대비 효과가 가장 큰 부분
  2. 작은 작업부터 시작하세요: 버그 수정, 테스트 추가 등으로 신뢰를 쌓은 후 큰 작업으로
  3. 훅을 적극 활용하세요: 반복적인 검증 작업을 자동화
  4. 서브에이전트를 활용하세요: 큰 작업은 분할하여 병렬 처리
  5. 결과를 항상 검증하세요: AI 출력을 맹신하지 말고 리뷰하는 습관

12. 팁과 트릭

12.1 키보드 단축키

단축키기능
Ctrl+C현재 작업 중단
Ctrl+D세션 종료
Esc현재 입력 취소
Tab자동 완성
Up/Down이전 명령어 탐색

12.2 슬래시 명령어

/help          # 도움말
/clear         # 대화 초기화
/compact       # 대화 내용 압축
/memory        # 메모리(CLAUDE.md) 확인
/add-memory    # 메모리에 규칙 추가
/model         # 모델 변경
/cost          # 현재 세션 비용 확인
/diff          # 현재 변경사항 확인
/undo          # 마지막 변경 되돌리기
/review        # 코드 리뷰 요청
/init          # 프로젝트 초기화
/bug           # 버그 리포트
/config        # 설정 변경

12.3 메모리 시스템 활용

Claude Code의 메모리 시스템은 세션 간에 학습한 내용을 유지합니다.

# 대화 중 메모리 추가
/add-memory "이 프로젝트에서 API 응답은 항상 camelCase를 사용합니다"
/add-memory "테스트 파일은 __tests__ 디렉토리에 위치합니다"
/add-memory "Prisma 마이그레이션 후 항상 npx prisma generate를 실행합니다"

12.4 효율적인 프롬프트 작성

나쁜 프롬프트:

로그인 기능 만들어줘

좋은 프롬프트:

NextAuth.js를 사용하여 Google OAuth 로그인 기능을 추가해줘.
- /app/api/auth/[...nextauth]/route.ts 에 설정
- Google Provider 사용
- 세션에 사용자 ID 포함
- 로그인/로그아웃 버튼 컴포넌트 생성
- 기존 Navbar 컴포넌트에 통합

12.5 디버깅 전략

# 상세 로그 모드
claude --verbose

# 도구 사용 로그
claude --debug-tools

# 세션 기록 내보내기
claude --export-session ./session-log.json

# 특정 모델로 전환하여 비교
claude --model claude-opus-4-20250514

12.6 비용 최적화

# 현재 세션 비용 확인
/cost

# 경제적 모드 (Haiku 사용)
claude --model claude-haiku

# 자동 비용 알림 설정
claude config set cost.alert-threshold 5.00

13. 퀴즈

Claude Code에 대해 얼마나 이해했는지 확인해보세요.

Q1. Claude Code의 세 가지 핵심 능력은 무엇인가요?

A1. Claude Code의 세 가지 핵심 능력은:

  1. 코드베이스 읽기: 프로젝트 전체 구조와 파일을 이해
  2. 파일 편집: 코드 수정, 생성, 삭제 수행
  3. 명령어 실행: 쉘 커맨드를 직접 실행

이 세 가지 능력의 조합이 Claude Code를 단순 챗봇이 아닌 진정한 코딩 에이전트로 만듭니다.

Q2. 서브에이전트(Subagent)의 핵심 특성 네 가지는?

A2. 서브에이전트의 핵심 특성:

  1. 독립 컨텍스트: 각 서브에이전트가 자체 컨텍스트 윈도우를 가짐
  2. 병렬 실행: 여러 서브에이전트가 동시에 작업 수행
  3. 결과 통합: 메인 에이전트가 결과를 종합
  4. 실패 격리: 하나의 실패가 다른 작업에 영향 없음
Q3. CLAUDE.md의 계층 구조에서 가장 높은 우선순위를 가진 것은?

A3. 하위 디렉토리의 CLAUDE.md가 가장 높은 우선순위를 가집니다. 계층 구조는:

  1. 전역 CLAUDE.md (가장 낮음)
  2. 프로젝트 루트 CLAUDE.md
  3. 하위 디렉토리 CLAUDE.md (가장 높음 — 해당 디렉토리 내에서)

더 구체적인 위치의 설정이 일반적인 설정을 오버라이드합니다.

Q4. MCP(Model Context Protocol)의 역할은 무엇이며, 어떤 외부 시스템과 연동할 수 있나요?

A4. MCP는 AI 모델이 외부 도구와 데이터 소스에 접근할 수 있게 해주는 표준 프로토콜입니다. 연동 가능한 시스템 예시:

  • 데이터베이스: PostgreSQL, SQLite, MySQL
  • 버전 관리: GitHub, GitLab
  • 커뮤니케이션: Slack, Discord
  • 프로젝트 관리: Linear, Jira
  • 웹 브라우저: Puppeteer
  • 검색: Brave Search
  • 에러 추적: Sentry
  • 커스텀 API: 자체 MCP 서버 구축 가능
Q5. Claude Code의 훅(Hook) 시스템에서 PostToolUse 훅은 언제 실행되며, 대표적인 활용 사례는?

A5. PostToolUse 훅은 Claude Code가 도구(파일 편집, 명령어 실행 등)를 사용한 직후에 실행됩니다.

대표적인 활용 사례:

  • 자동 포매팅: 파일 수정 후 Prettier/ESLint 자동 실행
  • 자동 테스트: 파일 변경 후 관련 테스트 자동 실행
  • 변경 로깅: 파일 변경 이력 자동 기록
  • 타입 검사: TypeScript 파일 수정 후 타입 체크 자동 실행

이를 통해 코드 품질을 자동으로 유지할 수 있습니다.


참고 자료

공식 문서

  1. Anthropic Claude Code 공식 문서
  2. Claude Code GitHub 리포지토리
  3. Model Context Protocol (MCP) 공식 사이트
  4. MCP 서버 목록
  5. Anthropic API 문서

블로그 및 기술 문서

  1. Anthropic 블로그 - Claude Code 소개
  2. Claude Code Best Practices
  3. CLAUDE.md 작성 가이드
  4. Claude Code Hooks 문서
  5. Agent SDK 가이드

커뮤니티 및 관련 자료

  1. Awesome Claude Code - 커뮤니티 리소스
  2. Claude Code Discord 커뮤니티
  3. MCP 서버 개발 가이드
  4. 에이전틱 코딩 트렌드 분석
  5. Claude Code vs 기존 AI 코딩 도구 비교
  6. Anthropic Cookbook - Claude Code 예제
  7. Claude Code 슬래시 명령어 레퍼런스

Claude Code Complete Guide: Subagents, Hooks, Agent SDK — Everything About Agentic Coding

Introduction: The Era of Agentic Coding

2025 marks the year the AI coding paradigm fundamentally shifted. Beyond simple code autocomplete, we have entered the era of Agentic Coding — where AI autonomously explores codebases, formulates plans, edits files, and runs tests.

Anthropic's Claude Code stands at the forefront of this paradigm. Operating through a terminal-native interface, it understands your entire project context and integrates naturally into developer workflows. It is not just a chatbot — it is a true coding agent.

This guide covers everything from Claude Code's core features to subagents, the hooks system, Agent SDK, and MCP server integration — the complete picture of agentic coding.

Target audience: Developers, team leads, and DevOps engineers interested in AI coding tools. Assumes basic terminal and Git knowledge.


1. What Is Claude Code

1.1 Core Concepts

Claude Code is Anthropic's terminal-based agentic coding tool. Rather than an IDE plugin, it runs directly in your terminal with three core capabilities:

CapabilityDescriptionExample
Read codebaseUnderstands full project structure and filesDependency analysis, architecture mapping
Edit filesPerforms code modifications, creation, deletionBug fixes, refactoring, new features
Run commandsExecutes shell commands directlyRunning tests, builds, Git operations

The key differentiator is depth of context. Claude Code understands not just individual files, but the entire project — directory structure, dependency relationships, coding conventions, and Git history.

1.2 Terminal-First Philosophy

Claude Code's choice of the terminal is deliberate:

  • Maximum flexibility: Combines with any editor or workflow
  • Automation friendly: Integrates into scripts and CI/CD pipelines
  • Low overhead: No additional IDE installation, works over SSH
  • Transparency: All commands and file changes are visible in the terminal
# Basic Claude Code execution
claude

# Run with a specific prompt
claude "Analyze the architecture of this project"

# Pipeline mode
cat error.log | claude "Analyze this error and fix it"

1.3 How It Works

Claude Code's workflow follows these steps:

  1. Context gathering: Scans project structure, CLAUDE.md files, Git state
  2. Plan formulation: Analyzes user request and creates a work plan
  3. Tool usage: Reads/writes files, executes commands, searches
  4. Verification: Confirms changes, runs tests
  5. Feedback loop: Makes additional modifications based on results

Throughout this process, users can review and approve each step. Balancing autonomy with control is Claude Code's design philosophy.


2. Claude Code vs Cursor vs GitHub Copilot

A comparison of the three major players in the agentic coding tool market.

2.1 Feature Comparison

FeatureClaude CodeCursorGitHub Copilot
InterfaceTerminal (CLI)IDE (VS Code fork)IDE plugin
Codebase understandingEntire projectEntire projectFile/tab level
File editingDirect editingDirect editingSuggestion-based
Command executionYesLimitedNo
Agent modeNativeComposer AgentAgent mode (preview)
SubagentsParallel subagentsNot supportedNot supported
Hooks systemBuilt-in hooksNot supportedNot supported
Custom agentsAgent SDKNot supportedExtensions
MCP supportNativeSupportedLimited
Automation/CIExcellentLimitedGitHub Actions
Multi-repoWorktree supportLimitedNot supported
PricingAPI usage-based20/20/40 per month10/10/19 per month

2.2 When to Choose Which Tool

Claude Code is ideal when:

  • You need complex refactoring across a large codebase
  • You want to integrate AI into CI/CD pipelines
  • You frequently make changes spanning multiple files
  • You want to build custom agents to automate team workflows

Cursor is ideal when:

  • You prefer a visual IDE environment
  • Real-time suggestions while coding are important
  • You are familiar with the VS Code ecosystem

GitHub Copilot is ideal when:

  • You want to start lightweight in your existing IDE
  • Inline autocomplete is your primary use case
  • You need tight integration with the GitHub ecosystem

3. Installation and Setup

3.1 Installation

Installing Claude Code is straightforward via npm:

# Requires Node.js 18 or higher
npm install -g @anthropic-ai/claude-code

# Or run with npx in a specific directory
npx @anthropic-ai/claude-code

After installation, proceed with authentication:

# Authentication process starts on first run
claude

# Authenticate with Anthropic account or API key
# Browser opens to complete authentication

3.2 VS Code Extension

While Claude Code is a terminal tool, it also provides a VS Code extension:

# Install the VS Code extension
code --install-extension anthropic.claude-code

Benefits of the VS Code extension:

  • Use Claude Code panel within the editor
  • View file changes in diff view
  • Ask questions about specific code via inline comments

3.3 Basic Configuration

# View configuration
claude config list

# Set model (default: claude-sonnet-4-20250514)
claude config set model claude-sonnet-4-20250514

# Permission settings
claude config set permissions.allow-edit true
claude config set permissions.allow-exec true

# Auto-approve patterns
claude config set permissions.auto-approve-commands "npm test,npm run lint"

3.4 Terminal Environment Tips

# Run Claude Code in tmux session (useful for long tasks)
tmux new-session -s claude
claude

# Save work logs
claude --output-dir ./claude-logs

# Non-interactive mode (for scripts)
claude -p "Update the README.md" --yes

4. Mastering CLAUDE.md

4.1 What Is CLAUDE.md

CLAUDE.md is a markdown file that conveys project context, conventions, and instructions to Claude Code. It is automatically read when Claude Code starts a project — the core mechanism for helping AI understand your project's "rules."

4.2 CLAUDE.md Hierarchy

CLAUDE.md can exist in multiple locations with hierarchical application:

LocationScopePurpose
~/.claude/CLAUDE.mdGlobalCommon rules for all projects
Project root CLAUDE.mdEntire projectArchitecture, tech stack, rules
Subdirectory CLAUDE.mdThat directoryModule-specific rules
.claude/CLAUDE.mdPersonalPersonal settings (not in Git)

4.3 Writing Effective CLAUDE.md

# Project Overview

This project is a blog platform built on Next.js 14.
Uses TypeScript with Tailwind CSS for styling.

# Tech Stack

- Framework: Next.js 14 (App Router)
- Language: TypeScript (strict mode)
- Styling: Tailwind CSS
- Database: PostgreSQL + Prisma ORM
- Testing: Jest + React Testing Library

# Coding Conventions

- Components: Functional components with arrow functions
- Naming: camelCase (variables/functions), PascalCase (components/types)
- Import order: External libraries > Internal modules > Relative paths
- Error handling: Use Result type pattern instead of try-catch

# Testing Rules

- Unit tests required for all new functions
- Test command: npm test
- Lint command: npm run lint
- Ensure npm run build passes before PR

# Prohibited Patterns

- No use of any type
- No console.log (use logger)
- No hardcoded strings (use constants file)

# Directory Structure

src/
app/ - Next.js App Router pages
components/ - Reusable components
lib/ - Utilities, helper functions
types/ - TypeScript type definitions
hooks/ - Custom React hooks

4.4 Advanced CLAUDE.md Patterns

Conditional instructions:

# File-Specific Rules

- When modifying files under /src/api/: Always update API docs as well
- When modifying files under /src/components/: Update Storybook stories
- When changing database schema: Auto-generate migration files

Workflow instructions:

# Work Order

1. First explore and understand relevant code
2. Explain implementation plan
3. Implement changes
4. Run and verify tests
5. Update related documentation

4.5 CLAUDE.md Management Commands

# Add to CLAUDE.md during a conversation
claude /add-memory "API responses always use snake_case"

# Check currently applied memory
claude /memory

# Auto-generate CLAUDE.md during project initialization
claude /init

5. Core Workflows

5.1 The Explore - Plan - Implement - Verify Cycle

Claude Code's fundamental work cycle has four stages:

Stage 1: Explore

> Analyze the authentication system architecture of this project

What Claude Code does:
- Scans project directory structure
- Searches auth-related files (grep, glob)
- Analyzes dependencies (package.json, import tracing)
- Checks configuration files

Stage 2: Plan

> I want to add refresh token rotation to the JWT token renewal logic

What Claude Code does:
- Analyzes current token renewal logic
- Lists files that need changes
- Explains implementation plan
- Analyzes expected impact scope

Stage 3: Implement

Once the user approves the plan, Claude Code directly modifies the code. It shows diffs before each file change and requests approval.

Stage 4: Verify

> Test and verify the changes

What Claude Code does:
- Runs npm test
- Lint check
- Type check
- Build verification

5.2 Real Scenario: Bug Fix

# Pipe error log to Claude Code
cat error.log | claude "Analyze this error and fix it"

# Claude Code's workflow:
# 1. Analyze error message
# 2. Search related source code
# 3. Identify root cause
# 4. Write fix
# 5. Run tests to confirm fix

5.3 Real Scenario: Adding a New Feature

> Add an activity history timeline to the user profile page.
> Show the last 30 days of activity in chronological order,
> with infinite scroll to load older activities.

Claude Code's work:
1. Analyze existing profile page code
2. Check/create activity data API endpoint
3. Implement timeline component
4. Implement infinite scroll logic
5. Apply styling
6. Write and run tests

5.4 Git Workflow Integration

# Create a commit from current changes
claude commit

# Create a PR
claude "Create a PR from the changes on the current branch"

# Code review
claude "Review the changes in PR #42"

# Resolve merge conflicts
claude "Resolve the current merge conflicts"

6. Subagents Deep Dive

6.1 What Are Subagents

Subagents are one of Claude Code's most powerful features. The main agent splits complex tasks into multiple independent subtasks and executes them in parallel.

Main Agent (Orchestrator)
├── Subagent 1: Implement API endpoints
├── Subagent 2: Write frontend components
├── Subagent 3: Database migration
└── Subagent 4: Write test code

6.2 How Subagents Work

Subagents have the following characteristics:

CharacteristicDescription
Independent contextEach subagent has its own context window
Parallel executionMultiple subagents work simultaneously
Result integrationMain agent synthesizes subagent results
Failure isolationOne subagent's failure does not affect others
Read-only optionAnalysis/exploration subagents can run read-only

6.3 Subagent Usage Patterns

Pattern 1: Large-Scale Refactoring

> Convert all class components to functional components across the project

Main agent's work:
1. Search all files using class components
2. Divide files into groups
3. Assign each group to a subagent
4. Subagents perform conversion in parallel
5. Integrate results and run tests

Pattern 2: Multi-File Analysis

> Analyze security vulnerabilities in this project

Subagent 1: Analyze authentication/authorization code
Subagent 2: Check SQL injection possibilities
Subagent 3: Check XSS vulnerabilities
Subagent 4: Dependency security audit

Pattern 3: Code Generation + Testing

> Create a user management CRUD API

Subagent 1: Generate API routes and controllers
Subagent 2: Generate data models and migrations
Subagent 3: Write integration tests
Subagent 4: Generate API documentation

6.4 Background Agents

Claude Code can continue working in the background:

# Start background agent
claude --background "Increase test coverage to above 80%"

# Check background agent status
claude --list-backgrounds

# Review results
claude --resume <session-id>

Use cases for background agents:

  • Long-running refactoring tasks
  • Large-scale code migration
  • Test coverage improvement
  • Documentation tasks

6.5 Parallel Work with Worktrees

Combining with Git worktrees enables even more powerful parallel work:

# Create worktree and perform independent work
claude "Create a worktree and refactor the auth module on the feature-auth branch"

# Continue other work on main branch
claude "Continue with the bug fix"

Benefits of worktrees:

  • Isolated work environment: Experiment without affecting main code
  • Parallel development: Develop multiple features simultaneously
  • Safe experimentation: Just delete the worktree if it fails

7. Hooks System

7.1 What Are Hooks

Hooks are custom actions that automatically execute in response to specific events in Claude Code. They are the core mechanism for automating development workflows.

7.2 Types of Hooks

Hook EventTrigger PointUse Case
PreToolUseBefore tool executionBlock dangerous commands, back up files
PostToolUseAfter tool executionAuto-formatting, lint execution
NotificationWhen notification occursSlack alerts, email sending
StopWhen agent terminatesFinal verification, report generation

7.3 Configuring Hooks

Hooks are configured in the .claude/settings.json file:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit",
        "command": "cp \"$CLAUDE_FILE_PATH\" \"$CLAUDE_FILE_PATH.bak\" 2>/dev/null || true"
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit",
        "command": "npx prettier --write \"$CLAUDE_FILE_PATH\""
      },
      {
        "matcher": "Write",
        "command": "npx eslint --fix \"$CLAUDE_FILE_PATH\""
      }
    ],
    "Notification": [
      {
        "matcher": "",
        "command": "terminal-notifier -message \"$CLAUDE_NOTIFICATION\" -title \"Claude Code\""
      }
    ],
    "Stop": [
      {
        "matcher": "",
        "command": "npm test 2>&1 | tail -20"
      }
    ]
  }
}

7.4 Practical Hook Recipes

Recipe 1: Auto-Test Execution

Automatically run related tests whenever a file is modified:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit",
        "command": "if [[ \"$CLAUDE_FILE_PATH\" == *.ts ]]; then npx jest --findRelatedTests \"$CLAUDE_FILE_PATH\" --passWithNoTests; fi"
      }
    ]
  }
}

Recipe 2: Auto-Formatting Pipeline

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "command": "npx prettier --write \"$CLAUDE_FILE_PATH\" && npx eslint --fix \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
      }
    ]
  }
}

Recipe 3: Security Guardrails

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "command": "if echo \"$CLAUDE_COMMAND\" | grep -qE 'rm -rf|DROP TABLE|DELETE FROM'; then echo 'BLOCKED: Dangerous command detected' && exit 1; fi"
      }
    ]
  }
}

Recipe 4: Change Logging

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "command": "echo \"$(date): $CLAUDE_FILE_PATH modified\" >> .claude/change.log"
      }
    ]
  }
}

7.5 Debugging Hooks

# View hook execution logs
claude --verbose

# Disable a specific hook
claude config set hooks.PostToolUse.enabled false

# Skip hooks (temporarily)
claude --no-hooks

8. Agent SDK

8.1 Agent SDK Overview

The Agent SDK enables programmatic access to Claude Code's core capabilities, allowing you to build custom AI agents.

import { AgentSDK } from '@anthropic-ai/claude-code-sdk'

const agent = new AgentSDK({
  model: 'claude-sonnet-4-20250514',
  permissions: {
    fileRead: true,
    fileWrite: true,
    commandExec: ['npm test', 'npm run lint'],
  },
})

8.2 Core Concepts

ConceptDescription
SessionConversation context with the agent
ToolsCapabilities available to the agent
PermissionsLimits on the agent's scope of work
EventsEvents that occur during agent work

8.3 Building Custom Agents

Example 1: Code Review Agent

import { AgentSDK } from '@anthropic-ai/claude-code-sdk'

async function createCodeReviewAgent() {
  const agent = new AgentSDK({
    model: 'claude-sonnet-4-20250514',
    systemPrompt: `You are a senior code reviewer.
    Review code from these perspectives:
    1. Security vulnerabilities
    2. Performance issues
    3. Coding convention compliance
    4. Test coverage`,
    permissions: {
      fileRead: true,
      fileWrite: false,
      commandExec: ['git diff'],
    },
  })

  const session = await agent.createSession()
  const result = await session.send('Review the changes in the current PR')

  console.log(result.response)
  console.log('Issues found:', result.issues)
}

Example 2: Auto-Documentation Agent

async function createDocAgent() {
  const agent = new AgentSDK({
    model: 'claude-sonnet-4-20250514',
    systemPrompt: `Automatically generate JSDoc/TSDoc documentation for functions and modules.
    Update existing docs or create new ones where missing.`,
    permissions: {
      fileRead: true,
      fileWrite: true,
      commandExec: ['npm run build'],
    },
  })

  const session = await agent.createSession()
  await session.send('Add documentation to all exported functions in the src/lib/ directory')
}

Example 3: Database Migration Agent

async function createMigrationAgent() {
  const agent = new AgentSDK({
    model: 'claude-sonnet-4-20250514',
    systemPrompt: `A specialized agent for managing Prisma migrations.
    Analyzes schema changes and generates safe migrations.`,
    permissions: {
      fileRead: true,
      fileWrite: true,
      commandExec: ['npx prisma migrate dev', 'npx prisma generate', 'npx prisma db push'],
    },
  })

  const session = await agent.createSession()
  await session.send('Create a migration to add a profileImage field to the User model')
}

8.4 Event Handling

const session = await agent.createSession()

session.on('toolUse', (event) => {
  console.log(`Tool used: ${event.tool} - ${event.description}`)
})

session.on('fileChange', (event) => {
  console.log(`File changed: ${event.path} - ${event.type}`)
})

session.on('commandExec', (event) => {
  console.log(`Command executed: ${event.command}`)
  console.log(`Result: ${event.output}`)
})

session.on('error', (event) => {
  console.error(`Error occurred: ${event.message}`)
})

8.5 Permission Model

Security is a core design principle of the Agent SDK:

const agent = new AgentSDK({
  permissions: {
    // File access control
    fileRead: true,
    fileWrite: true,
    fileGlob: ['src/**/*.ts', 'tests/**/*.ts'], // Allowed patterns
    fileExclude: ['*.env', 'secrets/**'], // Blocked patterns

    // Command execution control
    commandExec: ['npm test', 'npm run lint', 'npx prisma migrate dev'],

    // Network access control
    networkAccess: false,

    // MCP server access
    mcpServers: ['filesystem', 'database'],
  },
})

9. MCP Server Integration

9.1 What Is MCP (Model Context Protocol)

MCP is a standard protocol that enables AI models to access external tools and data sources. Claude Code natively supports MCP, enabling integration with various external systems:

Claude Code <--MCP--> Database Server
Claude Code <--MCP--> GitHub API
Claude Code <--MCP--> Slack API
Claude Code <--MCP--> File System
Claude Code <--MCP--> Custom API

9.2 MCP Server Configuration

Register MCP servers at the project level in .claude/settings.json:

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/project"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "ghp_xxxxxxxxxxxx"
      }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "postgresql://user:pass@localhost:5432/mydb"
      }
    },
    "slack": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-slack"],
      "env": {
        "SLACK_TOKEN": "xoxb-xxxxxxxxxxxx"
      }
    }
  }
}
MCP ServerPurposeCapabilities
filesystemFile systemFile read/write, directory traversal
githubGitHub integrationPRs, issues, code search, reviews
postgresPostgreSQLQuery execution, schema inspection
sqliteSQLiteLocal database operations
slackSlack integrationMessage sending, channel queries
puppeteerWeb browserWeb scraping, E2E testing
memoryPersistent memoryData persistence across sessions
brave-searchWeb searchReal-time web search
sentryError trackingError log queries, analysis
linearProject managementIssue tracking, sprint management

9.4 Building Custom MCP Servers

Create custom MCP servers to connect your own APIs or internal systems:

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'

const server = new McpServer({
  name: 'my-internal-api',
  version: '1.0.0',
})

// Define tools
server.tool(
  'getDeployStatus',
  'Get deployment status',
  {
    environment: { type: 'string', enum: ['staging', 'production'] },
  },
  async (params) => {
    const status = await fetchDeployStatus(params.environment)
    return {
      content: [
        {
          type: 'text',
          text: JSON.stringify(status, null, 2),
        },
      ],
    }
  }
)

server.tool(
  'triggerDeploy',
  'Trigger a deployment',
  {
    environment: { type: 'string' },
    version: { type: 'string' },
  },
  async (params) => {
    const result = await triggerDeploy(params.environment, params.version)
    return {
      content: [
        {
          type: 'text',
          text: `Deployment triggered: ${result.id}`,
        },
      ],
    }
  }
)

// Start server
const transport = new StdioServerTransport()
await server.connect(transport)

9.5 MCP Server Usage Scenarios

Scenario 1: Database-Integrated Development

> Check the users table schema and create a new API endpoint

Claude Code's work:
1. Query schema via MCP postgres server
2. Analyze existing API patterns
3. Generate new endpoint code
4. Generate migration file
5. Write tests

Scenario 2: GitHub-Integrated Workflow

> Check recently opened issues with the bug label,
> and fix the highest priority one

Claude Code's work:
1. Query issue list via MCP github server
2. Analyze priorities
3. Explore and fix related code
4. Create PR

10. Advanced Patterns

10.1 Multi-Repository Work

Perform tasks spanning multiple repositories:

# In a monorepo environment
claude "Analyze the impact of changes to the packages/shared library on
packages/web and packages/api, and perform all necessary updates"

10.2 Git Worktree Usage

# Develop multiple features simultaneously
claude "Create worktrees and perform these tasks in parallel:
1. feature/auth - Refactor authentication module
2. feature/dashboard - Optimize dashboard performance
3. fix/memory-leak - Fix memory leak"

10.3 Scheduled Tasks

Schedule repetitive tasks with Claude Code:

# Generate daily code quality report
claude schedule --cron "0 9 * * *" "Generate a code quality report and share it on Slack"

# Check dependency updates every Monday
claude schedule --cron "0 10 * * 1" "Check npm outdated and apply safe updates"

10.4 Headless Mode and CI/CD Integration

# GitHub Actions example
name: Claude Code Review
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run Claude Code Review
        run: |
          npx @anthropic-ai/claude-code -p \
            "Review the changes in this PR and leave comments" \
            --yes --output-format json
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

10.5 Context Window Optimization

Strategies for efficiently using context in large projects:

  1. Pre-provide project context via CLAUDE.md: Supply essential information upfront instead of repeated exploration
  2. Distribute context via subagents: Split large tasks into smaller independent tasks
  3. Compress conversations with /compact: Retain only essentials in long conversations
  4. File filtering: Exclude unnecessary files with .claudeignore
# .claudeignore example
node_modules/
dist/
.next/
coverage/
*.lock
*.log

11. Real-World Case Studies and Productivity Data

11.1 Anthropic Internal Usage Data

Usage data shared by Anthropic's internal development team:

MetricValue
Code writing time reduction~40-60%
Code review time reduction~30-50%
Average bug fix time50% decrease vs. baseline
Test coverage improvementAverage 15-20% increase
Daily commit countAverage 2-3x increase

11.2 Case Study 1: Large-Scale Migration

Situation: Migrating 200 React class components to functional components

  • Estimated manual work: 2-3 weeks (1 person)
  • With Claude Code: 2 days (subagent parallel processing)
  • Conversion success rate: 95% (remaining 5% required manual review)

11.3 Case Study 2: API Integration Development

Situation: External payment API integration (Stripe)

  • Work performed by Claude Code:
    • API documentation analysis (using MCP brave-search)
    • Interface type definitions
    • Service layer implementation
    • Webhook handler implementation
    • Error handling
    • 80% of unit/integration tests written
  • Time taken: 4 hours (vs. 2-3 days manually)

11.4 Case Study 3: Legacy Code Modernization

Situation: Modernizing a jQuery + PHP app to Next.js + TypeScript

  • Defined migration rules in CLAUDE.md
  • Parallel component-by-component conversion via subagents
  • Automatic type checking and testing via hooks
  • Reduced a 6-week project to 2 weeks

11.5 Tips for Maximizing Productivity

  1. Write detailed CLAUDE.md: The highest ROI investment
  2. Start with small tasks: Build trust with bug fixes and test additions before tackling larger work
  3. Use hooks actively: Automate repetitive verification tasks
  4. Leverage subagents: Split large tasks for parallel processing
  5. Always verify results: Review AI output rather than blindly trusting it

12. Tips and Tricks

12.1 Keyboard Shortcuts

ShortcutFunction
Ctrl+CCancel current task
Ctrl+DEnd session
EscCancel current input
TabAutocomplete
Up/DownBrowse previous commands

12.2 Slash Commands

/help          # Help
/clear         # Clear conversation
/compact       # Compress conversation
/memory        # Check memory (CLAUDE.md)
/add-memory    # Add rule to memory
/model         # Change model
/cost          # Check current session cost
/diff          # View current changes
/undo          # Undo last change
/review        # Request code review
/init          # Initialize project
/bug           # Bug report
/config        # Change settings

12.3 Using the Memory System

Claude Code's memory system maintains learned content across sessions:

# Add memory during conversation
/add-memory "API responses in this project always use camelCase"
/add-memory "Test files are located in __tests__ directories"
/add-memory "Always run npx prisma generate after Prisma migrations"

12.4 Writing Effective Prompts

Bad prompt:

Make a login feature

Good prompt:

Add Google OAuth login using NextAuth.js.
- Configure in /app/api/auth/[...nextauth]/route.ts
- Use Google Provider
- Include user ID in session
- Create login/logout button component
- Integrate into existing Navbar component

12.5 Debugging Strategies

# Verbose logging mode
claude --verbose

# Tool usage logging
claude --debug-tools

# Export session history
claude --export-session ./session-log.json

# Switch to a specific model for comparison
claude --model claude-opus-4-20250514

12.6 Cost Optimization

# Check current session cost
/cost

# Economy mode (use Haiku)
claude --model claude-haiku

# Set automatic cost alerts
claude config set cost.alert-threshold 5.00

13. Quiz

Test your understanding of Claude Code.

Q1. What are Claude Code's three core capabilities?

A1. Claude Code's three core capabilities are:

  1. Read codebase: Understands full project structure and files
  2. Edit files: Performs code modifications, creation, and deletion
  3. Run commands: Executes shell commands directly

The combination of these three capabilities makes Claude Code a true coding agent rather than a simple chatbot.

Q2. What are the four key characteristics of subagents?

A2. The four key characteristics of subagents:

  1. Independent context: Each subagent has its own context window
  2. Parallel execution: Multiple subagents work simultaneously
  3. Result integration: The main agent synthesizes results
  4. Failure isolation: One failure does not affect other tasks
Q3. In the CLAUDE.md hierarchy, which has the highest priority?

A3. The subdirectory CLAUDE.md has the highest priority. The hierarchy is:

  1. Global CLAUDE.md (lowest)
  2. Project root CLAUDE.md
  3. Subdirectory CLAUDE.md (highest — within that directory)

More specific settings override general ones.

Q4. What is MCP (Model Context Protocol), and what external systems can it integrate with?

A4. MCP is a standard protocol that enables AI models to access external tools and data sources. Examples of integrable systems:

  • Databases: PostgreSQL, SQLite, MySQL
  • Version control: GitHub, GitLab
  • Communication: Slack, Discord
  • Project management: Linear, Jira
  • Web browser: Puppeteer
  • Search: Brave Search
  • Error tracking: Sentry
  • Custom APIs: Build your own MCP server
Q5. When does the PostToolUse hook fire, and what are typical use cases?

A5. The PostToolUse hook fires immediately after Claude Code uses a tool (file editing, command execution, etc.).

Typical use cases:

  • Auto-formatting: Automatically run Prettier/ESLint after file modification
  • Auto-testing: Automatically run related tests after file changes
  • Change logging: Automatically record file change history
  • Type checking: Automatically run type checks after TypeScript file modifications

This enables automatic code quality maintenance.


References

Official Documentation

  1. Anthropic Claude Code Official Docs
  2. Claude Code GitHub Repository
  3. Model Context Protocol (MCP) Official Site
  4. MCP Server Directory
  5. Anthropic API Documentation

Blog Posts and Technical Articles

  1. Anthropic Blog - Introducing Claude Code
  2. Claude Code Best Practices
  3. CLAUDE.md Writing Guide
  4. Claude Code Hooks Documentation
  5. Agent SDK Guide
  1. Awesome Claude Code - Community Resources
  2. Claude Code Discord Community
  3. MCP Server Development Guide
  4. Agentic Coding Trends Analysis
  5. Claude Code vs Traditional AI Coding Tools
  6. Anthropic Cookbook - Claude Code Examples
  7. Claude Code Slash Commands Reference