# 플러그인 시스템

Claude Code 플러그인 시스템을 사용하면 사용자 지정 슬래시 명령, 특화된 에이전트, 재사용 가능한 스킬, 자동화 훅을 만들어 Claude의 기능을 확장할 수 있어요. 플러그인을 사용하면 팀의 모범 사례와 워크플로를 코드로 정의할 수 있어요.

## 플러그인이란?

### 핵심 개념

Claude Code 플러그인은 특정 파일 구조를 가진 디렉터리로, 다음 구성 요소를 추가할 수 있어요:

| 구성 요소 | 설명 | 파일 형식 |
|-----------|-------------|-------------|
| **Commands** | 사용자 지정 슬래시 명령 | `.md` 파일 |
| **Agents** | 특화된 작업 서브에이전트 | `.md` 파일 |
| **Skills** | 재사용 가능한 지식과 기능 | 디렉터리 + `SKILL.md` |
| **Hooks** | 이벤트 기반 자동화 | `hooks.json` |

### 플러그인이 필요한 이유

- **팀 표준화**: 코딩 표준과 리뷰 기준을 실행 가능한 명령으로 정의할 수 있어요

- **워크플로 자동화**: 커밋, 배포, 리뷰 같은 반복 작업을 자동화할 수 있어요

- **지식 공유**: 팀원 간에 모범 사례와 전문 지식을 공유할 수 있어요

- **사용자 지정 경험**: 프로젝트 요구에 맞게 Claude의 동작을 사용자 지정할 수 있어요

## 플러그인 디렉터리 구조

```
my-plugin/
├── .claude-plugin/
│   └── plugin.json          # Required: Plugin manifest
├── commands/                 # Slash commands (.md files)
│   ├── review.md
│   └── deploy.md
├── agents/                   # Subagent definitions (.md files)
│   └── code-reviewer.md
├── skills/                   # Agent skills (subdirectories)
│   └── coding-standards/
│       └── SKILL.md
├── hooks/
│   └── hooks.json           # Event handler configuration
├── .mcp.json                # MCP server definitions (optional)
└── scripts/                 # Helper scripts (optional)
```

## 빠른 시작

### 플러그인 설치

```bash
# Install from marketplace
/plugin install plugin-name@claude-code-marketplace

# Install from local directory
claude --plugin-dir /path/to/my-plugin
```

### 플러그인 생성 마법사 사용

```bash
/plugin-dev:create-plugin
```

이 명령은 8단계에 걸쳐 완전한 플러그인을 만들도록 안내해요.

## 사용자 지정 명령 만들기

### 기본 명령 형식

`commands/` 디렉터리에 `.md` 파일을 만들어요:

```markdown
---
description: Perform code review
argument-hint: [file-path]
allowed-tools: Read, Bash(git status:*), Bash(git diff:*)
---

Please review the code quality of: @$1

Focus on:
1. Code readability
2. Potential bugs
3. Performance issues
4. Security vulnerabilities
```

### YAML 프런트매터 구성

| 필드 | 설명 | 예시 |
|-------|-------------|---------|
| `description` | 명령 설명 (/help에 표시됨) | `Perform code review` |
| `argument-hint` | 매개변수 힌트 | `[file-path] [options]` |
| `allowed-tools` | 허용된 도구 | `Read, Bash(git status:*), Bash(git diff:*)` |
| `model` | 모델 지정 | `opus` 또는 `sonnet` |

### 동적 인자 사용

- `$1`, `$2`, `$3`... - 위치 인자

- `$ARGUMENTS` - 모든 인자

- `@path/to/file` - 파일 참조

- `!`command`` - Bash 명령 실행

### 명령 예시

**코드 리뷰 명령** (`commands/review.md`):

```markdown
---
description: Comprehensive code review
argument-hint: [file-or-directory]
allowed-tools: Read, Grep, Glob
model: opus
---

Perform a comprehensive code review of @$1.

Checklist:
- [ ] Code style follows project standards
- [ ] No potential security issues
- [ ] Error handling is complete
- [ ] Tests are needed

If it's a directory, first use Glob tool to find all relevant files.
```

**스마트 커밋 명령** (`commands/commit.md`):

```markdown
---
description: Smart commit with generated message
allowed-tools: Bash(git status:*), Bash(git diff:*), Bash(git add:*), Bash(git commit:*)
---

1. Run `git status` to see changes
2. Run `git diff --staged` to analyze staged changes
3. Generate a conventional commit message based on changes
4. Execute `git commit`

Commit message format:
- feat: New feature
- fix: Bug fix
- docs: Documentation update
- refactor: Refactoring
- test: Test related
```

> ⚠️ **`Bash(git:*)`는 절대 작성하지 마세요**: 이 와일드카드는 `git push --force`, `git reset --hard`, 원격 변경 같은 파괴적인 명령을 포함해 모든 git 하위 명령을 한 번에 허용해요. 실제로 필요한 하위 명령(`git status` / `git diff` / `git add` / `git commit`)만 나열하고, 커밋 명령에 `git push`를 슬쩍 넣지 마세요.

## 사용자 지정 에이전트 만들기

### 에이전트 정의 형식

`agents/` 디렉터리에 `.md` 파일을 만들어요:

```markdown
---
description: Specialized code review agent
model: opus
tools: Read, Grep, Glob
---

You are a professional code review agent. Your task is to:

1. Carefully read the provided code
2. Identify potential issues
3. Provide specific improvement suggestions
4. Focus on security and performance

Always be constructive and specific.
```

### 에이전트 유형

| 유형 | 용도 | 예시 |
|------|---------|---------|
| Review Agent | 코드 리뷰, PR 리뷰 | `code-reviewer` |
| Test Agent | 테스트 생성 및 실행 | `test-generator` |
| Doc Agent | 문서 생성 | `doc-writer` |
| Refactor Agent | 코드 리팩터링 | `refactorer` |

## 스킬 만들기

### 스킬 디렉터리 구조

```
skills/
└── coding-standards/
    ├── SKILL.md              # Required: Skill definition
    ├── references/           # Reference materials
    │   └── style-guide.md
    └── examples/             # Example code
        └── good-practices.md
```

### SKILL.md 형식

```markdown
# Coding Standards Skill

## Overview
This skill contains team coding standards and best practices.

## Knowledge Content

### Naming Conventions
- Variables: camelCase
- Constants: UPPER_SNAKE_CASE
- Classes: PascalCase
- Files: kebab-case

### Code Style
- Use 2-space indentation
- Max line width 100 characters
- Use semicolons

### Error Handling
- Always use try-catch
- Log errors
- Provide meaningful error messages
```

## 훅 만들기

### hooks.json 형식

`hooks.json`은 `settings.json`의 `hooks` 필드와 같은 형태를 사용해요: 이벤트 이름 → matcher → `hooks` 배열이에요. 이벤트는 실제 라이프사이클 이벤트(`PreToolUse` / `PostToolUse` 등)여야 하며, `on_commit` 같은 예전의 존재하지 않는 이름은 존재하지 않아요.

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "echo \"$TOOL_INPUT\" | grep -qE 'rm -rf /|git push --force' && exit 2 || exit 0"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "npm run lint && npm run typecheck"
          }
        ]
      }
    ]
  }
}
```

### 지원되는 이벤트

| 이벤트 | 트리거 시점 | 차단 가능 |
|-------|----------------|-----------|
| `PreToolUse` | 도구 실행 전 | 예 (exit 2) |
| `PostToolUse` | 도구 실행 후 | 아니요 |
| `UserPromptSubmit` | 사용자가 프롬프트 제출 시 | 예 |
| `SessionStart` | 세션 시작 시 | 아니요 |
| `Stop` | Claude가 응답을 마칠 때 | 아니요 |
| `Notification` | Claude가 알림을 보낼 때 | 아니요 |

전체 이벤트 목록과 핸들러 문법은 [Hooks System](/docs/advanced/hooks)을 참고하세요.

## 플러그인 매니페스트

### plugin.json 형식

```json
{
  "name": "my-plugin",
  "version": "1.0.0",
  "description": "My custom plugin",
  "author": "Your Name",
  "components": {
    "commands": ["commands/*.md"],
    "agents": ["agents/*.md"],
    "skills": ["skills/*/SKILL.md"],
    "hooks": "hooks/hooks.json"
  },
  "mcpServers": ".mcp.json"
}
```

## 실전 예시

### 예시 1: 팀 코드 리뷰 플러그인

```
team-review-plugin/
├── .claude-plugin/
│   └── plugin.json
├── commands/
│   ├── review-pr.md          # PR review command
│   ├── security-check.md     # Security check command
│   └── perf-audit.md         # Performance audit command
├── agents/
│   ├── security-reviewer.md  # Security review agent
│   └── perf-analyzer.md      # Performance analysis agent
└── skills/
    └── team-standards/
        └── SKILL.md          # Team standards skill
```

### 예시 2: 배포 자동화 플러그인

```
deploy-plugin/
├── .claude-plugin/
│   └── plugin.json
├── commands/
│   ├── deploy-staging.md     # Deploy to staging
│   ├── deploy-prod.md        # Deploy to production
│   └── rollback.md           # Rollback command
├── hooks/
│   └── hooks.json            # Pre-deploy check hooks
└── .mcp.json                 # Kubernetes MCP config
```

## 모범 사례

### 명령 설계

1. **단일 책임**: 각 명령은 한 가지 일만 해요

2. **명확한 설명**: description을 간결하게 유지하세요

3. **매개변수 문서화**: argument-hint로 매개변수를 설명하세요

4. **최소 권한**: allowed-tools에는 필요한 도구만 포함하세요

5. **오류 처리**: 실패 시나리오를 고려하세요

### 플러그인 구성

1. **모듈화**: 관련 기능을 함께 구성하세요

2. **재사용성**: 스킬은 여러 명령에서 사용할 수 있어야 해요

3. **문서화**: README와 사용 안내를 추가하세요

4. **버전 관리**: 시맨틱 버전 관리를 사용하세요

### 보안 고려 사항

1. **하드코딩된 시크릿 금지**: 환경 변수를 사용하세요

2. **파일 접근 제한**: 필요한 경로에만 접근하세요

3. **입력 검증**: 매개변수를 검증하세요

4. **감사 로그**: 민감한 작업을 기록하세요

## 플러그인 디버깅

```bash
# View plugin load status
/plugin list

# View command details
/help my-command

# Test command
/my-command test-argument
```

## 다음 단계

- 외부 연동을 확장하려면 [MCP Servers](/docs/advanced/mcp)를 알아보세요

- 효율을 높이려면 [CLI Tips](/docs/usage/cli-tips)를 확인하세요

- 개발 흐름을 최적화하려면 [Workflow Tips](/docs/usage/workflow-tips)를 살펴보세요