From 44ac37d84b88c9a703ff0e3b87b4218608d7086a Mon Sep 17 00:00:00 2001 From: hello Date: Sun, 26 Apr 2026 13:53:58 +0900 Subject: [PATCH] =?UTF-8?q?chore:=20remove=20claude-docs/=20=E2=80=94=20su?= =?UTF-8?q?perseded=20by=20claude-code-guide=20subagent?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit claude-code-guide subagent로 최신 Claude Code 레퍼런스를 검색하므로 정적 사본 5개 (agent-skills, hooks, plugins, slash-commands, subagents)를 제거. CLAUDE.md의 docs/ 디렉토리 참조도 정리. Co-Authored-By: Claude Opus 4.7 (1M context) --- CLAUDE.md | 9 +- claude-docs/agent-skills.md | 607 ----------------------- claude-docs/hooks.md | 892 ---------------------------------- claude-docs/plugins.md | 392 --------------- claude-docs/slash-commands.md | 490 ------------------- claude-docs/subagents.md | 387 --------------- 6 files changed, 3 insertions(+), 2774 deletions(-) delete mode 100644 claude-docs/agent-skills.md delete mode 100644 claude-docs/hooks.md delete mode 100644 claude-docs/plugins.md delete mode 100644 claude-docs/slash-commands.md delete mode 100644 claude-docs/subagents.md diff --git a/CLAUDE.md b/CLAUDE.md index 6c87751..3538b1c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -103,10 +103,7 @@ Each plugin requires `.claude-plugin/plugin.json`: - `marketplace.json` - Marketplace catalog - Plugin directories contain `.claude-plugin/plugin.json` -- **`docs/`** - Reference documentation for Claude Code features - - Not part of plugins; useful for understanding plugin development patterns - -- **Plugin directories** (e.g., `code-style-plugin/`, `simple-sdd-plugin/`) +- **Plugin directories** (e.g., `agent-team-plugin/`, `writing-specs-plugin/`) - Each plugin is self-contained and independently installable - Include README.md with installation and usage instructions @@ -216,6 +213,6 @@ Plugins can be shared through: ## See Also -- Claude Code Plugins Documentation: Check `docs/` directory for feature references +- Claude Code Plugins Documentation: use the `claude-code-guide` subagent for up-to-date references - Individual plugin READMEs: Each plugin contains usage documentation -- Plugin Structure: Refer to existing plugins as examples (e.g., `code-style-plugin/`) +- Plugin Structure: refer to existing plugins as examples (e.g., `writing-specs-plugin/`) diff --git a/claude-docs/agent-skills.md b/claude-docs/agent-skills.md deleted file mode 100644 index 5e3a8e5..0000000 --- a/claude-docs/agent-skills.md +++ /dev/null @@ -1,607 +0,0 @@ -# Agent Skills - -> Create, manage, and share Skills to extend Claude's capabilities in Claude Code. - -This guide shows you how to create, use, and manage Agent Skills in Claude Code. Skills are modular capabilities that extend Claude's functionality through organized folders containing instructions, scripts, and resources. - -## Prerequisites - -* Claude Code version 1.0 or later -* Basic familiarity with [Claude Code](/en/docs/claude-code/quickstart) - -## What are Agent Skills? - -Agent Skills package expertise into discoverable capabilities. Each Skill consists of a `SKILL.md` file with instructions that Claude reads when relevant, plus optional supporting files like scripts and templates. - -**How Skills are invoked**: Skills are **model-invoked**—Claude autonomously decides when to use them based on your request and the Skill's description. This is different from slash commands, which are **user-invoked** (you explicitly type `/command` to trigger them). - -**Benefits**: - -* Extend Claude's capabilities for your specific workflows -* Share expertise across your team via git -* Reduce repetitive prompting -* Compose multiple Skills for complex tasks - -Learn more in the [Agent Skills overview](/en/docs/agents-and-tools/agent-skills/overview). - - - For a deep dive into the architecture and real-world applications of Agent Skills, read our engineering blog: [Equipping agents for the real world with Agent Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills). - - -## Create a Skill - -Skills are stored as directories containing a `SKILL.md` file. - -### Personal Skills - -Personal Skills are available across all your projects. Store them in `~/.claude/skills/`: - -```bash theme={null} -mkdir -p ~/.claude/skills/my-skill-name -``` - -**Use personal Skills for**: - -* Your individual workflows and preferences -* Experimental Skills you're developing -* Personal productivity tools - -### Project Skills - -Project Skills are shared with your team. Store them in `.claude/skills/` within your project: - -```bash theme={null} -mkdir -p .claude/skills/my-skill-name -``` - -**Use project Skills for**: - -* Team workflows and conventions -* Project-specific expertise -* Shared utilities and scripts - -Project Skills are checked into git and automatically available to team members. - -### Plugin Skills - -Skills can also come from [Claude Code plugins](/en/docs/claude-code/plugins). Plugins may bundle Skills that are automatically available when the plugin is installed. These Skills work the same way as personal and project Skills. - -## Write SKILL.md - -Create a `SKILL.md` file with YAML frontmatter and Markdown content: - -```yaml theme={null} ---- -name: your-skill-name -description: Brief description of what this Skill does and when to use it ---- - -# Your Skill Name - -## Instructions -Provide clear, step-by-step guidance for Claude. - -## Examples -Show concrete examples of using this Skill. -``` - -**Field requirements**: - -* `name`: Must use lowercase letters, numbers, and hyphens only (max 64 characters) -* `description`: Brief description of what the Skill does and when to use it (max 1024 characters) - -The `description` field is critical for Claude to discover when to use your Skill. It should include both what the Skill does and when Claude should use it. - -See the [best practices guide](/en/docs/agents-and-tools/agent-skills/best-practices) for complete authoring guidance including validation rules. - -## Add supporting files - -Create additional files alongside SKILL.md: - -``` -my-skill/ -├── SKILL.md (required) -├── reference.md (optional documentation) -├── examples.md (optional examples) -├── scripts/ -│ └── helper.py (optional utility) -└── templates/ - └── template.txt (optional template) -``` - -Reference these files from SKILL.md: - -````markdown theme={null} -For advanced usage, see [reference.md](reference.md). - -Run the helper script: -```bash -python scripts/helper.py input.txt -``` -```` - -Claude reads these files only when needed, using progressive disclosure to manage context efficiently. - -## Restrict tool access with allowed-tools - -Use the `allowed-tools` frontmatter field to limit which tools Claude can use when a Skill is active: - -```yaml theme={null} ---- -name: safe-file-reader -description: Read files without making changes. Use when you need read-only file access. -allowed-tools: Read, Grep, Glob ---- - -# Safe File Reader - -This Skill provides read-only file access. - -## Instructions -1. Use Read to view file contents -2. Use Grep to search within files -3. Use Glob to find files by pattern -``` - -When this Skill is active, Claude can only use the specified tools (Read, Grep, Glob) without needing to ask for permission. This is useful for: - -* Read-only Skills that shouldn't modify files -* Skills with limited scope (e.g., only data analysis, no file writing) -* Security-sensitive workflows where you want to restrict capabilities - -If `allowed-tools` is not specified, Claude will ask for permission to use tools as normal, following the standard permission model. - - - `allowed-tools` is only supported for Skills in Claude Code. - - -## View available Skills - -Skills are automatically discovered by Claude from three sources: - -* Personal Skills: `~/.claude/skills/` -* Project Skills: `.claude/skills/` -* Plugin Skills: bundled with installed plugins - -**To view all available Skills**, ask Claude directly: - -``` -What Skills are available? -``` - -or - -``` -List all available Skills -``` - -This will show all Skills from all sources, including plugin Skills. - -**To inspect a specific Skill**, you can also check the filesystem: - -```bash theme={null} -# List personal Skills -ls ~/.claude/skills/ - -# List project Skills (if in a project directory) -ls .claude/skills/ - -# View a specific Skill's content -cat ~/.claude/skills/my-skill/SKILL.md -``` - -## Test a Skill - -After creating a Skill, test it by asking questions that match your description. - -**Example**: If your description mentions "PDF files": - -``` -Can you help me extract text from this PDF? -``` - -Claude autonomously decides to use your Skill if it matches the request—you don't need to explicitly invoke it. The Skill activates automatically based on the context of your question. - -## Debug a Skill - -If Claude doesn't use your Skill, check these common issues: - -### Make description specific - -**Too vague**: - -```yaml theme={null} -description: Helps with documents -``` - -**Specific**: - -```yaml theme={null} -description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction. -``` - -Include both what the Skill does and when to use it in the description. - -### Verify file path - -**Personal Skills**: `~/.claude/skills/skill-name/SKILL.md` -**Project Skills**: `.claude/skills/skill-name/SKILL.md` - -Check the file exists: - -```bash theme={null} -# Personal -ls ~/.claude/skills/my-skill/SKILL.md - -# Project -ls .claude/skills/my-skill/SKILL.md -``` - -### Check YAML syntax - -Invalid YAML prevents the Skill from loading. Verify the frontmatter: - -```bash theme={null} -cat SKILL.md | head -n 10 -``` - -Ensure: - -* Opening `---` on line 1 -* Closing `---` before Markdown content -* Valid YAML syntax (no tabs, correct indentation) - -### View errors - -Run Claude Code with debug mode to see Skill loading errors: - -```bash theme={null} -claude --debug -``` - -## Share Skills with your team - -**Recommended approach**: Distribute Skills through [plugins](/en/docs/claude-code/plugins). - -To share Skills via plugin: - -1. Create a plugin with Skills in the `skills/` directory -2. Add the plugin to a marketplace -3. Team members install the plugin - -For complete instructions, see [Add Skills to your plugin](/en/docs/claude-code/plugins#add-skills-to-your-plugin). - -You can also share Skills directly through project repositories: - -### Step 1: Add Skill to your project - -Create a project Skill: - -```bash theme={null} -mkdir -p .claude/skills/team-skill -# Create SKILL.md -``` - -### Step 2: Commit to git - -```bash theme={null} -git add .claude/skills/ -git commit -m "Add team Skill for PDF processing" -git push -``` - -### Step 3: Team members get Skills automatically - -When team members pull the latest changes, Skills are immediately available: - -```bash theme={null} -git pull -claude # Skills are now available -``` - -## Update a Skill - -Edit SKILL.md directly: - -```bash theme={null} -# Personal Skill -code ~/.claude/skills/my-skill/SKILL.md - -# Project Skill -code .claude/skills/my-skill/SKILL.md -``` - -Changes take effect the next time you start Claude Code. If Claude Code is already running, restart it to load the updates. - -## Remove a Skill - -Delete the Skill directory: - -```bash theme={null} -# Personal -rm -rf ~/.claude/skills/my-skill - -# Project -rm -rf .claude/skills/my-skill -git commit -m "Remove unused Skill" -``` - -## Best practices - -### Keep Skills focused - -One Skill should address one capability: - -**Focused**: - -* "PDF form filling" -* "Excel data analysis" -* "Git commit messages" - -**Too broad**: - -* "Document processing" (split into separate Skills) -* "Data tools" (split by data type or operation) - -### Write clear descriptions - -Help Claude discover when to use Skills by including specific triggers in your description: - -**Clear**: - -```yaml theme={null} -description: Analyze Excel spreadsheets, create pivot tables, and generate charts. Use when working with Excel files, spreadsheets, or analyzing tabular data in .xlsx format. -``` - -**Vague**: - -```yaml theme={null} -description: For files -``` - -### Test with your team - -Have teammates use Skills and provide feedback: - -* Does the Skill activate when expected? -* Are the instructions clear? -* Are there missing examples or edge cases? - -### Document Skill versions - -You can document Skill versions in your SKILL.md content to track changes over time. Add a version history section: - -```markdown theme={null} -# My Skill - -## Version History -- v2.0.0 (2025-10-01): Breaking changes to API -- v1.1.0 (2025-09-15): Added new features -- v1.0.0 (2025-09-01): Initial release -``` - -This helps team members understand what changed between versions. - -## Troubleshooting - -### Claude doesn't use my Skill - -**Symptom**: You ask a relevant question but Claude doesn't use your Skill. - -**Check**: Is the description specific enough? - -Vague descriptions make discovery difficult. Include both what the Skill does and when to use it, with key terms users would mention. - -**Too generic**: - -```yaml theme={null} -description: Helps with data -``` - -**Specific**: - -```yaml theme={null} -description: Analyze Excel spreadsheets, generate pivot tables, create charts. Use when working with Excel files, spreadsheets, or .xlsx files. -``` - -**Check**: Is the YAML valid? - -Run validation to check for syntax errors: - -```bash theme={null} -# View frontmatter -cat .claude/skills/my-skill/SKILL.md | head -n 15 - -# Check for common issues -# - Missing opening or closing --- -# - Tabs instead of spaces -# - Unquoted strings with special characters -``` - -**Check**: Is the Skill in the correct location? - -```bash theme={null} -# Personal Skills -ls ~/.claude/skills/*/SKILL.md - -# Project Skills -ls .claude/skills/*/SKILL.md -``` - -### Skill has errors - -**Symptom**: The Skill loads but doesn't work correctly. - -**Check**: Are dependencies available? - -Claude will automatically install required dependencies (or ask for permission to install them) when it needs them. - -**Check**: Do scripts have execute permissions? - -```bash theme={null} -chmod +x .claude/skills/my-skill/scripts/*.py -``` - -**Check**: Are file paths correct? - -Use forward slashes (Unix style) in all paths: - -**Correct**: `scripts/helper.py` -**Wrong**: `scripts\helper.py` (Windows style) - -### Multiple Skills conflict - -**Symptom**: Claude uses the wrong Skill or seems confused between similar Skills. - -**Be specific in descriptions**: Help Claude choose the right Skill by using distinct trigger terms in your descriptions. - -Instead of: - -```yaml theme={null} -# Skill 1 -description: For data analysis - -# Skill 2 -description: For analyzing data -``` - -Use: - -```yaml theme={null} -# Skill 1 -description: Analyze sales data in Excel files and CRM exports. Use for sales reports, pipeline analysis, and revenue tracking. - -# Skill 2 -description: Analyze log files and system metrics data. Use for performance monitoring, debugging, and system diagnostics. -``` - -## Examples - -### Simple Skill (single file) - -``` -commit-helper/ -└── SKILL.md -``` - -```yaml theme={null} ---- -name: generating-commit-messages -description: Generates clear commit messages from git diffs. Use when writing commit messages or reviewing staged changes. ---- - -# Generating Commit Messages - -## Instructions - -1. Run `git diff --staged` to see changes -2. I'll suggest a commit message with: - - Summary under 50 characters - - Detailed description - - Affected components - -## Best practices - -- Use present tense -- Explain what and why, not how -``` - -### Skill with tool permissions - -``` -code-reviewer/ -└── SKILL.md -``` - -```yaml theme={null} ---- -name: code-reviewer -description: Review code for best practices and potential issues. Use when reviewing code, checking PRs, or analyzing code quality. -allowed-tools: Read, Grep, Glob ---- - -# Code Reviewer - -## Review checklist - -1. Code organization and structure -2. Error handling -3. Performance considerations -4. Security concerns -5. Test coverage - -## Instructions - -1. Read the target files using Read tool -2. Search for patterns using Grep -3. Find related files using Glob -4. Provide detailed feedback on code quality -``` - -### Multi-file Skill - -``` -pdf-processing/ -├── SKILL.md -├── FORMS.md -├── REFERENCE.md -└── scripts/ - ├── fill_form.py - └── validate.py -``` - -**SKILL.md**: - -````yaml theme={null} ---- -name: pdf-processing -description: Extract text, fill forms, merge PDFs. Use when working with PDF files, forms, or document extraction. Requires pypdf and pdfplumber packages. ---- - -# PDF Processing - -## Quick start - -Extract text: -```python -import pdfplumber -with pdfplumber.open("doc.pdf") as pdf: - text = pdf.pages[0].extract_text() -``` - -For form filling, see [FORMS.md](FORMS.md). -For detailed API reference, see [REFERENCE.md](REFERENCE.md). - -## Requirements - -Packages must be installed in your environment: -```bash -pip install pypdf pdfplumber -``` -```` - - - List required packages in the description. Packages must be installed in your environment before Claude can use them. - - -Claude loads additional files only when needed. - -## Next steps - - - - Write Skills that Claude can use effectively - - - - Learn how Skills work across Claude products - - - - Use Skills programmatically with TypeScript and Python - - - - Create your first Skill - - diff --git a/claude-docs/hooks.md b/claude-docs/hooks.md deleted file mode 100644 index a8b9265..0000000 --- a/claude-docs/hooks.md +++ /dev/null @@ -1,892 +0,0 @@ -# Hooks reference - -> This page provides reference documentation for implementing hooks in Claude Code. - - - For a quickstart guide with examples, see [Get started with Claude Code hooks](/en/docs/claude-code/hooks-guide). - - -## Configuration - -Claude Code hooks are configured in your [settings files](/en/docs/claude-code/settings): - -* `~/.claude/settings.json` - User settings -* `.claude/settings.json` - Project settings -* `.claude/settings.local.json` - Local project settings (not committed) -* Enterprise managed policy settings - -### Structure - -Hooks are organized by matchers, where each matcher can have multiple hooks: - -```json theme={null} -{ - "hooks": { - "EventName": [ - { - "matcher": "ToolPattern", - "hooks": [ - { - "type": "command", - "command": "your-command-here" - } - ] - } - ] - } -} -``` - -* **matcher**: Pattern to match tool names, case-sensitive (only applicable for - `PreToolUse` and `PostToolUse`) - * Simple strings match exactly: `Write` matches only the Write tool - * Supports regex: `Edit|Write` or `Notebook.*` - * Use `*` to match all tools. You can also use empty string (`""`) or leave - `matcher` blank. -* **hooks**: Array of commands to execute when the pattern matches - * `type`: Currently only `"command"` is supported - * `command`: The bash command to execute (can use `$CLAUDE_PROJECT_DIR` - environment variable) - * `timeout`: (Optional) How long a command should run, in seconds, before - canceling that specific command. - -For events like `UserPromptSubmit`, `Notification`, `Stop`, and `SubagentStop` -that don't use matchers, you can omit the matcher field: - -```json theme={null} -{ - "hooks": { - "UserPromptSubmit": [ - { - "hooks": [ - { - "type": "command", - "command": "/path/to/prompt-validator.py" - } - ] - } - ] - } -} -``` - -### Project-Specific Hook Scripts - -You can use the environment variable `CLAUDE_PROJECT_DIR` (only available when -Claude Code spawns the hook command) to reference scripts stored in your project, -ensuring they work regardless of Claude's current directory: - -```json theme={null} -{ - "hooks": { - "PostToolUse": [ - { - "matcher": "Write|Edit", - "hooks": [ - { - "type": "command", - "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh" - } - ] - } - ] - } -} -``` - -### Plugin hooks - -[Plugins](/en/docs/claude-code/plugins) can provide hooks that integrate seamlessly with your user and project hooks. Plugin hooks are automatically merged with your configuration when plugins are enabled. - -**How plugin hooks work**: - -* Plugin hooks are defined in the plugin's `hooks/hooks.json` file or in a file given by a custom path to the `hooks` field. -* When a plugin is enabled, its hooks are merged with user and project hooks -* Multiple hooks from different sources can respond to the same event -* Plugin hooks use the `${CLAUDE_PLUGIN_ROOT}` environment variable to reference plugin files - -**Example plugin hook configuration**: - -```json theme={null} -{ - "description": "Automatic code formatting", - "hooks": { - "PostToolUse": [ - { - "matcher": "Write|Edit", - "hooks": [ - { - "type": "command", - "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh", - "timeout": 30 - } - ] - } - ] - } -} -``` - - - Plugin hooks use the same format as regular hooks with an optional `description` field to explain the hook's purpose. - - - - Plugin hooks run alongside your custom hooks. If multiple hooks match an event, they all execute in parallel. - - -**Environment variables for plugins**: - -* `${CLAUDE_PLUGIN_ROOT}`: Absolute path to the plugin directory -* `${CLAUDE_PROJECT_DIR}`: Project root directory (same as for project hooks) -* All standard environment variables are available - -See the [plugin components reference](/en/docs/claude-code/plugins-reference#hooks) for details on creating plugin hooks. - -## Hook Events - -### PreToolUse - -Runs after Claude creates tool parameters and before processing the tool call. - -**Common matchers:** - -* `Task` - Subagent tasks (see [subagents documentation](/en/docs/claude-code/sub-agents)) -* `Bash` - Shell commands -* `Glob` - File pattern matching -* `Grep` - Content search -* `Read` - File reading -* `Edit` - File editing -* `Write` - File writing -* `WebFetch`, `WebSearch` - Web operations - -### PostToolUse - -Runs immediately after a tool completes successfully. - -Recognizes the same matcher values as PreToolUse. - -### Notification - -Runs when Claude Code sends notifications. Notifications are sent when: - -1. Claude needs your permission to use a tool. Example: "Claude needs your - permission to use Bash" -2. The prompt input has been idle for at least 60 seconds. "Claude is waiting - for your input" - -### UserPromptSubmit - -Runs when the user submits a prompt, before Claude processes it. This allows you -to add additional context based on the prompt/conversation, validate prompts, or -block certain types of prompts. - -### Stop - -Runs when the main Claude Code agent has finished responding. Does not run if -the stoppage occurred due to a user interrupt. - -### SubagentStop - -Runs when a Claude Code subagent (Task tool call) has finished responding. - -### PreCompact - -Runs before Claude Code is about to run a compact operation. - -**Matchers:** - -* `manual` - Invoked from `/compact` -* `auto` - Invoked from auto-compact (due to full context window) - -### SessionStart - -Runs when Claude Code starts a new session or resumes an existing session (which -currently does start a new session under the hood). Useful for loading in -development context like existing issues or recent changes to your codebase, installing dependencies, or setting up environment variables. - -**Matchers:** - -* `startup` - Invoked from startup -* `resume` - Invoked from `--resume`, `--continue`, or `/resume` -* `clear` - Invoked from `/clear` -* `compact` - Invoked from auto or manual compact. - -#### Persisting environment variables - -SessionStart hooks have access to the `CLAUDE_ENV_FILE` environment variable, which provides a file path where you can persist environment variables for subsequent bash commands. - -**Example: Setting individual environment variables** - -```bash theme={null} -#!/bin/bash - -if [ -n "$CLAUDE_ENV_FILE" ]; then - echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE" - echo 'export API_KEY=your-api-key' >> "$CLAUDE_ENV_FILE" - echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE" -fi - -exit 0 -``` - -**Example: Persisting all environment changes from the hook** - -When your setup modifies the environment (e.g., `nvm use`), capture and persist all changes by diffing the environment: - -```bash theme={null} -#!/bin/bash - -ENV_BEFORE=$(export -p | sort) - -# Run your setup commands that modify the environment -source ~/.nvm/nvm.sh -nvm use 20 - -if [ -n "$CLAUDE_ENV_FILE" ]; then - ENV_AFTER=$(export -p | sort) - comm -13 <(echo "$ENV_BEFORE") <(echo "$ENV_AFTER") >> "$CLAUDE_ENV_FILE" -fi - -exit 0 -``` - -Any variables written to this file will be available in all subsequent bash commands that Claude Code executes during the session. - - - `CLAUDE_ENV_FILE` is only available for SessionStart hooks. Other hook types do not have access to this variable. - - -### SessionEnd - -Runs when a Claude Code session ends. Useful for cleanup tasks, logging session -statistics, or saving session state. - -The `reason` field in the hook input will be one of: - -* `clear` - Session cleared with /clear command -* `logout` - User logged out -* `prompt_input_exit` - User exited while prompt input was visible -* `other` - Other exit reasons - -## Hook Input - -Hooks receive JSON data via stdin containing session information and -event-specific data: - -```typescript theme={null} -{ - // Common fields - session_id: string - transcript_path: string // Path to conversation JSON - cwd: string // The current working directory when the hook is invoked - permission_mode: string // Current permission mode: "default", "plan", "acceptEdits", or "bypassPermissions" - - // Event-specific fields - hook_event_name: string - ... -} -``` - -### PreToolUse Input - -The exact schema for `tool_input` depends on the tool. - -```json theme={null} -{ - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "PreToolUse", - "tool_name": "Write", - "tool_input": { - "file_path": "/path/to/file.txt", - "content": "file content" - } -} -``` - -### PostToolUse Input - -The exact schema for `tool_input` and `tool_response` depends on the tool. - -```json theme={null} -{ - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "PostToolUse", - "tool_name": "Write", - "tool_input": { - "file_path": "/path/to/file.txt", - "content": "file content" - }, - "tool_response": { - "filePath": "/path/to/file.txt", - "success": true - } -} -``` - -### Notification Input - -```json theme={null} -{ - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "Notification", - "message": "Task completed successfully" -} -``` - -### UserPromptSubmit Input - -```json theme={null} -{ - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "UserPromptSubmit", - "prompt": "Write a function to calculate the factorial of a number" -} -``` - -### Stop and SubagentStop Input - -`stop_hook_active` is true when Claude Code is already continuing as a result of -a stop hook. Check this value or process the transcript to prevent Claude Code -from running indefinitely. - -```json theme={null} -{ - "session_id": "abc123", - "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "permission_mode": "default", - "hook_event_name": "Stop", - "stop_hook_active": true -} -``` - -### PreCompact Input - -For `manual`, `custom_instructions` comes from what the user passes into -`/compact`. For `auto`, `custom_instructions` is empty. - -```json theme={null} -{ - "session_id": "abc123", - "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "permission_mode": "default", - "hook_event_name": "PreCompact", - "trigger": "manual", - "custom_instructions": "" -} -``` - -### SessionStart Input - -```json theme={null} -{ - "session_id": "abc123", - "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "permission_mode": "default", - "hook_event_name": "SessionStart", - "source": "startup" -} -``` - -### SessionEnd Input - -```json theme={null} -{ - "session_id": "abc123", - "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "SessionEnd", - "reason": "exit" -} -``` - -## Hook Output - -There are two ways for hooks to return output back to Claude Code. The output -communicates whether to block and any feedback that should be shown to Claude -and the user. - -### Simple: Exit Code - -Hooks communicate status through exit codes, stdout, and stderr: - -* **Exit code 0**: Success. `stdout` is shown to the user in transcript mode - (CTRL-R), except for `UserPromptSubmit` and `SessionStart`, where stdout is - added to the context. -* **Exit code 2**: Blocking error. `stderr` is fed back to Claude to process - automatically. See per-hook-event behavior below. -* **Other exit codes**: Non-blocking error. `stderr` is shown to the user and - execution continues. - - - Reminder: Claude Code does not see stdout if the exit code is 0, except for - the `UserPromptSubmit` hook where stdout is injected as context. - - -#### Exit Code 2 Behavior - -| Hook Event | Behavior | -| ------------------ | ------------------------------------------------------------------ | -| `PreToolUse` | Blocks the tool call, shows stderr to Claude | -| `PostToolUse` | Shows stderr to Claude (tool already ran) | -| `Notification` | N/A, shows stderr to user only | -| `UserPromptSubmit` | Blocks prompt processing, erases prompt, shows stderr to user only | -| `Stop` | Blocks stoppage, shows stderr to Claude | -| `SubagentStop` | Blocks stoppage, shows stderr to Claude subagent | -| `PreCompact` | N/A, shows stderr to user only | -| `SessionStart` | N/A, shows stderr to user only | -| `SessionEnd` | N/A, shows stderr to user only | - -### Advanced: JSON Output - -Hooks can return structured JSON in `stdout` for more sophisticated control: - -#### Common JSON Fields - -All hook types can include these optional fields: - -```json theme={null} -{ - "continue": true, // Whether Claude should continue after hook execution (default: true) - "stopReason": "string", // Message shown when continue is false - - "suppressOutput": true, // Hide stdout from transcript mode (default: false) - "systemMessage": "string" // Optional warning message shown to the user -} -``` - -If `continue` is false, Claude stops processing after the hooks run. - -* For `PreToolUse`, this is different from `"permissionDecision": "deny"`, which - only blocks a specific tool call and provides automatic feedback to Claude. -* For `PostToolUse`, this is different from `"decision": "block"`, which - provides automated feedback to Claude. -* For `UserPromptSubmit`, this prevents the prompt from being processed. -* For `Stop` and `SubagentStop`, this takes precedence over any - `"decision": "block"` output. -* In all cases, `"continue" = false` takes precedence over any - `"decision": "block"` output. - -`stopReason` accompanies `continue` with a reason shown to the user, not shown -to Claude. - -#### `PreToolUse` Decision Control - -`PreToolUse` hooks can control whether a tool call proceeds. - -* `"allow"` bypasses the permission system. `permissionDecisionReason` is shown - to the user but not to Claude. -* `"deny"` prevents the tool call from executing. `permissionDecisionReason` is - shown to Claude. -* `"ask"` asks the user to confirm the tool call in the UI. - `permissionDecisionReason` is shown to the user but not to Claude. - -```json theme={null} -{ - "hookSpecificOutput": { - "hookEventName": "PreToolUse", - "permissionDecision": "allow" | "deny" | "ask", - "permissionDecisionReason": "My reason here" - } -} -``` - - - The `decision` and `reason` fields are deprecated for PreToolUse hooks. - Use `hookSpecificOutput.permissionDecision` and - `hookSpecificOutput.permissionDecisionReason` instead. The deprecated fields - `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively. - - -#### `PostToolUse` Decision Control - -`PostToolUse` hooks can provide feedback to Claude after tool execution. - -* `"block"` automatically prompts Claude with `reason`. -* `undefined` does nothing. `reason` is ignored. -* `"hookSpecificOutput.additionalContext"` adds context for Claude to consider. - -```json theme={null} -{ - "decision": "block" | undefined, - "reason": "Explanation for decision", - "hookSpecificOutput": { - "hookEventName": "PostToolUse", - "additionalContext": "Additional information for Claude" - } -} -``` - -#### `UserPromptSubmit` Decision Control - -`UserPromptSubmit` hooks can control whether a user prompt is processed. - -* `"block"` prevents the prompt from being processed. The submitted prompt is - erased from context. `"reason"` is shown to the user but not added to context. -* `undefined` allows the prompt to proceed normally. `"reason"` is ignored. -* `"hookSpecificOutput.additionalContext"` adds the string to the context if not - blocked. - -```json theme={null} -{ - "decision": "block" | undefined, - "reason": "Explanation for decision", - "hookSpecificOutput": { - "hookEventName": "UserPromptSubmit", - "additionalContext": "My additional context here" - } -} -``` - -#### `Stop`/`SubagentStop` Decision Control - -`Stop` and `SubagentStop` hooks can control whether Claude must continue. - -* `"block"` prevents Claude from stopping. You must populate `reason` for Claude - to know how to proceed. -* `undefined` allows Claude to stop. `reason` is ignored. - -```json theme={null} -{ - "decision": "block" | undefined, - "reason": "Must be provided when Claude is blocked from stopping" -} -``` - -#### `SessionStart` Decision Control - -`SessionStart` hooks allow you to load in context at the start of a session. - -* `"hookSpecificOutput.additionalContext"` adds the string to the context. -* Multiple hooks' `additionalContext` values are concatenated. - -```json theme={null} -{ - "hookSpecificOutput": { - "hookEventName": "SessionStart", - "additionalContext": "My additional context here" - } -} -``` - -#### `SessionEnd` Decision Control - -`SessionEnd` hooks run when a session ends. They cannot block session termination -but can perform cleanup tasks. - -#### Exit Code Example: Bash Command Validation - -```python theme={null} -#!/usr/bin/env python3 -import json -import re -import sys - -# Define validation rules as a list of (regex pattern, message) tuples -VALIDATION_RULES = [ - ( - r"\bgrep\b(?!.*\|)", - "Use 'rg' (ripgrep) instead of 'grep' for better performance and features", - ), - ( - r"\bfind\s+\S+\s+-name\b", - "Use 'rg --files | rg pattern' or 'rg --files -g pattern' instead of 'find -name' for better performance", - ), -] - - -def validate_command(command: str) -> list[str]: - issues = [] - for pattern, message in VALIDATION_RULES: - if re.search(pattern, command): - issues.append(message) - return issues - - -try: - input_data = json.load(sys.stdin) -except json.JSONDecodeError as e: - print(f"Error: Invalid JSON input: {e}", file=sys.stderr) - sys.exit(1) - -tool_name = input_data.get("tool_name", "") -tool_input = input_data.get("tool_input", {}) -command = tool_input.get("command", "") - -if tool_name != "Bash" or not command: - sys.exit(1) - -# Validate the command -issues = validate_command(command) - -if issues: - for message in issues: - print(f"• {message}", file=sys.stderr) - # Exit code 2 blocks tool call and shows stderr to Claude - sys.exit(2) -``` - -#### JSON Output Example: UserPromptSubmit to Add Context and Validation - - - For `UserPromptSubmit` hooks, you can inject context using either method: - - * Exit code 0 with stdout: Claude sees the context (special case for `UserPromptSubmit`) - * JSON output: Provides more control over the behavior - - -```python theme={null} -#!/usr/bin/env python3 -import json -import sys -import re -import datetime - -# Load input from stdin -try: - input_data = json.load(sys.stdin) -except json.JSONDecodeError as e: - print(f"Error: Invalid JSON input: {e}", file=sys.stderr) - sys.exit(1) - -prompt = input_data.get("prompt", "") - -# Check for sensitive patterns -sensitive_patterns = [ - (r"(?i)\b(password|secret|key|token)\s*[:=]", "Prompt contains potential secrets"), -] - -for pattern, message in sensitive_patterns: - if re.search(pattern, prompt): - # Use JSON output to block with a specific reason - output = { - "decision": "block", - "reason": f"Security policy violation: {message}. Please rephrase your request without sensitive information." - } - print(json.dumps(output)) - sys.exit(0) - -# Add current time to context -context = f"Current time: {datetime.datetime.now()}" -print(context) - -""" -The following is also equivalent: -print(json.dumps({ - "hookSpecificOutput": { - "hookEventName": "UserPromptSubmit", - "additionalContext": context, - }, -})) -""" - -# Allow the prompt to proceed with the additional context -sys.exit(0) -``` - -#### JSON Output Example: PreToolUse with Approval - -```python theme={null} -#!/usr/bin/env python3 -import json -import sys - -# Load input from stdin -try: - input_data = json.load(sys.stdin) -except json.JSONDecodeError as e: - print(f"Error: Invalid JSON input: {e}", file=sys.stderr) - sys.exit(1) - -tool_name = input_data.get("tool_name", "") -tool_input = input_data.get("tool_input", {}) - -# Example: Auto-approve file reads for documentation files -if tool_name == "Read": - file_path = tool_input.get("file_path", "") - if file_path.endswith((".md", ".mdx", ".txt", ".json")): - # Use JSON output to auto-approve the tool call - output = { - "decision": "approve", - "reason": "Documentation file auto-approved", - "suppressOutput": True # Don't show in transcript mode - } - print(json.dumps(output)) - sys.exit(0) - -# For other cases, let the normal permission flow proceed -sys.exit(0) -``` - -## Working with MCP Tools - -Claude Code hooks work seamlessly with -[Model Context Protocol (MCP) tools](/en/docs/claude-code/mcp). When MCP servers -provide tools, they appear with a special naming pattern that you can match in -your hooks. - -### MCP Tool Naming - -MCP tools follow the pattern `mcp____`, for example: - -* `mcp__memory__create_entities` - Memory server's create entities tool -* `mcp__filesystem__read_file` - Filesystem server's read file tool -* `mcp__github__search_repositories` - GitHub server's search tool - -### Configuring Hooks for MCP Tools - -You can target specific MCP tools or entire MCP servers: - -```json theme={null} -{ - "hooks": { - "PreToolUse": [ - { - "matcher": "mcp__memory__.*", - "hooks": [ - { - "type": "command", - "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log" - } - ] - }, - { - "matcher": "mcp__.*__write.*", - "hooks": [ - { - "type": "command", - "command": "/home/user/scripts/validate-mcp-write.py" - } - ] - } - ] - } -} -``` - -## Examples - - - For practical examples including code formatting, notifications, and file protection, see [More Examples](/en/docs/claude-code/hooks-guide#more-examples) in the get started guide. - - -## Security Considerations - -### Disclaimer - -**USE AT YOUR OWN RISK**: Claude Code hooks execute arbitrary shell commands on -your system automatically. By using hooks, you acknowledge that: - -* You are solely responsible for the commands you configure -* Hooks can modify, delete, or access any files your user account can access -* Malicious or poorly written hooks can cause data loss or system damage -* Anthropic provides no warranty and assumes no liability for any damages - resulting from hook usage -* You should thoroughly test hooks in a safe environment before production use - -Always review and understand any hook commands before adding them to your -configuration. - -### Security Best Practices - -Here are some key practices for writing more secure hooks: - -1. **Validate and sanitize inputs** - Never trust input data blindly -2. **Always quote shell variables** - Use `"$VAR"` not `$VAR` -3. **Block path traversal** - Check for `..` in file paths -4. **Use absolute paths** - Specify full paths for scripts (use - "\$CLAUDE\_PROJECT\_DIR" for the project path) -5. **Skip sensitive files** - Avoid `.env`, `.git/`, keys, etc. - -### Configuration Safety - -Direct edits to hooks in settings files don't take effect immediately. Claude -Code: - -1. Captures a snapshot of hooks at startup -2. Uses this snapshot throughout the session -3. Warns if hooks are modified externally -4. Requires review in `/hooks` menu for changes to apply - -This prevents malicious hook modifications from affecting your current session. - -## Hook Execution Details - -* **Timeout**: 60-second execution limit by default, configurable per command. - * A timeout for an individual command does not affect the other commands. -* **Parallelization**: All matching hooks run in parallel -* **Deduplication**: Multiple identical hook commands are deduplicated automatically -* **Environment**: Runs in current directory with Claude Code's environment - * The `CLAUDE_PROJECT_DIR` environment variable is available and contains the - absolute path to the project root directory (where Claude Code was started) - * The `CLAUDE_CODE_REMOTE` environment variable indicates whether the hook is running in a remote (web) environment (`"true"`) or local CLI environment (not set or empty). Use this to run different logic based on execution context. -* **Input**: JSON via stdin -* **Output**: - * PreToolUse/PostToolUse/Stop/SubagentStop: Progress shown in transcript (Ctrl-R) - * Notification/SessionEnd: Logged to debug only (`--debug`) - * UserPromptSubmit/SessionStart: stdout added as context for Claude - -## Debugging - -### Basic Troubleshooting - -If your hooks aren't working: - -1. **Check configuration** - Run `/hooks` to see if your hook is registered -2. **Verify syntax** - Ensure your JSON settings are valid -3. **Test commands** - Run hook commands manually first -4. **Check permissions** - Make sure scripts are executable -5. **Review logs** - Use `claude --debug` to see hook execution details - -Common issues: - -* **Quotes not escaped** - Use `\"` inside JSON strings -* **Wrong matcher** - Check tool names match exactly (case-sensitive) -* **Command not found** - Use full paths for scripts - -### Advanced Debugging - -For complex hook issues: - -1. **Inspect hook execution** - Use `claude --debug` to see detailed hook - execution -2. **Validate JSON schemas** - Test hook input/output with external tools -3. **Check environment variables** - Verify Claude Code's environment is correct -4. **Test edge cases** - Try hooks with unusual file paths or inputs -5. **Monitor system resources** - Check for resource exhaustion during hook - execution -6. **Use structured logging** - Implement logging in your hook scripts - -### Debug Output Example - -Use `claude --debug` to see hook execution details: - -``` -[DEBUG] Executing hooks for PostToolUse:Write -[DEBUG] Getting matching hook commands for PostToolUse with query: Write -[DEBUG] Found 1 hook matchers in settings -[DEBUG] Matched 1 hooks for query "Write" -[DEBUG] Found 1 hook commands to execute -[DEBUG] Executing hook command: with timeout 60000ms -[DEBUG] Hook command completed with status 0: -``` - -Progress messages appear in transcript mode (Ctrl-R) showing: - -* Which hook is running -* Command being executed -* Success/failure status -* Output or error messages diff --git a/claude-docs/plugins.md b/claude-docs/plugins.md deleted file mode 100644 index 5159436..0000000 --- a/claude-docs/plugins.md +++ /dev/null @@ -1,392 +0,0 @@ -# Plugins - -> Extend Claude Code with custom commands, agents, hooks, Skills, and MCP servers through the plugin system. - - - For complete technical specifications and schemas, see [Plugins reference](/en/docs/claude-code/plugins-reference). For marketplace management, see [Plugin marketplaces](/en/docs/claude-code/plugin-marketplaces). - - -Plugins let you extend Claude Code with custom functionality that can be shared across projects and teams. Install plugins from [marketplaces](/en/docs/claude-code/plugin-marketplaces) to add pre-built commands, agents, hooks, Skills, and MCP servers, or create your own to automate your workflows. - -## Quickstart - -Let's create a simple greeting plugin to get you familiar with the plugin system. We'll build a working plugin that adds a custom command, test it locally, and understand the core concepts. - -### Prerequisites - -* Claude Code installed on your machine -* Basic familiarity with command-line tools - -### Create your first plugin - - - - ```bash theme={null} - mkdir test-marketplace - cd test-marketplace - ``` - - - - ```bash theme={null} - mkdir my-first-plugin - cd my-first-plugin - ``` - - - - ```bash Create .claude-plugin/plugin.json theme={null} - mkdir .claude-plugin - cat > .claude-plugin/plugin.json << 'EOF' - { - "name": "my-first-plugin", - "description": "A simple greeting plugin to learn the basics", - "version": "1.0.0", - "author": { - "name": "Your Name" - } - } - EOF - ``` - - - - ```bash Create commands/hello.md theme={null} - mkdir commands - cat > commands/hello.md << 'EOF' - --- - description: Greet the user with a personalized message - --- - - # Hello Command - - Greet the user warmly and ask how you can help them today. Make the greeting personal and encouraging. - EOF - ``` - - - - ```bash Create marketplace.json theme={null} - cd .. - mkdir .claude-plugin - cat > .claude-plugin/marketplace.json << 'EOF' - { - "name": "test-marketplace", - "owner": { - "name": "Test User" - }, - "plugins": [ - { - "name": "my-first-plugin", - "source": "./my-first-plugin", - "description": "My first test plugin" - } - ] - } - EOF - ``` - - - - ```bash Start Claude Code from parent directory theme={null} - cd .. - claude - ``` - - ```shell Add the test marketplace theme={null} - /plugin marketplace add ./test-marketplace - ``` - - ```shell Install your plugin theme={null} - /plugin install my-first-plugin@test-marketplace - ``` - - Select "Install now". You'll then need to restart Claude Code in order to use the new plugin. - - ```shell Try your new command theme={null} - /hello - ``` - - You'll see Claude use your greeting command! Check `/help` to see your new command listed. - - - -You've successfully created and tested a plugin with these key components: - -* **Plugin manifest** (`.claude-plugin/plugin.json`) - Describes your plugin's metadata -* **Commands directory** (`commands/`) - Contains your custom slash commands -* **Test marketplace** - Allows you to test your plugin locally - -### Plugin structure overview - -Your plugin follows this basic structure: - -``` -my-first-plugin/ -├── .claude-plugin/ -│ └── plugin.json # Plugin metadata -├── commands/ # Custom slash commands (optional) -│ └── hello.md -├── agents/ # Custom agents (optional) -│ └── helper.md -├── skills/ # Agent Skills (optional) -│ └── my-skill/ -│ └── SKILL.md -└── hooks/ # Event handlers (optional) - └── hooks.json -``` - -**Additional components you can add:** - -* **Commands**: Create markdown files in `commands/` directory -* **Agents**: Create agent definitions in `agents/` directory -* **Skills**: Create `SKILL.md` files in `skills/` directory -* **Hooks**: Create `hooks/hooks.json` for event handling -* **MCP servers**: Create `.mcp.json` for external tool integration - - - **Next steps**: Ready to add more features? Jump to [Develop more complex plugins](#develop-more-complex-plugins) to add agents, hooks, and MCP servers. For complete technical specifications of all plugin components, see [Plugins reference](/en/docs/claude-code/plugins-reference). - - -*** - -## Install and manage plugins - -Learn how to discover, install, and manage plugins to extend your Claude Code capabilities. - -### Prerequisites - -* Claude Code installed and running -* Basic familiarity with command-line interfaces - -### Add marketplaces - -Marketplaces are catalogs of available plugins. Add them to discover and install plugins: - -```shell Add a marketplace theme={null} -/plugin marketplace add your-org/claude-plugins -``` - -```shell Browse available plugins theme={null} -/plugin -``` - -For detailed marketplace management including Git repositories, local development, and team distribution, see [Plugin marketplaces](/en/docs/claude-code/plugin-marketplaces). - -### Install plugins - -#### Via interactive menu (recommended for discovery) - -```shell Open the plugin management interface theme={null} -/plugin -``` - -Select "Browse Plugins" to see available options with descriptions, features, and installation options. - -#### Via direct commands (for quick installation) - -```shell Install a specific plugin theme={null} -/plugin install formatter@your-org -``` - -```shell Enable a disabled plugin theme={null} -/plugin enable plugin-name@marketplace-name -``` - -```shell Disable without uninstalling theme={null} -/plugin disable plugin-name@marketplace-name -``` - -```shell Completely remove a plugin theme={null} -/plugin uninstall plugin-name@marketplace-name -``` - -### Verify installation - -After installing a plugin: - -1. **Check available commands**: Run `/help` to see new commands -2. **Test plugin features**: Try the plugin's commands and features -3. **Review plugin details**: Use `/plugin` → "Manage Plugins" to see what the plugin provides - -## Set up team plugin workflows - -Configure plugins at the repository level to ensure consistent tooling across your team. When team members trust your repository folder, Claude Code automatically installs specified marketplaces and plugins. - -**To set up team plugins:** - -1. Add marketplace and plugin configuration to your repository's `.claude/settings.json` -2. Team members trust the repository folder -3. Plugins install automatically for all team members - -For complete instructions including configuration examples, marketplace setup, and rollout best practices, see [Configure team marketplaces](/en/docs/claude-code/plugin-marketplaces#how-to-configure-team-marketplaces). - -*** - -## Develop more complex plugins - -Once you're comfortable with basic plugins, you can create more sophisticated extensions. - -### Add Skills to your plugin - -Plugins can include [Agent Skills](/en/docs/claude-code/skills) to extend Claude's capabilities. Skills are model-invoked—Claude autonomously uses them based on the task context. - -To add Skills to your plugin, create a `skills/` directory at your plugin root and add Skill folders with `SKILL.md` files. Plugin Skills are automatically available when the plugin is installed. - -For complete Skill authoring guidance, see [Agent Skills](/en/docs/claude-code/skills). - -### Organize complex plugins - -For plugins with many components, organize your directory structure by functionality. For complete directory layouts and organization patterns, see [Plugin directory structure](/en/docs/claude-code/plugins-reference#plugin-directory-structure). - -### Test your plugins locally - -When developing plugins, use a local marketplace to test changes iteratively. This workflow builds on the quickstart pattern and works for plugins of any complexity. - - - - Organize your plugin and marketplace for testing: - - ```bash Create directory structure theme={null} - mkdir dev-marketplace - cd dev-marketplace - mkdir my-plugin - ``` - - This creates: - - ``` - dev-marketplace/ - ├── .claude-plugin/marketplace.json (you'll create this) - └── my-plugin/ (your plugin under development) - ├── .claude-plugin/plugin.json - ├── commands/ - ├── agents/ - └── hooks/ - ``` - - - - ```bash Create marketplace.json theme={null} - mkdir .claude-plugin - cat > .claude-plugin/marketplace.json << 'EOF' - { - "name": "dev-marketplace", - "owner": { - "name": "Developer" - }, - "plugins": [ - { - "name": "my-plugin", - "source": "./my-plugin", - "description": "Plugin under development" - } - ] - } - EOF - ``` - - - - ```bash Start Claude Code from parent directory theme={null} - cd .. - claude - ``` - - ```shell Add your development marketplace theme={null} - /plugin marketplace add ./dev-marketplace - ``` - - ```shell Install your plugin theme={null} - /plugin install my-plugin@dev-marketplace - ``` - - Test your plugin components: - - * Try your commands with `/command-name` - * Check that agents appear in `/agents` - * Verify hooks work as expected - - - - After making changes to your plugin code: - - ```shell Uninstall the current version theme={null} - /plugin uninstall my-plugin@dev-marketplace - ``` - - ```shell Reinstall to test changes theme={null} - /plugin install my-plugin@dev-marketplace - ``` - - Repeat this cycle as you develop and refine your plugin. - - - - - **For multiple plugins**: Organize plugins in subdirectories like `./plugins/plugin-name` and update your marketplace.json accordingly. See [Plugin sources](/en/docs/claude-code/plugin-marketplaces#plugin-sources) for organization patterns. - - -### Debug plugin issues - -If your plugin isn't working as expected: - -1. **Check the structure**: Ensure your directories are at the plugin root, not inside `.claude-plugin/` -2. **Test components individually**: Check each command, agent, and hook separately -3. **Use validation and debugging tools**: See [Debugging and development tools](/en/docs/claude-code/plugins-reference#debugging-and-development-tools) for CLI commands and troubleshooting techniques - -### Share your plugins - -When your plugin is ready to share: - -1. **Add documentation**: Include a README.md with installation and usage instructions -2. **Version your plugin**: Use semantic versioning in your `plugin.json` -3. **Create or use a marketplace**: Distribute through plugin marketplaces for easy installation -4. **Test with others**: Have team members test the plugin before wider distribution - - - For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/docs/claude-code/plugins-reference). - - -*** - -## Next steps - -Now that you understand Claude Code's plugin system, here are suggested paths for different goals: - -### For plugin users - -* **Discover plugins**: Browse community marketplaces for useful tools -* **Team adoption**: Set up repository-level plugins for your projects -* **Marketplace management**: Learn to manage multiple plugin sources -* **Advanced usage**: Explore plugin combinations and workflows - -### For plugin developers - -* **Create your first marketplace**: [Plugin marketplaces guide](/en/docs/claude-code/plugin-marketplaces) -* **Advanced components**: Dive deeper into specific plugin components: - * [Slash commands](/en/docs/claude-code/slash-commands) - Command development details - * [Subagents](/en/docs/claude-code/sub-agents) - Agent configuration and capabilities - * [Agent Skills](/en/docs/claude-code/skills) - Extend Claude's capabilities - * [Hooks](/en/docs/claude-code/hooks) - Event handling and automation - * [MCP](/en/docs/claude-code/mcp) - External tool integration -* **Distribution strategies**: Package and share your plugins effectively -* **Community contribution**: Consider contributing to community plugin collections - -### For team leads and administrators - -* **Repository configuration**: Set up automatic plugin installation for team projects -* **Plugin governance**: Establish guidelines for plugin approval and security review -* **Marketplace maintenance**: Create and maintain organization-specific plugin catalogs -* **Training and documentation**: Help team members adopt plugin workflows effectively - -## See also - -* [Plugin marketplaces](/en/docs/claude-code/plugin-marketplaces) - Creating and managing plugin catalogs -* [Slash commands](/en/docs/claude-code/slash-commands) - Understanding custom commands -* [Subagents](/en/docs/claude-code/sub-agents) - Creating and using specialized agents -* [Agent Skills](/en/docs/claude-code/skills) - Extend Claude's capabilities -* [Hooks](/en/docs/claude-code/hooks) - Automating workflows with event handlers -* [MCP](/en/docs/claude-code/mcp) - Connecting to external tools and services -* [Settings](/en/docs/claude-code/settings) - Configuration options for plugins - diff --git a/claude-docs/slash-commands.md b/claude-docs/slash-commands.md deleted file mode 100644 index 7a756b2..0000000 --- a/claude-docs/slash-commands.md +++ /dev/null @@ -1,490 +0,0 @@ -# Slash commands - -> Control Claude's behavior during an interactive session with slash commands. - -## Built-in slash commands - -| Command | Purpose | -| :------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------- | -| `/add-dir` | Add additional working directories | -| `/agents` | Manage custom AI subagents for specialized tasks | -| `/bug` | Report bugs (sends conversation to Anthropic) | -| `/clear` | Clear conversation history | -| `/compact [instructions]` | Compact conversation with optional focus instructions | -| `/config` | Open the Settings interface (Config tab) | -| `/cost` | Show token usage statistics (see [cost tracking guide](/en/docs/claude-code/costs#using-the-cost-command) for subscription-specific details) | -| `/doctor` | Checks the health of your Claude Code installation | -| `/help` | Get usage help | -| `/init` | Initialize project with CLAUDE.md guide | -| `/login` | Switch Anthropic accounts | -| `/logout` | Sign out from your Anthropic account | -| `/mcp` | Manage MCP server connections and OAuth authentication | -| `/memory` | Edit CLAUDE.md memory files | -| `/model` | Select or change the AI model | -| `/permissions` | View or update [permissions](/en/docs/claude-code/iam#configuring-permissions) | -| `/pr_comments` | View pull request comments | -| `/review` | Request code review | -| `/sandbox` | Enable sandboxed bash tool with filesystem and network isolation for safer, more autonomous execution | -| `/rewind` | Rewind the conversation and/or code | -| `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity | -| `/terminal-setup` | Install Shift+Enter key binding for newlines (iTerm2 and VSCode only) | -| `/usage` | Show plan usage limits and rate limit status (subscription plans only) | -| `/vim` | Enter vim mode for alternating insert and command modes | - -## Custom slash commands - -Custom slash commands allow you to define frequently-used prompts as Markdown files that Claude Code can execute. Commands are organized by scope (project-specific or personal) and support namespacing through directory structures. - -### Syntax - -``` -/ [arguments] -``` - -#### Parameters - -| Parameter | Description | -| :--------------- | :---------------------------------------------------------------- | -| `` | Name derived from the Markdown filename (without `.md` extension) | -| `[arguments]` | Optional arguments passed to the command | - -### Command types - -#### Project commands - -Commands stored in your repository and shared with your team. When listed in `/help`, these commands show "(project)" after their description. - -**Location**: `.claude/commands/` - -In the following example, we create the `/optimize` command: - -```bash theme={null} -# Create a project command -mkdir -p .claude/commands -echo "Analyze this code for performance issues and suggest optimizations:" > .claude/commands/optimize.md -``` - -#### Personal commands - -Commands available across all your projects. When listed in `/help`, these commands show "(user)" after their description. - -**Location**: `~/.claude/commands/` - -In the following example, we create the `/security-review` command: - -```bash theme={null} -# Create a personal command -mkdir -p ~/.claude/commands -echo "Review this code for security vulnerabilities:" > ~/.claude/commands/security-review.md -``` - -### Features - -#### Namespacing - -Organize commands in subdirectories. The subdirectories are used for organization and appear in the command description, but they do not affect the command name itself. The description will show whether the command comes from the project directory (`.claude/commands`) or the user-level directory (`~/.claude/commands`), along with the subdirectory name. - -Conflicts between user and project level commands are not supported. Otherwise, multiple commands with the same base file name can coexist. - -For example, a file at `.claude/commands/frontend/component.md` creates the command `/component` with description showing "(project:frontend)". -Meanwhile, a file at `~/.claude/commands/component.md` creates the command `/component` with description showing "(user)". - -#### Arguments - -Pass dynamic values to commands using argument placeholders: - -##### All arguments with `$ARGUMENTS` - -The `$ARGUMENTS` placeholder captures all arguments passed to the command: - -```bash theme={null} -# Command definition -echo 'Fix issue #$ARGUMENTS following our coding standards' > .claude/commands/fix-issue.md - -# Usage -> /fix-issue 123 high-priority -# $ARGUMENTS becomes: "123 high-priority" -``` - -##### Individual arguments with `$1`, `$2`, etc. - -Access specific arguments individually using positional parameters (similar to shell scripts): - -```bash theme={null} -# Command definition -echo 'Review PR #$1 with priority $2 and assign to $3' > .claude/commands/review-pr.md - -# Usage -> /review-pr 456 high alice -# $1 becomes "456", $2 becomes "high", $3 becomes "alice" -``` - -Use positional arguments when you need to: - -* Access arguments individually in different parts of your command -* Provide defaults for missing arguments -* Build more structured commands with specific parameter roles - -#### Bash command execution - -Execute bash commands before the slash command runs using the `!` prefix. The output is included in the command context. You *must* include `allowed-tools` with the `Bash` tool, but you can choose the specific bash commands to allow. - -For example: - -```markdown theme={null} ---- -allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*) -description: Create a git commit ---- - -## Context - -- Current git status: !`git status` -- Current git diff (staged and unstaged changes): !`git diff HEAD` -- Current branch: !`git branch --show-current` -- Recent commits: !`git log --oneline -10` - -## Your task - -Based on the above changes, create a single git commit. -``` - -#### File references - -Include file contents in commands using the `@` prefix to [reference files](/en/docs/claude-code/common-workflows#reference-files-and-directories). - -For example: - -```markdown theme={null} -# Reference a specific file - -Review the implementation in @src/utils/helpers.js - -# Reference multiple files - -Compare @src/old-version.js with @src/new-version.js -``` - -#### Thinking mode - -Slash commands can trigger extended thinking by including [extended thinking keywords](/en/docs/claude-code/common-workflows#use-extended-thinking). - -### Frontmatter - -Command files support frontmatter, useful for specifying metadata about the command: - -| Frontmatter | Purpose | Default | -| :------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------- | -| `allowed-tools` | List of tools the command can use | Inherits from the conversation | -| `argument-hint` | The arguments expected for the slash command. Example: `argument-hint: add [tagId] \| remove [tagId] \| list`. This hint is shown to the user when auto-completing the slash command. | None | -| `description` | Brief description of the command | Uses the first line from the prompt | -| `model` | Specific model string (see [Models overview](/en/docs/about-claude/models/overview)) | Inherits from the conversation | -| `disable-model-invocation` | Whether to prevent `SlashCommand` tool from calling this command | false | - -For example: - -```markdown theme={null} ---- -allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*) -argument-hint: [message] -description: Create a git commit -model: claude-3-5-haiku-20241022 ---- - -Create a git commit with message: $ARGUMENTS -``` - -Example using positional arguments: - -```markdown theme={null} ---- -argument-hint: [pr-number] [priority] [assignee] -description: Review pull request ---- - -Review PR #$1 with priority $2 and assign to $3. -Focus on security, performance, and code style. -``` - -## Plugin commands - -[Plugins](/en/docs/claude-code/plugins) can provide custom slash commands that integrate seamlessly with Claude Code. Plugin commands work exactly like user-defined commands but are distributed through [plugin marketplaces](/en/docs/claude-code/plugin-marketplaces). - -### How plugin commands work - -Plugin commands are: - -* **Namespaced**: Commands can use the format `/plugin-name:command-name` to avoid conflicts (plugin prefix is optional unless there are name collisions) -* **Automatically available**: Once a plugin is installed and enabled, its commands appear in `/help` -* **Fully integrated**: Support all command features (arguments, frontmatter, bash execution, file references) - -### Plugin command structure - -**Location**: `commands/` directory in plugin root - -**File format**: Markdown files with frontmatter - -**Basic command structure**: - -```markdown theme={null} ---- -description: Brief description of what the command does ---- - -# Command Name - -Detailed instructions for Claude on how to execute this command. -Include specific guidance on parameters, expected outcomes, and any special considerations. -``` - -**Advanced command features**: - -* **Arguments**: Use placeholders like `{arg1}` in command descriptions -* **Subdirectories**: Organize commands in subdirectories for namespacing -* **Bash integration**: Commands can execute shell scripts and programs -* **File references**: Commands can reference and modify project files - -### Invocation patterns - -```shell Direct command (when no conflicts) theme={null} -/command-name -``` - -```shell Plugin-prefixed (when needed for disambiguation) theme={null} -/plugin-name:command-name -``` - -```shell With arguments (if command supports them) theme={null} -/command-name arg1 arg2 -``` - -## MCP slash commands - -MCP servers can expose prompts as slash commands that become available in Claude Code. These commands are dynamically discovered from connected MCP servers. - -### Command format - -MCP commands follow the pattern: - -``` -/mcp____ [arguments] -``` - -### Features - -#### Dynamic discovery - -MCP commands are automatically available when: - -* An MCP server is connected and active -* The server exposes prompts through the MCP protocol -* The prompts are successfully retrieved during connection - -#### Arguments - -MCP prompts can accept arguments defined by the server: - -``` -# Without arguments -> /mcp__github__list_prs - -# With arguments -> /mcp__github__pr_review 456 -> /mcp__jira__create_issue "Bug title" high -``` - -#### Naming conventions - -* Server and prompt names are normalized -* Spaces and special characters become underscores -* Names are lowercased for consistency - -### Managing MCP connections - -Use the `/mcp` command to: - -* View all configured MCP servers -* Check connection status -* Authenticate with OAuth-enabled servers -* Clear authentication tokens -* View available tools and prompts from each server - -### MCP permissions and wildcards - -When configuring [permissions for MCP tools](/en/docs/claude-code/iam#tool-specific-permission-rules), note that **wildcards are not supported**: - -* ✅ **Correct**: `mcp__github` (approves ALL tools from the github server) -* ✅ **Correct**: `mcp__github__get_issue` (approves specific tool) -* ❌ **Incorrect**: `mcp__github__*` (wildcards not supported) - -To approve all tools from an MCP server, use just the server name: `mcp__servername`. To approve specific tools only, list each tool individually. - -## `SlashCommand` tool - -The `SlashCommand` tool allows Claude to execute [custom slash commands](/en/docs/claude-code/slash-commands#custom-slash-commands) programmatically -during a conversation. This gives Claude the ability to invoke custom commands -on your behalf when appropriate. - -To encourage Claude to trigger `SlashCommand` tool, your instructions (prompts, -CLAUDE.md, etc.) generally need to reference the command by name with its slash. - -Example: - -``` -> Run /write-unit-test when you are about to start writing tests. -``` - -This tool puts each available custom slash command's metadata into context up to the -character budget limit. You can use `/context` to monitor token usage and follow -the operations below to manage context. - -### `SlashCommand` tool supported commands - -`SlashCommand` tool only supports custom slash commands that: - -* Are user-defined. Built-in commands like `/compact` and `/init` are *not* supported. -* Have the `description` frontmatter field populated. We use the `description` in the context. - -For Claude Code versions >= 1.0.124, you can see which custom slash commands -`SlashCommand` tool can invoke by running `claude --debug` and triggering a query. - -### Disable `SlashCommand` tool - -To prevent Claude from executing any slash commands via the tool: - -```bash theme={null} -/permissions -# Add to deny rules: SlashCommand -``` - -This will also remove SlashCommand tool (and the slash command descriptions) from context. - -### Disable specific commands only - -To prevent a specific slash command from becoming available, add -`disable-model-invocation: true` to the slash command's frontmatter. - -This will also remove the command's metadata from context. - -### `SlashCommand` permission rules - -The permission rules support: - -* **Exact match**: `SlashCommand:/commit` (allows only `/commit` with no arguments) -* **Prefix match**: `SlashCommand:/review-pr:*` (allows `/review-pr` with any arguments) - -### Character budget limit - -The `SlashCommand` tool includes a character budget to limit the size of command -descriptions shown to Claude. This prevents token overflow when many commands -are available. - -The budget includes each custom slash command's name, args, and description. - -* **Default limit**: 15,000 characters -* **Custom limit**: Set via `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable - -When the character budget is exceeded, Claude will see only a subset of the -available commands. In `/context`, a warning will show with "M of N commands". - -## Skills vs slash commands - -**Slash commands** and **Agent Skills** serve different purposes in Claude Code: - -### Use slash commands for - -**Quick, frequently-used prompts**: - -* Simple prompt snippets you use often -* Quick reminders or templates -* Frequently-used instructions that fit in one file - -**Examples**: - -* `/review` → "Review this code for bugs and suggest improvements" -* `/explain` → "Explain this code in simple terms" -* `/optimize` → "Analyze this code for performance issues" - -### Use Skills for - -**Comprehensive capabilities with structure**: - -* Complex workflows with multiple steps -* Capabilities requiring scripts or utilities -* Knowledge organized across multiple files -* Team workflows you want to standardize - -**Examples**: - -* PDF processing Skill with form-filling scripts and validation -* Data analysis Skill with reference docs for different data types -* Documentation Skill with style guides and templates - -### Key differences - -| Aspect | Slash Commands | Agent Skills | -| -------------- | -------------------------------- | ----------------------------------- | -| **Complexity** | Simple prompts | Complex capabilities | -| **Structure** | Single .md file | Directory with SKILL.md + resources | -| **Discovery** | Explicit invocation (`/command`) | Automatic (based on context) | -| **Files** | One file only | Multiple files, scripts, templates | -| **Scope** | Project or personal | Project or personal | -| **Sharing** | Via git | Via git | - -### Example comparison - -**As a slash command**: - -```markdown theme={null} -# .claude/commands/review.md -Review this code for: -- Security vulnerabilities -- Performance issues -- Code style violations -``` - -Usage: `/review` (manual invocation) - -**As a Skill**: - -``` -.claude/skills/code-review/ -├── SKILL.md (overview and workflows) -├── SECURITY.md (security checklist) -├── PERFORMANCE.md (performance patterns) -├── STYLE.md (style guide reference) -└── scripts/ - └── run-linters.sh -``` - -Usage: "Can you review this code?" (automatic discovery) - -The Skill provides richer context, validation scripts, and organized reference material. - -### When to use each - -**Use slash commands**: - -* You invoke the same prompt repeatedly -* The prompt fits in a single file -* You want explicit control over when it runs - -**Use Skills**: - -* Claude should discover the capability automatically -* Multiple files or scripts are needed -* Complex workflows with validation steps -* Team needs standardized, detailed guidance - -Both slash commands and Skills can coexist. Use the approach that fits your needs. - -Learn more about [Agent Skills](/en/docs/claude-code/skills). - -## See also - -* [Plugins](/en/docs/claude-code/plugins) - Extend Claude Code with custom commands through plugins -* [Identity and Access Management](/en/docs/claude-code/iam) - Complete guide to permissions, including MCP tool permissions -* [Interactive mode](/en/docs/claude-code/interactive-mode) - Shortcuts, input modes, and interactive features -* [CLI reference](/en/docs/claude-code/cli-reference) - Command-line flags and options -* [Settings](/en/docs/claude-code/settings) - Configuration options -* [Memory management](/en/docs/claude-code/memory) - Managing Claude's memory across sessions diff --git a/claude-docs/subagents.md b/claude-docs/subagents.md deleted file mode 100644 index de2c37e..0000000 --- a/claude-docs/subagents.md +++ /dev/null @@ -1,387 +0,0 @@ -# Subagents - -> Create and use specialized AI subagents in Claude Code for task-specific workflows and improved context management. - -Custom subagents in Claude Code are specialized AI assistants that can be invoked to handle specific types of tasks. They enable more efficient problem-solving by providing task-specific configurations with customized system prompts, tools and a separate context window. - -## What are subagents? - -Subagents are pre-configured AI personalities that Claude Code can delegate tasks to. Each subagent: - -* Has a specific purpose and expertise area -* Uses its own context window separate from the main conversation -* Can be configured with specific tools it's allowed to use -* Includes a custom system prompt that guides its behavior - -When Claude Code encounters a task that matches a subagent's expertise, it can delegate that task to the specialized subagent, which works independently and returns results. - -## Key benefits - - - - Each subagent operates in its own context, preventing pollution of the main conversation and keeping it focused on high-level objectives. - - - - Subagents can be fine-tuned with detailed instructions for specific domains, leading to higher success rates on designated tasks. - - - - Once created, subagents can be used across different projects and shared with your team for consistent workflows. - - - - Each subagent can have different tool access levels, allowing you to limit powerful tools to specific subagent types. - - - -## Quick start - -To create your first subagent: - - - - Run the following command: - - ``` - /agents - ``` - - - - Choose whether to create a project-level or user-level subagent - - - - * **Recommended**: Generate with Claude first, then customize to make it yours - * Describe your subagent in detail and when it should be used - * Select the tools you want to grant access to (or leave blank to inherit all tools) - * The interface shows all available tools, making selection easy - * If you're generating with Claude, you can also edit the system prompt in your own editor by pressing `e` - - - - Your subagent is now available! Claude will use it automatically when appropriate, or you can invoke it explicitly: - - ``` - > Use the code-reviewer subagent to check my recent changes - ``` - - - -## Subagent configuration - -### File locations - -Subagents are stored as Markdown files with YAML frontmatter in two possible locations: - -| Type | Location | Scope | Priority | -| :-------------------- | :------------------ | :---------------------------- | :------- | -| **Project subagents** | `.claude/agents/` | Available in current project | Highest | -| **User subagents** | `~/.claude/agents/` | Available across all projects | Lower | - -When subagent names conflict, project-level subagents take precedence over user-level subagents. - -### Plugin agents - -[Plugins](/en/docs/claude-code/plugins) can provide custom subagents that integrate seamlessly with Claude Code. Plugin agents work identically to user-defined agents and appear in the `/agents` interface. - -**Plugin agent locations**: Plugins include agents in their `agents/` directory (or custom paths specified in the plugin manifest). - -**Using plugin agents**: - -* Plugin agents appear in `/agents` alongside your custom agents -* Can be invoked explicitly: "Use the code-reviewer agent from the security-plugin" -* Can be invoked automatically by Claude when appropriate -* Can be managed (viewed, inspected) through `/agents` interface - -See the [plugin components reference](/en/docs/claude-code/plugins-reference#agents) for details on creating plugin agents. - -### CLI-based configuration - -You can also define subagents dynamically using the `--agents` CLI flag, which accepts a JSON object: - -```bash theme={null} -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" - } -}' -``` - -**Priority**: CLI-defined subagents have lower priority than project-level subagents but higher priority than user-level subagents. - -**Use case**: This approach is useful for: - -* Quick testing of subagent configurations -* Session-specific subagents that don't need to be saved -* Automation scripts that need custom subagents -* Sharing subagent definitions in documentation or scripts - -For detailed information about the JSON format and all available options, see the [CLI reference documentation](/en/docs/claude-code/cli-reference#agents-flag-format). - -### File format - -Each subagent is defined in a Markdown file with this structure: - -```markdown theme={null} ---- -name: your-sub-agent-name -description: Description of when this subagent should be invoked -tools: tool1, tool2, tool3 # Optional - inherits all tools if omitted -model: sonnet # Optional - specify model alias or 'inherit' ---- - -Your subagent's system prompt goes here. This can be multiple paragraphs -and should clearly define the subagent's role, capabilities, and approach -to solving problems. - -Include specific instructions, best practices, and any constraints -the subagent should follow. -``` - -#### Configuration fields - -| Field | Required | Description | -| :------------ | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `name` | Yes | Unique identifier using lowercase letters and hyphens | -| `description` | Yes | Natural language description of the subagent's purpose | -| `tools` | No | Comma-separated list of specific tools. If omitted, inherits all tools from the main thread | -| `model` | No | Model to use for this subagent. Can be a model alias (`sonnet`, `opus`, `haiku`) or `'inherit'` to use the main conversation's model. If omitted, defaults to the [configured subagent model](/en/docs/claude-code/model-config) | - -### Model selection - -The `model` field allows you to control which [AI model](/en/docs/claude-code/model-config) the subagent uses: - -* **Model alias**: Use one of the available aliases: `sonnet`, `opus`, or `haiku` -* **`'inherit'`**: Use the same model as the main conversation (useful for consistency) -* **Omitted**: If not specified, uses the default model configured for subagents (`sonnet`) - - - Using `'inherit'` is particularly useful when you want your subagents to adapt to the model choice of the main conversation, ensuring consistent capabilities and response style throughout your session. - - -### Available tools - -Subagents can be granted access to any of Claude Code's internal tools. See the [tools documentation](/en/docs/claude-code/settings#tools-available-to-claude) for a complete list of available tools. - - - **Recommended:** Use the `/agents` command to modify tool access - it provides an interactive interface that lists all available tools, including any connected MCP server tools, making it easier to select the ones you need. - - -You have two options for configuring tools: - -* **Omit the `tools` field** to inherit all tools from the main thread (default), including MCP tools -* **Specify individual tools** as a comma-separated list for more granular control (can be edited manually or via `/agents`) - -**MCP Tools**: Subagents can access MCP tools from configured MCP servers. When the `tools` field is omitted, subagents inherit all MCP tools available to the main thread. - -## Managing subagents - -### Using the /agents command (Recommended) - -The `/agents` command provides a comprehensive interface for subagent management: - -``` -/agents -``` - -This opens an interactive menu where you can: - -* View all available subagents (built-in, user, and project) -* Create new subagents with guided setup -* Edit existing custom subagents, including their tool access -* Delete custom subagents -* See which subagents are active when duplicates exist -* **Easily manage tool permissions** with a complete list of available tools - -### Direct file management - -You can also manage subagents by working directly with their files: - -```bash theme={null} -# Create a project subagent -mkdir -p .claude/agents -echo '--- -name: test-runner -description: Use proactively to run tests and fix failures ---- - -You are a test automation expert. When you see code changes, proactively run the appropriate tests. If tests fail, analyze the failures and fix them while preserving the original test intent.' > .claude/agents/test-runner.md - -# Create a user subagent -mkdir -p ~/.claude/agents -# ... create subagent file -``` - -## Using subagents effectively - -### Automatic delegation - -Claude Code proactively delegates tasks based on: - -* The task description in your request -* The `description` field in subagent configurations -* Current context and available tools - - - To encourage more proactive subagent use, include phrases like "use PROACTIVELY" or "MUST BE USED" in your `description` field. - - -### Explicit invocation - -Request a specific subagent by mentioning it in your command: - -``` -> Use the test-runner subagent to fix failing tests -> Have the code-reviewer subagent look at my recent changes -> Ask the debugger subagent to investigate this error -``` - -## Example subagents - -### Code reviewer - -```markdown theme={null} ---- -name: code-reviewer -description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code. -tools: Read, Grep, Glob, Bash -model: inherit ---- - -You are a senior code reviewer ensuring high standards of code quality and security. - -When invoked: -1. Run git diff to see recent changes -2. Focus on modified files -3. Begin review immediately - -Review checklist: -- Code is simple and readable -- Functions and variables are well-named -- No duplicated code -- Proper error handling -- No exposed secrets or API keys -- Input validation implemented -- Good test coverage -- Performance considerations addressed - -Provide feedback organized by priority: -- Critical issues (must fix) -- Warnings (should fix) -- Suggestions (consider improving) - -Include specific examples of how to fix issues. -``` - -### Debugger - -```markdown theme={null} ---- -name: debugger -description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues. -tools: Read, Edit, Bash, Grep, Glob ---- - -You are an expert debugger specializing in root cause analysis. - -When invoked: -1. Capture error message and stack trace -2. Identify reproduction steps -3. Isolate the failure location -4. Implement minimal fix -5. Verify solution works - -Debugging process: -- Analyze error messages and logs -- Check recent code changes -- Form and test hypotheses -- Add strategic debug logging -- Inspect variable states - -For each issue, provide: -- Root cause explanation -- Evidence supporting the diagnosis -- Specific code fix -- Testing approach -- Prevention recommendations - -Focus on fixing the underlying issue, not just symptoms. -``` - -### Data scientist - -```markdown theme={null} ---- -name: data-scientist -description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries. -tools: Bash, Read, Write -model: sonnet ---- - -You are a data scientist specializing in SQL and BigQuery analysis. - -When invoked: -1. Understand the data analysis requirement -2. Write efficient SQL queries -3. Use BigQuery command line tools (bq) when appropriate -4. Analyze and summarize results -5. Present findings clearly - -Key practices: -- Write optimized SQL queries with proper filters -- Use appropriate aggregations and joins -- Include comments explaining complex logic -- Format results for readability -- Provide data-driven recommendations - -For each analysis: -- Explain the query approach -- Document any assumptions -- Highlight key findings -- Suggest next steps based on data - -Always ensure queries are efficient and cost-effective. -``` - -## Best practices - -* **Start with Claude-generated agents**: We highly recommend generating your initial subagent with Claude and then iterating on it to make it personally yours. This approach gives you the best results - a solid foundation that you can customize to your specific needs. - -* **Design focused subagents**: Create subagents with single, clear responsibilities rather than trying to make one subagent do everything. This improves performance and makes subagents more predictable. - -* **Write detailed prompts**: Include specific instructions, examples, and constraints in your system prompts. The more guidance you provide, the better the subagent will perform. - -* **Limit tool access**: Only grant tools that are necessary for the subagent's purpose. This improves security and helps the subagent focus on relevant actions. - -* **Version control**: Check project subagents into version control so your team can benefit from and improve them collaboratively. - -## Advanced usage - -### Chaining subagents - -For complex workflows, you can chain multiple subagents: - -``` -> First use the code-analyzer subagent to find performance issues, then use the optimizer subagent to fix them -``` - -### Dynamic subagent selection - -Claude Code intelligently selects subagents based on context. Make your `description` fields specific and action-oriented for best results. - -## Performance considerations - -* **Context efficiency**: Agents help preserve main context, enabling longer overall sessions -* **Latency**: Subagents start off with a clean slate each time they are invoked and may add latency as they gather context that they require to do their job effectively. - -## Related documentation - -* [Plugins](/en/docs/claude-code/plugins) - Extend Claude Code with custom agents through plugins -* [Slash commands](/en/docs/claude-code/slash-commands) - Learn about other built-in commands -* [Settings](/en/docs/claude-code/settings) - Configure Claude Code behavior -* [Hooks](/en/docs/claude-code/hooks) - Automate workflows with event handlers