
Claude Code Development
- 18 installs
- 3 repo stars
- Updated January 13, 2026
- shino369/claude-code-personal-workspace
Helps with ai & agent building tasks.
About
claude-code-development is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- claude-code-development
- AI & Agent Building
- AI-coding skill
Claude Code Development by the numbers
- 18 all-time installs (skills.sh)
- Ranked #10,710 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Jul 27, 2026 (Skillselion catalog sync)
npx skills add https://github.com/shino369/claude-code-personal-workspace --skill claude-code-developmentAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 18 |
|---|---|
| repo stars | ★ 3 |
| Last updated | January 13, 2026 |
| Repository | shino369/claude-code-personal-workspace ↗ |
What it does
Helps with ai & agent building tasks.
Files
Claude Code Development
Overview
This skill provides comprehensive guidance for creating and configuring Claude Code components following official best practices. Use this when working with .claude/ directory structure including agents, skills, commands, hooks, and MCP integrations.
Official Documentation
All official documentation references are maintained in docs/claude/README.md. Always consult these references for the latest standards and best practices:
- Claude Code Settings
- Claude Code Memory Management
- Claude Code Sub-agents Documentation
- Claude Code Skills Documentation
- Claude Code Slash Commands Documentation
- Claude Code Hooks Documentation
- Claude Code MCP Support
- Agent Skills Best Practices
When creating new components, fetch and review the relevant documentation using the WebFetch tool.
Quick Start
When to Use Which Component?
Use a Subagent when you need:
- Task isolation in a separate context
- Specialized model or tool restrictions
- Repeated complex workflows
Use a Skill when you need:
- Reusable knowledge that Claude lacks
- Domain-specific terminology or patterns
- Expert knowledge loaded into context
Use a Command when you need:
- User-invocable workflows
- Shortcuts for common tasks
- Structured argument handling
Use a Hook when you need:
- Automated actions on tool events
- Validation before operations
- Cleanup after operations
Quick Examples
Agent (specialized AI for focused tasks):
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Grep, GlobSkill (reusable knowledge package):
name: api-design-patterns
description: REST API design. Use when designing or reviewing APIs.Command (user-invocable workflow):
description: Review code changes
allowed-tools: Task(code-reviewer)See detailed guides: Agents | Skills | Commands
Component Types Overview
Subagents (.claude/agents/)
Specialized AI assistants that handle specific types of tasks in isolated contexts.
- File Format: Markdown with YAML frontmatter
- Location:
.claude/agents/[agent-name].md - Key Fields: name, description, tools, model, skills, permissionMode
See Agent Creation Guide for complete details.
Skills (.claude/skills/)
Reusable knowledge packages that can be loaded into conversations or subagents.
- File Format: Markdown with YAML frontmatter
- Location:
.claude/skills/[skill-name]/SKILL.md - Key Fields: name, description, allowed-tools, context
See Skills Creation Guide for complete details.
Slash Commands (.claude/commands/)
User-invocable prompts that provide reusable workflows.
- File Format: Markdown with YAML frontmatter
- Location:
.claude/commands/[command-name].md - Key Fields: description, argument-hint, allowed-tools
See Commands Creation Guide for complete details.
Hooks (.claude/hooks/)
Scripts that run automatically on tool events.
- Configuration: In
.claude/settings.jsonor component frontmatter - Hook Events: PreToolUse, PostToolUse, SubagentStart, SubagentStop, Stop
- Hook Types: command (shell), prompt (text injection)
See Hooks Reference Guide for complete details.
Directory Structure
Standard layout for a well-organized .claude/ directory:
.claude/
├── settings.json # Project-level configuration
├── agents/
│ ├── agent-name-1.md
│ └── agent-name-2.md
├── skills/
│ ├── skill-name-1/
│ │ ├── SKILL.md
│ │ ├── reference.md # Progressive disclosure
│ │ └── scripts/
│ │ └── helper.py
│ └── skill-name-2/
│ └── SKILL.md
├── commands/
│ ├── command-1.md
│ └── command-2.md
└── hooks/
├── README.md # Hook documentation
└── scripts/
├── validate.sh
└── lint.shNaming Conventions
Agents: lowercase-with-hyphens
- Good:
code-reviewer,test-runner,db-analyzer - Avoid:
CodeReviewer,test_runner,DBAnalyzer
Skills: lowercase-with-hyphens (gerund form preferred)
- Good:
processing-pdfs,analyzing-data,reviewing-code - Acceptable:
pdf-processing,data-analysis,code-review - Avoid:
helper,utils,tools(too vague)
Commands: lowercase-with-hyphens
- Good:
translate,deploy-staging,run-tests - Avoid:
doTranslate,Deploy_Staging
Files: Always use .md extension for agents, skills, and commands
Quality Checklist
All Components: Valid YAML, clear description with trigger terms, follows naming conventions
Agents: Focused purpose, minimal tools, clear workflow, tested Skills: Concise (<500 lines), concrete examples, one-level references Commands: User-facing, clear arguments, examples included Hooks: Fast execution, proper error handling, appropriate scope
For detailed checklists, see component-specific guides.
Best Practices Summary
1. Follow official documentation: Always consult official guides 2. Be concise: Assume Claude is smart, avoid over-explaining 3. Use progressive disclosure: Split large content into multiple files 4. Test thoroughly: Verify components work as expected 5. Iterate based on behavior: Watch how Claude uses components and refine 6. Keep components focused: Each component should do one thing well 7. Document clearly: Good descriptions and examples are essential 8. Use appropriate tools: Restrict tool access to minimum needed 9. Maintain consistency: Follow naming conventions and patterns 10. Version control: Check components into git for team collaboration
References
For detailed guidance, see these companion guides:
- [Agent Creation Guide](agents-guide.md) - Comprehensive subagent development
- [Skills Creation Guide](skills-guide.md) - Detailed skill creation with progressive disclosure
- [Commands Creation Guide](commands-guide.md) - Slash command development patterns
- [Hooks Reference Guide](hooks-guide.md) - Complete hooks documentation
- [Common Patterns & Examples](patterns-examples.md) - Practical patterns and examples
Always refer to the official documentation (see top of this file) when:
- Creating new component types
- Using advanced features
- Troubleshooting issues
- Following best practices
- Understanding permission models
The official documentation is the source of truth. This skill provides a practical guide, but defer to official docs for authoritative information.
Agent Creation Guide
Complete guide for creating and configuring Claude Code subagents.
Overview
Subagents are specialized AI assistants that handle specific types of tasks in isolated contexts. They provide:
- Task Isolation: Separate context for focused work
- Tool Restrictions: Limited access to only necessary tools
- Model Selection: Choose the best model for the task
- Permission Control: Custom permission handling modes
File Structure
File Format: Markdown with YAML frontmatter Location: .claude/agents/[agent-name].md
---
name: agent-name
description: When to delegate to this agent
tools: Read, Write, Grep
model: sonnet
permissionMode: default
skills: skill-1, skill-2
hooks:
PreToolUse:
- matcher: 'Bash'
hooks:
- type: command
command: './scripts/validate.sh'
---
# Agent System Prompt
[Agent instructions here]Frontmatter Fields
Required Fields
name (string)
- Unique identifier for the agent
- Must be lowercase with hyphens only
- Examples:
code-reviewer,test-runner,data-analyzer
description (string)
- When Claude should delegate to this subagent
- Include trigger terms users would naturally say
- Be specific about the agent's purpose
- Examples:
- "Reviews code changes for quality, security, and best practices"
- "Runs automated tests and reports results. Use when user asks to test code."
- "Analyzes database schemas and suggests optimizations"
Optional Fields
tools (array or comma-separated string)
- Allowlist of tools the agent can use
- If not specified, agent inherits all tools from parent
- Available tools: Read, Write, Edit, Bash, Grep, Glob, NotebookEdit, WebFetch, WebSearch, Skill, TodoWrite
- Syntax:
tools: Read, Write, Grep, Glob - Can restrict Bash with patterns:
Bash(python:*)
disallowedTools (array or comma-separated string)
- Denylist of tools the agent cannot use
- Use when easier to block specific tools than list all allowed
- Syntax:
disallowedTools: Bash, Edit - Cannot be used with
toolsfield
model (string)
- Model to use for this agent
- Can be a model alias (
sonnet,opus,haiku,inherit) or specific model string - Default:
sonnet(if not specified) - Use
inheritto match the main conversation's model - Recommendations:
opus: Complex reasoning, creative taskssonnet: General purpose, balancedhaiku: Fast, simple tasks
permissionMode (string)
- How to handle tool permissions
- Options:
default: Ask user for permission (standard behavior)acceptEdits: Auto-approve edit-only operationsdontAsk: Auto-approve all operations (use cautiously)bypassPermissions: Skip permission checks entirelyplan: Generate plan before execution- Recommendations:
- Use
defaultfor most agents - Use
acceptEditsfor trusted editing agents - Use
planfor complex multi-step workflows - Avoid
bypassPermissionsunless necessary
skills (array or comma-separated string)
- Skills to load into agent context at startup
- Full skill content is injected, not just made available for invocation
- Syntax:
skills: skill-1, skill-2 - Subagents don't inherit skills from the parent conversation
- Keep list minimal - only include necessary skills
- Skills add to context window size
hooks (object)
- Lifecycle hooks scoped to this agent
- See Hooks Reference Guide for details
- Common hooks:
PreToolUse: Validate before tool executionPostToolUse: Cleanup or logging after tool executionStop: Cleanup when agent completes
System Prompt Structure
The content after frontmatter is the agent's system prompt. Structure it clearly:
# Agent Name
[One-sentence description of the agent's role]
## Your Expertise
- [Area 1]
- [Area 2]
- [Area 3]
## Workflow
1. [Step 1]
2. [Step 2]
3. [Step 3]
4. [Step 4]
## Guidelines
- [Important rule 1]
- [Important rule 2]
- [Important rule 3]
## Examples
**Example 1**: [Scenario]
→ [How to handle]
**Example 2**: [Scenario]
→ [How to handle]System Prompt Best Practices
1. Be specific: Clearly define the agent's role and scope 2. Include workflow: Step-by-step process agents should follow 3. Provide examples: Concrete scenarios help agents understand context 4. Set boundaries: What the agent should NOT do 5. Keep it concise: Long prompts dilute important instructions 6. Use formatting: Headers, lists, and bold text for clarity
Component Interaction
Skills in Subagents
Load skills by listing them in the skills frontmatter field:
---
name: api-developer
description: Develops REST APIs following best practices
tools: Read, Write, Edit, Bash
skills: api-design-patterns, security-best-practices
---Important notes:
- Full skill content is injected at subagent startup
- Skills are not just "available" - they're loaded into context
- Keep skills list minimal to avoid context bloat
- Skills add to the agent's expertise immediately
Commands Invoking Subagents
Commands delegate to subagents using the Task tool:
---
description: Review code for quality issues
allowed-tools: Task(code-reviewer)
---
## Your Task
Use the Task tool to invoke the code-reviewer subagent:
- subagent_type: "code-reviewer"
- prompt: "Review the following files: [file list]"Tool Restrictions
Inheritance: Subagents inherit tools from parent by default
Allowlist approach (recommended for security):
tools: Read, Grep, Glob # Only these tools allowedDenylist approach (when most tools are needed):
disallowedTools: Bash, Edit # All tools except thesePattern restrictions (fine-grained control):
tools: Read, Write, Bash(python:*) # Bash only for Python scriptsDevelopment Workflow
Step 1: Identify the Need
Ask yourself:
- What task needs isolation?
- Does this require specialized behavior?
- Would tool restrictions improve security?
- Is this a repeated workflow?
Step 2: Design the Interface
Define:
- What inputs does the agent need?
- What outputs should it provide?
- What tools are necessary?
- What model is appropriate?
Step 3: Create the File
1. Create .claude/agents/[name].md 2. Add frontmatter with required fields 3. Write clear, focused system prompt 4. Include workflow steps 5. Add guidelines and examples
Step 4: Write the System Prompt
Template:
# [Agent Name]
You are [clear description of role and capabilities].
## Your Expertise
[List specific areas of expertise]
## Workflow
1. [First step - usually input validation]
2. [Middle steps - core processing]
3. [Final step - output formatting]
## Guidelines
- [Critical rules]
- [Best practices]
- [Common pitfalls to avoid]
## Examples
[Concrete examples showing expected behavior]Step 5: Test
1. Use /agents to verify agent appears in list 2. Test with representative tasks 3. Verify tool restrictions work 4. Check permission handling 5. Validate output quality
Step 6: Iterate
Based on observed behavior:
- Refine description if agent doesn't trigger appropriately
- Adjust system prompt if behavior is off
- Modify tool restrictions if too restrictive or permissive
- Add examples if agent misunderstands common cases
Troubleshooting
Agent Not Loading
Symptoms: Agent doesn't appear in /agents list
Solutions:
1. Check file location: Must be in .claude/agents/ 2. Verify YAML frontmatter syntax (no tabs, proper indentation) 3. Ensure name and description fields are present 4. Restart Claude Code session 5. Check for YAML parsing errors in logs
Agent Not Triggering
Symptoms: Claude doesn't delegate to agent automatically
Solutions:
1. Review description - does it include trigger terms? 2. Make description more specific and detailed 3. Try explicit invocation: "Use the [agent-name] subagent to..." 4. Add more scenarios to description 5. Check if another agent has overlapping description
Agent Has Wrong Tools
Symptoms: Permission errors or unexpected tool access
Solutions:
1. Verify tools or disallowedTools syntax 2. Check for tool name typos 3. Remember: tools is allowlist, disallowedTools is denylist 4. Cannot use both tools and disallowedTools together 5. Test with minimal tool set first
Agent Behavior Incorrect
Symptoms: Agent doesn't follow instructions or makes mistakes
Solutions:
1. Simplify system prompt - less is often more 2. Add concrete examples of expected behavior 3. Use clearer workflow steps 4. Try different model (opus for complex reasoning) 5. Reduce loaded skills if context seems confused 6. Add explicit "do NOT" guidelines
Skills Not Loading
Symptoms: Agent doesn't use skill knowledge
Solutions:
1. Verify skill names in skills field are correct 2. Check skills exist in .claude/skills/[name]/SKILL.md 3. Ensure skill SKILL.md has valid frontmatter 4. Try loading fewer skills (one at a time for testing) 5. Check skill file size - very large skills may cause issues
Common Patterns
Read-Only Research Agent
Use case: Safe exploration without modification risk
---
name: codebase-explorer
description: Explores codebase to find information. Use when researching code structure or finding specific implementations.
tools: Read, Grep, Glob
model: haiku
permissionMode: plan
---Benefits:
- Fast (haiku model)
- Safe (read-only tools)
- Structured (plan mode)
High-Permission Editor Agent
Use case: Trusted automated editing
---
name: code-formatter
description: Formats code according to style guidelines
tools: Read, Edit, Bash(prettier:*)
model: sonnet
permissionMode: acceptEdits
---Benefits:
- Efficient (auto-approves edits)
- Restricted (only formatting tools)
- Controlled (pattern-limited Bash)
Multi-Skill Specialist Agent
Use case: Domain expert with loaded knowledge
---
name: api-developer
description: Develops REST APIs following best practices. Use when creating or modifying API endpoints.
tools: Read, Write, Edit, Bash(npm:*), Grep, Glob
model: sonnet
skills: api-design-patterns, security-best-practices, openapi-spec
permissionMode: default
---Benefits:
- Expert knowledge loaded
- Full development tools
- Standard permissions
Validation Agent with Hooks
Use case: Pre-flight checks before operations
---
name: safe-deployer
description: Deploys code to production with validation checks
tools: Read, Bash
model: sonnet
permissionMode: plan
hooks:
PreToolUse:
- matcher: 'Bash'
hooks:
- type: command
command: './scripts/pre-deploy-check.sh'
Stop:
- hooks:
- type: command
command: './scripts/post-deploy-notify.sh'
---Benefits:
- Validation before execution
- Post-deployment cleanup
- Safety through planning
Best Practices Summary
1. Single Purpose: Each agent should excel at one specific task 2. Minimal Tools: Only grant necessary tools for security 3. Clear Descriptions: Include trigger terms for automatic delegation 4. Focused Prompts: Concise system prompts with clear workflows 5. Appropriate Model: Match model to task complexity 6. Load Relevant Skills: Only include skills that are needed 7. Test Thoroughly: Verify behavior with representative tasks 8. Iterate Based on Use: Refine based on actual usage patterns 9. Document Examples: Show concrete scenarios in system prompt 10. Use Hooks Wisely: Add validation and cleanup where beneficial
Advanced Topics
Model Selection Strategy
Use Opus when:
- Complex reasoning required
- Creative problem solving
- Nuanced decision making
- Multi-step planning
Use Sonnet when:
- General purpose tasks
- Balanced speed and quality
- Most development work
- Standard agent operations
Use Haiku when:
- Simple, repetitive tasks
- Fast responses needed
- Read-only exploration
- Basic validation
Permission Mode Strategy
default: Standard mode
- Use for most agents
- User reviews all operations
- Safest option
acceptEdits: Auto-approve edits
- Use for trusted editing agents
- Faster workflow for safe edits
- Still validates destructive operations
plan: Generate execution plan
- Use for complex workflows
- Shows steps before execution
- Good for learning agent behavior
dontAsk: Auto-approve all
- Use very sparingly
- Only for highly trusted, constrained agents
- Consider security implications
bypassPermissions: Skip all checks
- Rarely appropriate
- Only for internal automation
- Significant security risk
Skill Loading Optimization
Tips for managing skills in agents:
1. Load only what's needed: Each skill adds to context 2. Test incrementally: Add skills one at a time 3. Consider skill size: Large skills consume more context 4. Use progressive disclosure: Split large skills into smaller ones 5. Monitor behavior: Too many skills can dilute focus
Hook Integration
Common hook patterns for agents:
Pre-validation:
hooks:
PreToolUse:
- matcher: 'Write|Edit'
hooks:
- type: command
command: './scripts/validate-syntax.sh $TOOL_INPUT'Post-cleanup:
hooks:
PostToolUse:
- matcher: 'Bash'
hooks:
- type: command
command: './scripts/cleanup-temp.sh'Agent lifecycle:
hooks:
Stop:
- hooks:
- type: command
command: './scripts/agent-summary.sh'Related Documentation
- Skills Creation Guide - How to create skills for agents
- Commands Creation Guide - How to invoke agents from commands
- Hooks Reference Guide - Complete hooks documentation
- Common Patterns & Examples - More agent examples
For official documentation, see SKILL.md.
Commands Creation Guide
Complete guide for creating and configuring Claude Code slash commands.
Overview
Slash commands are user-invocable prompts that provide reusable workflows. They provide:
- User Interface: Easy access via
/command-namesyntax - Argument Handling: Structured input parsing
- Workflow Automation: Reusable task sequences
- Subagent Delegation: Orchestrate complex operations
File Structure
File Format: Markdown with YAML frontmatter Location: .claude/commands/[command-name].md
---
description: Brief description shown in /help
argument-hint: [--option <value>] <content>
allowed-tools: Task(agent-name), Read, Write
model: sonnet
disable-model-invocation: false
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate.sh"
---
# Command Name
## Parse Arguments
Command arguments: `$ARGUMENTS`
Extract needed values from arguments.
## Your Task
1. Parse arguments
2. Validate inputs
3. Perform work or delegate to subagent
4. Return results
## Examples
**Example 1**: `/command arg1 arg2`
→ [What happens]
**Example 2**: `/command @file.md`
→ [What happens]Frontmatter Fields
Required Fields
description (string)
- Brief description of what the command does
- Shown in
/helpmenu - Should be user-facing and clear
- Examples:
- "Translate text between English, Japanese, and Chinese"
- "Review code changes for quality and security issues"
- "Generate API documentation from source code"
Optional Fields
argument-hint (string)
- The arguments expected for the slash command
- Shown to the user when auto-completing the slash command in
/helpmenu - Use square brackets for optional:
[--option] - Use angle brackets for required:
<text> - Examples:
[--lang <en|ja|cn>] <text><source-file> [output-file][--format <json|yaml>] <input>add [tagId] | remove [tagId] | list
allowed-tools (array or comma-separated string)
- Tools the command can use
- Common pattern:
Task(agent-name)for delegation - Can include: Read, Write, Edit, Bash, Grep, Glob, etc.
- Syntax:
allowed-tools: Task(translator), Read
model (string)
- Model to use for this command
- Can be a model alias (
sonnet,opus,haiku) or specific model string - Default: inherits from parent context
- Most commands use default (sonnet)
disable-model-invocation (boolean)
- Prevent Skill tool from calling this command
- Default:
false - Set to
truefor commands only users should invoke - Use when command requires interactive input
hooks (object)
- Lifecycle hooks scoped to this command's execution
- Supports
PreToolUse,PostToolUse, andStopevents - See Hooks Reference Guide for details
- Useful for validation and cleanup
- Automatically cleaned up after command completes
Command Structure
Basic Command Template
---
description: Clear description for /help menu
argument-hint: [options] <required>
allowed-tools: Task(agent-name)
---
# Command Name
## Parse Arguments
Command arguments: `$ARGUMENTS`
Parse the arguments:
- Extract options: `--flag`, `--option value`
- Extract positional arguments: `$1`, `$2`, etc.
- Handle file references: `@filename`
## Your Task
1. **Validate Input**
- Check required arguments present
- Validate argument formats
- If missing, ask user with AskUserQuestion
2. **Process Request**
- Perform the task directly, OR
- Delegate to subagent with Task tool
3. **Return Results**
- Format output clearly
- Provide feedback to user
- Handle errors gracefully
## Examples
### Example 1: Basic Usage
**Input**: `/command arg1 arg2`
**Output**: [Expected result]
### Example 2: With Options
**Input**: `/command --option value arg1`
**Output**: [Expected result]
### Example 3: With File Reference
**Input**: `/command @file.md`
**Output**: [Expected result]Argument Parsing
Commands receive arguments via special variables:
`$ARGUMENTS` - All arguments as single string
Command: /translate --lang ja Hello world
$ARGUMENTS: "--lang ja Hello world"Positional variables - $1, $2, $3, etc.
Command: /deploy staging api-server
$1: "staging"
$2: "api-server"Parsing patterns:
## Parse Arguments
Command arguments: `$ARGUMENTS`
Extract:
- Language flag: Look for `--lang <value>` in $ARGUMENTS
- Text content: Everything after flags
- File reference: Look for `@filename` pattern
Example parsing:
- If $ARGUMENTS contains "--lang ja", set language to Japanese
- If $ARGUMENTS starts with "@", read file content
- Remaining text is the content to processFile References
Support @filename syntax for file inputs:
## Parse Arguments
If $ARGUMENTS starts with "@":
1. Extract filename after "@"
2. Use Read tool to get file content
3. Process the file content
Example:
- `/command @document.txt` → Read document.txt and processCommand Patterns
Pattern 1: Simple Direct Command
Command does work directly without delegation:
---
description: Format code in current directory
allowed-tools: Read, Write, Bash(prettier:*)
---
# Format Code
## Parse Arguments
Optional file pattern: `$1` (defaults to all files)
## Your Task
1. Find files matching pattern (or all files)
2. Run prettier on each file
3. Report which files were formatted
## Example
**/format** → Formats all files
**/format src/\*.ts** → Formats TypeScript files in src/Pattern 2: Subagent Delegation
Command delegates complex work to specialized agent:
---
description: Review code for quality and security issues
allowed-tools: Task(code-reviewer)
---
# Review Code
## Parse Arguments
Optional file or directory: `$1` (defaults to changed files)
## Your Task
1. Determine which files to review
2. Invoke code-reviewer subagent with Task tool:
- subagent_type: "code-reviewer"
- prompt: "Review these files: [file list]. Check for security issues, code quality, and best practices."
3. Present the review findings to user
## Examples
**/review** → Reviews all changed files
**/review src/auth.ts** → Reviews specific filePattern 3: Multi-Step Workflow
Command orchestrates multiple operations:
---
description: Deploy application to specified environment
allowed-tools: Task(deployment-agent), Bash
---
# Deploy Application
## Parse Arguments
Required environment: `$1` (staging, production)
Optional service: `$2` (defaults to all services)
## Your Task
1. **Validate Environment**
- Ensure environment is valid
- Check permissions for that environment
- If production, confirm with user
2. **Pre-Deployment Checks**
- Run tests with Task(deployment-agent)
- Verify dependencies
- Check configuration
3. **Deploy**
- Delegate to deployment-agent
- Monitor deployment progress
- Report status
4. **Post-Deployment**
- Verify deployment health
- Run smoke tests
- Notify team
## Examples
**/deploy staging** → Deploy all services to staging
**/deploy production api-server** → Deploy api-server to productionPattern 4: Interactive Command
Command asks for additional input if needed:
---
description: Generate API documentation
allowed-tools: Read, Write, Task(doc-generator)
---
# Generate API Documentation
## Parse Arguments
Optional output format: `$1` (markdown, html, pdf)
Optional output path: `$2`
## Your Task
1. **Check Arguments**
- If format not specified, ask user: "What format? (markdown/html/pdf)"
- If output path not specified, ask: "Where should I save the documentation?"
2. **Generate Documentation**
- Delegate to doc-generator agent
- Include format and path in prompt
3. **Confirm Completion**
- Show output path
- Offer to open/preview
## Examples
**/gendocs** → Asks for format and path
**/gendocs markdown** → Asks for path only
**/gendocs markdown docs/api.md** → Generates directlyDevelopment Workflow
Step 1: Define the Use Case
Ask yourself:
- What user task should this simplify?
- Would users benefit from a shortcut?
- Is this a repeated workflow?
- What arguments make sense?
Step 2: Design the Syntax
Consider:
- Command name (verb form:
deploy,review,translate) - Required vs optional arguments
- Flags and options
- File reference support
- Default behaviors
Step 3: Create the File
1. Create .claude/commands/[name].md 2. Add frontmatter with description 3. Add argument-hint if arguments are complex 4. Specify allowed-tools
Step 4: Write the Command Logic
Structure:
1. Argument parsing section 2. Validation logic 3. Main task execution 4. Error handling 5. Examples
Step 5: Test
1. Run /help to verify command appears 2. Test with no arguments 3. Test with partial arguments 4. Test with full arguments 5. Test with file references 6. Test with invalid inputs
Step 6: Document
Add examples covering:
- Basic usage
- Common options
- Edge cases
- Error scenarios
Best Practices
Command Design
1. User-facing: Commands are for users, not internal automation 2. Clear names: Use verbs, keep short, be descriptive 3. Intuitive syntax: Match user expectations 4. Good defaults: Work with no arguments when possible 5. Helpful errors: Guide user when input is invalid
Argument Handling
1. Parse carefully: Handle all argument formats 2. Validate early: Check arguments before heavy work 3. Ask when needed: Use AskUserQuestion for missing required args 4. Support files: Enable @filename pattern where useful 5. Document syntax: Use argument-hint for complex arguments
Delegation Strategy
1. Use subagents: Delegate complex work to specialized agents 2. Clear prompts: Provide full context to subagents 3. Handle errors: Catch and report subagent failures 4. Show progress: Keep user informed during long operations
Error Handling
1. Validate input: Check arguments before processing 2. Provide feedback: Tell user what went wrong 3. Suggest fixes: Help user correct mistakes 4. Fail gracefully: Don't leave system in bad state
Troubleshooting
Command Not in /help
Symptoms: Command doesn't appear in help menu
Solutions:
1. Check file location: .claude/commands/[name].md 2. Verify frontmatter has description field 3. Check for YAML syntax errors 4. Ensure filename ends with .md 5. Restart Claude Code session
Command Fails to Execute
Symptoms: Command runs but errors or does nothing
Solutions:
1. Check allowed-tools includes necessary tools 2. Verify tool names are correct 3. Test argument parsing with simple inputs 4. Check for permission issues 5. Verify subagent names if using Task tool
Arguments Not Parsed Correctly
Symptoms: Command gets wrong values from arguments
Solutions:
1. Review argument parsing logic 2. Test with different argument patterns 3. Handle both $ARGUMENTS and $1, $2 formats 4. Account for quoted strings 5. Test file reference pattern (@filename)
Subagent Not Found
Symptoms: Task tool fails to find agent
Solutions:
1. Verify agent exists in .claude/agents/ 2. Check agent name spelling in allowed-tools 3. Ensure agent has valid frontmatter 4. Use exact agent name, case-sensitive 5. Restart session if agent was just created
Command Behaves Unexpectedly
Symptoms: Command does something different than intended
Solutions:
1. Review command prompt for clarity 2. Add more specific instructions 3. Include examples of correct behavior 4. Simplify command logic 5. Add validation steps
Advanced Topics
Complex Argument Parsing
Handle sophisticated argument patterns:
## Parse Arguments
Command arguments: `$ARGUMENTS`
Parse complex syntax:
1. **Extract flags**
- Look for `--flag` or `--option value` patterns
- Common flags: `--force`, `--verbose`, `--dry-run`
2. **Extract positional arguments**
- Get values by position: `$1`, `$2`, etc.
- Handle optional vs required
3. **Handle file references**
- Check for `@filename` pattern
- Support multiple files: `@file1.txt @file2.txt`
4. **Parse key-value pairs**
- Support syntax like `key=value`
- Example: `name=api-server env=staging`
Example:/deploy staging api-server --force --verbose → env: staging → service: api-server → force: true → verbose: true
Multi-Agent Orchestration
Coordinate multiple agents:
---
description: Full code quality pipeline
allowed-tools: Task(linter), Task(test-runner), Task(code-reviewer)
---
## Your Task
1. **Lint Code**
- Invoke linter agent
- If linting fails, stop and report errors
2. **Run Tests**
- Invoke test-runner agent
- If tests fail, stop and report failures
3. **Review Code**
- Invoke code-reviewer agent
- Generate comprehensive review report
4. **Summary**
- Combine all results
- Provide actionable feedbackConditional Execution
Execute different paths based on context:
## Your Task
1. **Determine Context**
- Check if in git repository
- Check current branch
- Check for uncommitted changes
2. **Choose Path**
- If on main branch → Warn and require confirmation
- If uncommitted changes → Ask to stash or commit
- Otherwise → Proceed normally
3. **Execute**
- Run appropriate workflow for context
- Handle errors specific to each pathProgress Reporting
Keep user informed during long operations:
## Your Task
1. **Setup**
- Tell user: "Starting deployment to staging..."
2. **Pre-checks**
- Tell user: "Running pre-deployment checks..."
- Run checks
- Tell user: "Pre-checks passed"
3. **Deployment**
- Tell user: "Deploying services..."
- Deploy each service
- Tell user: "Deployed service X" after each
4. **Verification**
- Tell user: "Verifying deployment..."
- Run health checks
- Tell user: "Deployment complete and verified"Hook Integration
Add validation and automation:
---
description: Safe file operations with validation
allowed-tools: Write, Edit
hooks:
PreToolUse:
- matcher: 'Write|Edit'
hooks:
- type: command
command: './scripts/backup.sh $TOOL_INPUT'
- type: command
command: './scripts/validate.sh $TOOL_INPUT'
---
## Your Task
File operations are automatically:
1. Backed up before modification (PreToolUse hook)
2. Validated before writing (PreToolUse hook)
Proceed with confidence knowing hooks provide safety.Common Patterns
Read-Process-Write Command
---
description: Process files with transformation
allowed-tools: Read, Write
---
## Parse Arguments
Input file: `$1`
Output file: `$2` (optional, defaults to input + .out)
## Your Task
1. Read input file
2. Process content (transformation logic)
3. Write to output file
4. Report completionSearch-Report Command
---
description: Search codebase and generate report
allowed-tools: Grep, Glob, Write
---
## Parse Arguments
Search term: `$1`
Output file: `$2` (optional, defaults to search-results.md)
## Your Task
1. Use Grep to find all occurrences
2. Organize results by file
3. Generate markdown report
4. Write to output file
5. Show summary statisticsValidation Command
---
description: Validate project configuration
allowed-tools: Read, Bash
---
## Your Task
1. Check all required config files exist
2. Validate config file syntax
3. Check for required fields
4. Run validation scripts
5. Generate validation report with pass/failRelated Documentation
- Agent Creation Guide - Creating agents for delegation
- Skills Creation Guide - Loading skills for command use
- Hooks Reference Guide - Adding hooks to commands
- Common Patterns & Examples - More command examples
For official documentation, see SKILL.md.
Hooks Reference Guide
Complete guide for configuring and using Claude Code hooks.
Overview
Hooks are scripts that run automatically on tool events. They provide:
- Automated Validation: Pre-execution checks
- Post-Processing: Cleanup and logging after operations
- Lifecycle Management: Setup and teardown
- Event-Driven Automation: React to specific tool usage
Hook Configuration
Hooks can be configured in two places:
1. Global Configuration: In .claude/settings.json (applies to all components) 2. Component Configuration: In frontmatter of agents, skills, or commands (scoped to that component)
Global Hooks (settings.json)
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "./scripts/validate-bash.sh $TOOL_INPUT",
"once": false
}
]
}
],
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "./scripts/lint.sh"
}
]
}
]
}
}Component Hooks (Frontmatter)
---
name: component-name
description: Component description
hooks:
PreToolUse:
- matcher: 'Bash'
hooks:
- type: command
command: './scripts/validate.sh $TOOL_INPUT'
once: true
PostToolUse:
- matcher: 'Write|Edit'
hooks:
- type: command
command: './scripts/format.sh'
Stop:
- hooks:
- type: command
command: './scripts/cleanup.sh'
---Hook Events
PreToolUse
Runs before a tool is executed.
Matcher: Tool name (e.g., "Bash", "Write", "Edit", "Write|Edit") Use cases:
- Validate input before execution
- Check permissions
- Create backups
- Block unsafe operations
Special variables:
$TOOL_INPUT: The input being passed to the tool$TOOL_NAME: Name of the tool being invoked
Exit codes:
- 0: Allow operation to proceed
- Non-zero: Block operation and show error
Example:
PreToolUse:
- matcher: 'Bash'
hooks:
- type: command
command: './scripts/validate-bash-command.sh $TOOL_INPUT'PermissionRequest
Runs when the user is shown a permission dialog.
Matcher: Tool name (same as PreToolUse) Use cases:
- Auto-approve specific operations
- Auto-deny dangerous operations on behalf of user
- Modify tool inputs before approval
- Custom permission logic
Special variables:
$TOOL_INPUT: The input being passed to the tool$TOOL_NAME: Name of the tool being requested
Exit codes:
- 0: Normal processing (use JSON output for decision control)
- Non-zero: Error handling
Example:
PermissionRequest:
- matcher: 'Bash'
hooks:
- type: command
command: './scripts/permission-handler.sh $TOOL_INPUT'PostToolUse
Runs after a tool is executed successfully.
Matcher: Tool name (e.g., "Bash", "Write", "Edit") Use cases:
- Format code after editing
- Run linters
- Update indexes
- Log operations
- Notify external systems
Special variables:
$TOOL_OUTPUT: The output from the tool$TOOL_NAME: Name of the tool that was invoked
Exit codes:
- Exit codes don't block operations (tool already ran)
- Non-zero codes are logged but don't fail the operation
Example:
PostToolUse:
- matcher: 'Write|Edit'
hooks:
- type: command
command: './scripts/lint-file.sh'SubagentStart
Runs when a subagent begins execution.
Matcher: Agent name (e.g., "translator", "code-reviewer") Use cases:
- Setup environment for agent
- Load configuration
- Initialize resources
- Log agent invocation
Special variables:
$AGENT_NAME: Name of the starting agent
Example:
SubagentStart:
- matcher: 'translator'
hooks:
- type: command
command: './scripts/setup-translation-env.sh'SubagentStop
Runs when a subagent completes execution.
Matcher: Agent name (e.g., "translator", "code-reviewer") Use cases:
- Cleanup agent resources
- Save state
- Generate reports
- Log completion
Special variables:
$AGENT_NAME: Name of the stopping agent
Example:
SubagentStop:
- matcher: 'translator'
hooks:
- type: command
command: './scripts/cleanup-translation-env.sh'Stop
Runs when a component completes execution (main agent finished responding, not on user interrupt).
Matcher: None (no matcher field) Use cases:
- Final cleanup
- Generate summary
- Save results
- Notify completion
- Intelligently decide if Claude should continue working
Special variables: None
Example:
Stop:
- hooks:
- type: command
command: './scripts/final-cleanup.sh'Notification
Runs when Claude Code sends notifications.
Matcher: Notification type (e.g., permission_prompt, idle_prompt, auth_success, elicitation_dialog) Use cases:
- Alert on permission requests
- Monitor idle states
- Track authentication events
- Custom notification handling
Special variables:
$NOTIFICATION_TYPE: Type of notification
Example:
Notification:
- matcher: 'permission_prompt'
hooks:
- type: command
command: './scripts/permission-alert.sh'
- matcher: 'idle_prompt'
hooks:
- type: command
command: './scripts/idle-notification.sh'UserPromptSubmit
Runs when the user submits a prompt, before Claude processes it.
Matcher: None (no matcher field) Use cases:
- Add additional context based on prompt
- Validate prompts
- Block certain types of prompts
- Inject dynamic information
Special variables: None (prompt is in hook input JSON)
Example:
UserPromptSubmit:
- hooks:
- type: command
command: './scripts/prompt-validator.py'PreCompact
Runs before Claude Code is about to run a compact operation.
Matcher: Compact trigger type (manual or auto) Use cases:
- Prepare for compaction
- Save state before compact
- Add context before history is summarized
Special variables: None
Example:
PreCompact:
- matcher: 'manual'
hooks:
- type: command
command: './scripts/pre-compact-manual.sh'
- matcher: 'auto'
hooks:
- type: command
command: './scripts/pre-compact-auto.sh'SessionStart
Runs when Claude Code starts a new session or resumes an existing session.
Matcher: Session source type (startup, resume, clear, compact) Use cases:
- Load development context
- Install dependencies
- Set up environment variables
- Initialize resources
Special variables:
$CLAUDE_ENV_FILE: File path for persisting environment variables (SessionStart only)
Persisting environment variables:
SessionStart hooks can write to $CLAUDE_ENV_FILE to make environment variables available in all subsequent bash commands:
#!/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"
fi
exit 0Example:
SessionStart:
- matcher: 'startup'
hooks:
- type: command
command: './scripts/session-setup.sh'
- matcher: 'resume'
hooks:
- type: command
command: './scripts/session-resume.sh'SessionEnd
Runs when a Claude Code session ends.
Matcher: None (no matcher field) Use cases:
- Cleanup tasks
- Log session statistics
- Save session state
- Final notifications
Special variables: None (reason is in hook input JSON)
Session end reasons:
clear: Session cleared with /clear commandlogout: User logged outprompt_input_exit: User exited while prompt input was visibleother: Other exit reasons
Example:
SessionEnd:
- hooks:
- type: command
command: './scripts/session-cleanup.sh'Hook Types
Command Hook
Executes a shell command.
Type: command Fields:
command(required): Shell command to executeonce(optional): Run only once per session (default: false). After first successful execution, hook is removedtimeout(optional): How long a hook should run, in seconds, before canceling that specific hook
Example:
hooks:
- type: command
command: './scripts/validate.sh $TOOL_INPUT'
once: false
timeout: 30Command execution:
- Runs in shell context
- Can use all shell features (pipes, redirects, etc.)
- Has access to environment variables
- Working directory is repository root
Exit behavior:
- PreToolUse hooks: Non-zero exits block the operation
- PostToolUse hooks: Non-zero exits are logged only
- Stop hooks: Non-zero exits are logged only
Prompt Hook
Injects text into the conversation context or uses an LLM to evaluate whether to allow/block an action.
Type: prompt Fields:
prompt(required): Text to inject or prompt to send to LLM for evaluationonce(optional): Inject/run only once per session (default: false)timeout(optional): Timeout in seconds for LLM evaluation (default: 30 seconds)
Two modes of operation:
1. Context injection (for most hook events): Injects text into conversation 2. LLM evaluation (for Stop, SubagentStop, etc.): Uses LLM to make intelligent decisions
Example (context injection):
hooks:
- type: prompt
prompt: 'Remember to follow security best practices.'
once: trueExample (LLM evaluation for Stop hook):
hooks:
- type: prompt
prompt: 'Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete.'
timeout: 30Use cases:
- Add reminders and guidelines
- Inject context dynamically
- Make context-aware permission decisions
- Intelligently decide if work is complete
LLM evaluation response schema (for Stop, SubagentStop, etc.):
{
"ok": true | false,
"reason": "Explanation for the decision"
}ok: trueallows the actionok: falseprevents it (reason is required)
Matchers
Matchers determine when hooks trigger. They use regex patterns.
Tool Matchers (PreToolUse, PostToolUse)
Match tool names:
Single tool:
matcher: 'Bash'Multiple tools (OR):
matcher: 'Write|Edit'Pattern matching:
matcher: 'Write|Edit|NotebookEdit'All tools:
matcher: '.*'Agent Matchers (SubagentStart, SubagentStop)
Match agent names:
Single agent:
matcher: 'translator'Multiple agents (OR):
matcher: 'translator|code-reviewer'Pattern matching:
matcher: '.*-reviewer' # Matches any agent ending with -reviewerNo Matcher (Stop)
Stop hooks don't use matchers:
Stop:
- hooks:
- type: command
command: './cleanup.sh'Hook Scope
Global Hooks
Defined in .claude/settings.json:
- Apply to entire project
- Active for all sessions
- Persist across restarts
- Useful for project-wide policies
Example use cases:
- Code formatting on all edits
- Bash command validation
- Logging all tool usage
Component Hooks
Defined in component frontmatter:
- Scoped to that component's execution
- Automatically cleaned up when component completes
- Don't affect other components
- Useful for component-specific behavior
Example use cases:
- Agent-specific setup/teardown
- Command-specific validation
- Skill-specific tooling
Advanced Features
Once Flag
Run hook only once per session:
hooks:
- type: command
command: './scripts/expensive-setup.sh'
once: trueUse cases:
- One-time environment setup
- Initial configuration loading
- Session initialization
- First-run checks
Behavior:
- First trigger: Hook runs normally
- Subsequent triggers: Hook is skipped
- Reset: On session restart
Important: The once option is currently only supported for skills and slash commands, not for agents. For agents, hooks will run every time they are triggered.
Environment Variables
Hooks can access environment variables:
hooks:
- type: command
command: './scripts/deploy.sh $DEPLOYMENT_ENV'Available variables:
- All system environment variables
$TOOL_INPUT: Input to tool (PreToolUse only)$TOOL_OUTPUT: Output from tool (PostToolUse only)$TOOL_NAME: Name of tool being used$AGENT_NAME: Name of agent (SubagentStart/Stop only)
Chaining Hooks
Multiple hooks can be chained:
PreToolUse:
- matcher: 'Write'
hooks:
- type: command
command: './scripts/backup.sh $TOOL_INPUT'
- type: command
command: './scripts/validate.sh $TOOL_INPUT'
- type: prompt
prompt: 'Remember to review changes carefully.'Execution order:
- Hooks run in the order defined
- If any PreToolUse hook fails, operation is blocked
- All hooks in the chain must succeed
Conditional Execution
Hooks can include conditional logic in scripts:
#!/bin/bash
# scripts/conditional-hook.sh
if [ "$TOOL_NAME" = "Bash" ]; then
# Bash-specific validation
./validate-bash.sh "$TOOL_INPUT"
elif [ "$TOOL_NAME" = "Write" ]; then
# Write-specific validation
./validate-write.sh "$TOOL_INPUT"
fiBest Practices
Performance
1. Keep hooks fast: They run on every matching event 2. Use `once: true` for expensive operations 3. Avoid network calls in hot-path hooks 4. Cache results when possible 5. Profile hook execution if slowdowns occur
Security
1. Validate input: Don't trust $TOOL_INPUT blindly 2. Use PreToolUse hooks to block dangerous operations 3. Escape shell variables: Prevent injection attacks 4. Limit permissions: Hook scripts should have minimal access 5. Log security events: Track blocked operations
Reliability
1. Handle errors gracefully: Don't crash on unexpected input 2. Provide clear error messages: Help users understand failures 3. Test hook scripts independently: Unit test before integration 4. Use exit codes correctly: 0 for success, non-zero for failure 5. Log hook execution: Aid debugging
Maintainability
1. Document hooks: Explain what and why 2. Use descriptive script names: Clear purpose 3. Keep scripts simple: One responsibility per hook 4. Version control hook scripts: Track changes 5. Test on updates: Verify hooks still work
Scope Appropriately
1. Use component hooks for component-specific behavior 2. Use global hooks for project-wide policies 3. Prefer narrow matchers: Be specific about what triggers 4. Avoid overlapping hooks: Multiple hooks for same event can conflict 5. Clean up automatically: Let component hooks handle their cleanup
Common Patterns
Pre-Flight Validation
Validate before dangerous operations:
hooks:
PreToolUse:
- matcher: 'Bash'
hooks:
- type: command
command: |
if echo "$TOOL_INPUT" | grep -q "rm -rf"; then
echo "Dangerous rm command blocked"
exit 1
fiAutomatic Formatting
Format code after editing:
hooks:
PostToolUse:
- matcher: 'Write|Edit'
hooks:
- type: command
command: './scripts/format-code.sh'Backup Before Modification
Create backups before changing files:
hooks:
PreToolUse:
- matcher: 'Write|Edit'
hooks:
- type: command
command: './scripts/backup.sh $TOOL_INPUT'Environment Setup/Teardown
Setup and cleanup for agents:
hooks:
SubagentStart:
- matcher: 'deployment-agent'
hooks:
- type: command
command: './scripts/setup-deploy-env.sh'
once: true
SubagentStop:
- matcher: 'deployment-agent'
hooks:
- type: command
command: './scripts/cleanup-deploy-env.sh'Logging and Monitoring
Track tool usage:
hooks:
PostToolUse:
- matcher: '.*'
hooks:
- type: command
command: './scripts/log-tool-usage.sh $TOOL_NAME'Conditional Reminders
Inject context-aware reminders:
hooks:
PreToolUse:
- matcher: 'Bash'
hooks:
- type: prompt
prompt: 'Double-check bash commands for safety.'
- matcher: 'Write|Edit'
hooks:
- type: prompt
prompt: 'Remember to maintain code style consistency.'Git Operations
Auto-stage changes:
hooks:
PostToolUse:
- matcher: 'Write|Edit'
hooks:
- type: command
command: 'git add $TOOL_INPUT'Troubleshooting
Hook Not Triggering
Symptoms: Hook doesn't run when expected
Solutions:
1. Check matcher pattern matches tool/agent name exactly 2. Verify hook is in correct event section (PreToolUse vs PostToolUse) 3. Ensure script path is correct (relative to repo root) 4. Check script has execute permissions: chmod +x script.sh 5. Test hook script independently 6. Check for YAML syntax errors in configuration
Hook Blocking Operations
Symptoms: Tool usage fails unexpectedly
Solutions:
1. Check PreToolUse hook exit codes (non-zero blocks) 2. Review hook script for errors 3. Check hook script has proper error handling 4. Verify $TOOL_INPUT is being parsed correctly 5. Add debug logging to hook script 6. Test hook script with sample input
Hook Running Multiple Times
Symptoms: Hook executes more than expected
Solutions:
1. Add once: true if hook should run once per session 2. Check if multiple matchers are triggering hook 3. Verify hook isn't defined in both global and component configs 4. Review matcher pattern for unintended matches 5. Check if hook is being chained unintentionally
Hook Performance Issues
Symptoms: Operations slow when hooks enabled
Solutions:
1. Profile hook execution time 2. Add caching to expensive operations 3. Use once: true for setup operations 4. Optimize hook scripts 5. Move slow operations to PostToolUse if possible 6. Consider disabling hooks for specific components
Script Path Issues
Symptoms: Hook fails with "command not found"
Solutions:
1. Use paths relative to repository root 2. Ensure script has execute permissions 3. Use absolute paths if needed 4. Check script exists at specified path 5. Test script path manually: ./scripts/hook.sh
Environment Variable Issues
Symptoms: Hook script can't access variables
Solutions:
1. Verify environment variables are set 2. Check variable names are correct ($TOOL_INPUT, etc.) 3. Quote variables in scripts: "$TOOL_INPUT" 4. Test script with sample environment variables 5. Check shell script has proper shebang: #!/bin/bash
Hook Script Examples
Validation Script
#!/bin/bash
# scripts/validate-bash-command.sh
COMMAND="$1"
# Block dangerous patterns
if echo "$COMMAND" | grep -qE "rm -rf /|sudo rm"; then
echo "ERROR: Dangerous command blocked: $COMMAND"
exit 1
fi
# Check for unquoted variables
if echo "$COMMAND" | grep -qE '\$[A-Za-z_]+[^"]'; then
echo "WARNING: Unquoted variable detected"
exit 1
fi
exit 0Backup Script
#!/bin/bash
# scripts/backup.sh
FILE="$1"
BACKUP_DIR=".backups"
if [ -f "$FILE" ]; then
mkdir -p "$BACKUP_DIR"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
cp "$FILE" "$BACKUP_DIR/$(basename $FILE).$TIMESTAMP"
echo "Backed up $FILE"
fi
exit 0Formatting Script
#!/bin/bash
# scripts/format-code.sh
# Find files that were just modified
CHANGED_FILES=$(git diff --name-only --cached)
for FILE in $CHANGED_FILES; do
if [[ $FILE == *.js || $FILE == *.ts ]]; then
prettier --write "$FILE"
echo "Formatted $FILE"
fi
done
exit 0Environment Setup Script
#!/bin/bash
# scripts/setup-env.sh
echo "Setting up environment..."
# Load configuration
export API_KEY=$(cat .env | grep API_KEY | cut -d= -f2)
export ENV="staging"
# Initialize tools
npm install --silent
echo "Environment ready"
exit 0Related Documentation
- Agent Creation Guide - Using hooks in agents
- Skills Creation Guide - Using hooks in skills
- Commands Creation Guide - Using hooks in commands
- Common Patterns & Examples - More hook examples
For official documentation, see SKILL.md.
Common Patterns & Examples
Practical patterns and examples for building Claude Code components.
Overview
This guide provides real-world patterns for common use cases. Each pattern includes:
- Use case description
- Complete component examples
- Benefits and trade-offs
- When to use this pattern
Agent Patterns
Pattern 1: Read-Only Exploration Agent
Use Case: Safe codebase exploration without modification risk
Example:
---
name: codebase-explorer
description: Explores codebase to find information. Use when researching code structure or finding specific implementations.
tools: Read, Grep, Glob
model: haiku
permissionMode: plan
---
# Codebase Explorer
You are a codebase exploration specialist focused on quickly finding and analyzing code.
## Your Expertise
- Finding files and functions efficiently
- Understanding code structure and dependencies
- Analyzing implementation patterns
- Tracing code execution flows
## Workflow
1. **Understand the question**: Parse what user is looking for
2. **Search strategically**: Use Grep/Glob to locate relevant code
3. **Read and analyze**: Examine found files for answers
4. **Synthesize findings**: Provide clear, actionable summary
## Guidelines
- Start broad (Glob), then narrow (Grep), then deep (Read)
- Don't make assumptions - verify with actual code
- Cite file paths and line numbers in responses
- Suggest related areas to explore when relevantBenefits:
- Fast (haiku model for quick searches)
- Safe (read-only tools prevent accidental changes)
- Structured (plan mode shows search strategy)
- Efficient (focused on exploration only)
When to Use:
- Need to understand unfamiliar codebase
- Looking for specific implementations
- Want to trace code dependencies
- Researching patterns or conventions
---
Pattern 2: High-Permission Editor Agent
Use Case: Trusted automated editing with pre-approved changes
Example:
---
name: code-formatter
description: Formats code according to style guidelines. Use when code needs formatting or style fixes.
tools: Read, Edit, Bash(prettier:*,eslint:*)
model: sonnet
permissionMode: acceptEdits
---
# Code Formatter
You are an automated code formatting specialist that ensures consistent code style.
## Your Expertise
- Running formatters (prettier, eslint)
- Applying style fixes automatically
- Maintaining code consistency
- Handling multiple file types
## Workflow
1. **Identify files**: Determine which files need formatting
2. **Read current state**: Check file content before formatting
3. **Apply formatters**: Run appropriate formatter for each file type
4. **Verify changes**: Ensure formatting succeeded
5. **Report results**: Summarize what was formatted
## Guidelines
- Only format, never change logic
- Use project's existing formatter configuration
- Format all affected files, not just one
- Report if any files failed to format
- Preserve file encoding and line endingsBenefits:
- Efficient (auto-approves edit operations)
- Safe (restricted to formatting tools only)
- Fast (no permission prompts for edits)
- Controlled (Bash restricted to specific commands)
When to Use:
- Automated code formatting workflows
- Pre-commit style fixes
- Bulk formatting operations
- Trusted repetitive editing
---
Pattern 3: Multi-Skill Specialist Agent
Use Case: Domain expert with comprehensive loaded knowledge
Example:
---
name: api-developer
description: Develops REST APIs following best practices. Use when creating or modifying API endpoints, routes, or controllers.
tools: Read, Write, Edit, Bash(npm:*), Grep, Glob
model: sonnet
skills: api-design-patterns, openapi-spec, security-best-practices
permissionMode: default
---
# API Developer
You are an expert API developer specializing in RESTful API design and implementation.
## Your Expertise
- RESTful API design principles (from api-design-patterns skill)
- OpenAPI specification (from openapi-spec skill)
- API security best practices (from security-best-practices skill)
- Backend development patterns
- API documentation
## Workflow
1. **Understand requirements**: What endpoints are needed?
2. **Design API**: Apply REST principles and security patterns
3. **Implement endpoints**: Write clean, secure code
4. **Add documentation**: Document with OpenAPI/comments
5. **Test**: Verify endpoints work correctly
## Guidelines
- Follow RESTful conventions (from api-design-patterns)
- Always validate input (from security-best-practices)
- Document all endpoints with OpenAPI (from openapi-spec)
- Use appropriate HTTP methods and status codes
- Handle errors gracefully
- Consider pagination for list endpointsBenefits:
- Expert knowledge immediately available
- Consistent application of patterns
- Security built-in from loaded skills
- Documentation standards enforced
When to Use:
- Complex domain requiring multiple knowledge areas
- Need consistent application of standards
- Want to ensure best practices followed
- Domain expertise needs to be codified
Trade-offs:
- Larger context window usage
- More tokens consumed
- Slower startup (skills loaded at start)
---
Pattern 4: Validation Agent with Hooks
Use Case: Pre-flight checks and automated validation
Example:
---
name: safe-deployer
description: Deploys code to production with automated validation checks. Use when deploying to any environment.
tools: Read, Bash
model: sonnet
permissionMode: plan
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/pre-deploy-validation.sh $TOOL_INPUT"
- type: prompt
prompt: "Remember: All deploys require approval from security team."
Stop:
- hooks:
- type: command
command: "./scripts/post-deploy-notification.sh"
---
# Safe Deployer
You are a deployment specialist focused on safe, validated deployments.
## Your Expertise
- Deployment validation and checks
- Environment configuration
- Rollback procedures
- Monitoring deployment health
## Workflow
1. **Pre-deployment checks** (automated via hooks):
- Code tests passing
- Security scan clean
- Dependencies updated
- Configuration valid
2. **Plan deployment**:
- Generate deployment plan
- Show what will be deployed
- Get user confirmation
3. **Execute deployment**:
- Deploy to target environment
- Monitor for errors
- Verify health checks
4. **Post-deployment** (automated via hooks):
- Notify team via Slack
- Log deployment details
- Update deployment tracker
## Guidelines
- Never skip validation checks
- Always show deployment plan first
- Require confirmation for production
- Have rollback plan ready
- Monitor deployment closelyBenefits:
- Automatic validation prevents errors
- Consistent deployment process
- Audit trail via notifications
- Safety through planning mode
When to Use:
- Critical operations requiring validation
- Need automated safety checks
- Want audit logging
- Require consistent process
---
Skill Patterns
Pattern 1: Domain Terminology Skill
Use Case: Industry-specific vocabulary and concepts
Example:
---
name: kubernetes-terminology
description: Kubernetes architecture and terminology. Use when working with K8s deployments, configs, or troubleshooting.
---
# Kubernetes Terminology
## Core Concepts
**Pod**: Smallest deployable unit. Contains one or more containers that share network and storage.
**Deployment**: Manages replica sets and rolling updates. Declaratively manages pod lifecycle.
**Service**: Stable network endpoint for pods. Types: ClusterIP (internal), NodePort (node-level), LoadBalancer (external).
**Ingress**: HTTP/HTTPS routing to services. Manages external access with path-based routing.
**ConfigMap**: Non-sensitive configuration data. Mounted as files or environment variables.
**Secret**: Sensitive data (passwords, tokens). Base64 encoded, mounted securely.
## ArchitectureClient → Ingress → Service → Pod(s) → Container(s)
````
Quick Reference
Common kubectl Commands
kubectl get pods- List podskubectl describe pod <name>- Pod detailskubectl logs <pod>- View pod logskubectl apply -f <file>- Apply configurationkubectl delete <resource> <name>- Delete resource
Resource Limits
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"Best Practices
1. Use namespaces for environment separation 2. Set resource limits to prevent resource exhaustion 3. Use liveness/readiness probes for health checks 4. Store configs in ConfigMaps not in images 5. Use secrets for sensitive data, never hardcode
Common Patterns
Deployment with Service
apiVersion: apps/v1
kind: Deployment
metadata:
name: api-server
spec:
replicas: 3
selector:
matchLabels:
app: api-server
template:
metadata:
labels:
app: api-server
spec:
containers:
- name: api
image: api-server:latest
ports:
- containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
name: api-service
spec:
selector:
app: api-server
ports:
- port: 80
targetPort: 8080
**Benefits**:
- Quick terminology lookup
- Consistent usage of terms
- Common patterns readily available
- Best practices embedded
---
### Pattern 2: Progressive Disclosure Skill
**Use Case**: Large knowledge domain split for efficiency
**Example Structure**:
api-documentation-generator/ ├── SKILL.md # Main overview (< 500 lines) ├── openapi-spec.md # OpenAPI 3.0 specification details ├── examples.md # Real-world examples └── scripts/ └── generate.py # Generation utility
````
SKILL.md:
---
name: api-documentation-generator
description: Generates API documentation from source code. Use when creating or updating API docs.
allowed-tools: Read, Bash(python:*)
---
# API Documentation Generator
## Overview
This skill helps generate comprehensive API documentation from source code using multiple documentation formats.
## Quick Start
1. Analyze source code for API endpoints
2. Extract route definitions and parameters
3. Generate documentation in requested format
4. Validate documentation completeness
## Supported Formats
- **OpenAPI/Swagger**: See [openapi-spec.md](openapi-spec.md) for details
- **Markdown**: Standard markdown format
- **HTML**: Interactive documentation
## Core Process
### 1. Discovery
Scan code for API endpoints:
- Route definitions
- HTTP methods
- Parameters (path, query, body)
- Response structures
### 2. Analysis
Extract details:
- Request/response schemas
- Authentication requirements
- Example requests/responses
- Error codes
### 3. Generation
Create documentation:
- Choose format (OpenAPI, Markdown, etc.)
- Apply templates
- Validate completeness
- Generate output file
## Quick Reference
### Common Patterns
FastAPI endpoint
@app.get("/users/{user_id}") def get_user(user_id: int) -> User: """Get user by ID""" pass
OpenAPI equivalent
paths: /users/{user_id}: get: summary: Get user by ID parameters:
- name: user_id
in: path required: true schema: type: integer ````
Detailed References
- OpenAPI Specification: openapi-spec.md - Complete OpenAPI 3.0 details
- Examples: examples.md - Real-world documentation examples
- Generator Script:
python scripts/generate.py --help- Utility for generation
Best Practices
1. Document all endpoints, even internal ones 2. Include example requests and responses 3. Document error codes and their meanings 4. Keep docs in sync with code 5. Version your API documentation
````
Benefits:
- Main file stays focused and fast to load
- Detailed information available when needed
- Separation of concerns (overview vs details)
- Scripts available but not loaded into context
---
Command Patterns
Pattern 1: Simple Direct Command
Use Case: Command executes work directly
Example:
---
description: Format code in current directory
allowed-tools: Read, Write, Bash(prettier:*)
---
# Format Code
## Parse Arguments
Optional file pattern: `$1` (defaults to "**/*.{js,ts,jsx,tsx}")
## Your Task
1. **Determine Files**
- If $1 provided, use as file pattern
- Otherwise, use default pattern for JS/TS files
2. **Run Formatter**
- Execute: `npx prettier --write <pattern>`
- Capture output showing which files changed
3. **Report Results**
- List formatted files
- Show any files that had errors
- Provide summary count
## Examples
**/format** → Formats all JS/TS files
**/format src/\*.ts** → Formats TypeScript files in src/
**/format "**/*.jsx"** → Formats all JSX files---
Pattern 2: Subagent Delegation Command
Use Case: Command delegates complex work to agent
Example:
---
description: Review code for quality and security issues
allowed-tools: Task(code-reviewer), Grep, Glob
argument-hint: [file-or-directory]
---
# Review Code
## Parse Arguments
Optional target: `$1` (file, directory, or blank for changed files)
## Your Task
1. **Determine Scope**
- If $1 is provided: Review that file/directory
- If $1 is blank: Find files changed in git (use Grep/Glob)
2. **Prepare Context**
- Get list of files to review
- Read file sizes (for context planning)
- Prepare review prompt with all context
3. **Invoke Reviewer**
- Use Task tool to invoke code-reviewer agent
- Provide prompt: "Review these files: [list]. Check for:
- Security vulnerabilities
- Code quality issues
- Performance problems
- Best practice violations"
4. **Present Results**
- Show review findings organized by severity
- Highlight critical issues first
- Provide actionable recommendations
## Examples
**/review** → Reviews all changed files in current branch
**/review src/auth.ts** → Reviews specific authentication file
**/review src/** → Reviews all files in src directory---
Pattern 3: Multi-Step Workflow Command
Use Case: Command orchestrates complex multi-agent workflow
Example:
---
description: Run full CI/CD pipeline (test, build, deploy)
allowed-tools: Task(test-runner), Task(builder), Task(deployer), Bash
argument-hint: <environment> [service]
---
# CI/CD Pipeline
## Parse Arguments
Required environment: `$1` (staging, production)
Optional service: `$2` (defaults to all services)
## Your Task
### Step 1: Validation
- Check environment is valid (staging or production)
- If production, confirm with user: "Deploy to PRODUCTION? (yes/no)"
- Verify service exists (if specified)
### Step 2: Run Tests
- Invoke test-runner agent with Task tool
- Wait for completion
- If tests fail: STOP and report failures
- If tests pass: Continue to build
### Step 3: Build
- Invoke builder agent with Task tool
- Build for target environment
- If build fails: STOP and report errors
- If build succeeds: Continue to deploy
### Step 4: Deploy
- Invoke deployer agent with Task tool
- Deploy to specified environment
- Monitor deployment progress
- If deployment fails: Trigger rollback
### Step 5: Verification
- Run health checks with Bash
- Verify services are healthy
- Run smoke tests
- Report final status
### Step 6: Notification
- Send notification to team (Slack/email)
- Update deployment tracker
- Log deployment details
## Examples
**/ci-cd staging** → Deploy all services to staging
**/ci-cd staging api-server** → Deploy api-server to staging
**/ci-cd production** → Deploy to production (with confirmation)---
Hook Patterns
Pattern 1: Pre-Flight Validation
Use Case: Validate before dangerous operations
Example:
hooks:
PreToolUse:
- matcher: 'Bash'
hooks:
- type: command
command: |
#!/bin/bash
# Validate bash command safety
COMMAND="$TOOL_INPUT"
# Block dangerous patterns
if echo "$COMMAND" | grep -qE "rm -rf /|sudo rm|format|mkfs"; then
echo "ERROR: Dangerous command blocked: $COMMAND"
exit 1
fi
# Warn on production operations
if echo "$COMMAND" | grep -qi "production"; then
echo "WARNING: Production operation detected"
echo "Please confirm this is intended"
fi
exit 0---
Pattern 2: Automatic Backup
Use Case: Backup files before modification
Example:
hooks:
PreToolUse:
- matcher: 'Write|Edit'
hooks:
- type: command
command: |
#!/bin/bash
# Backup file before modification
FILE="$TOOL_INPUT"
BACKUP_DIR=".backups"
if [ -f "$FILE" ]; then
mkdir -p "$BACKUP_DIR"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
cp "$FILE" "$BACKUP_DIR/$(basename $FILE).$TIMESTAMP.bak"
echo "Backed up: $FILE"
fi
exit 0---
Pattern 3: Post-Processing
Use Case: Automatic formatting after edits
Example:
hooks:
PostToolUse:
- matcher: 'Write|Edit'
hooks:
- type: command
command: |
#!/bin/bash
# Format code after modification
FILE="$TOOL_INPUT"
# Format based on file type
if [[ "$FILE" == *.js || "$FILE" == *.ts ]]; then
npx prettier --write "$FILE"
echo "Formatted: $FILE"
elif [[ "$FILE" == *.py ]]; then
black "$FILE"
echo "Formatted: $FILE"
fi
exit 0---
Integration Patterns
Pattern: Command → Agent → Skills
Use Case: User command delegates to specialized agent with loaded skills
Structure:
User invokes: /translate "Hello world" --lang ja
↓
Command: translate.md
↓
Delegates to: Task(translator)
↓
Agent: translator.md (with skills: translation-expertise, terminology)
↓
Performs: Translation with expert knowledge loaded
↓
Returns: Translated result to userCommand (translate.md):
---
description: Translate text between English, Japanese, and Chinese
argument-hint: [--lang <en|ja|cn>] <text>
allowed-tools: Task(translator)
---
# Translate Command
## Parse Arguments
Arguments: `$ARGUMENTS`
Extract:
- Target language: Look for `--lang <value>` (default: auto-detect)
- Text to translate: Remaining content after flags
## Your Task
1. Parse target language and text
2. Invoke translator agent with Task tool:
- Provide text to translate
- Specify target language
- Request professional translation
3. Return translated text to user
## Examples
**/translate Hello world --lang ja** → Translates to Japanese
**/translate こんにちは --lang en** → Translates to EnglishAgent (translator.md):
---
name: translator
description: Professional translator for English, Japanese, and Chinese. Use when user requests translation.
tools: Read, Write
model: opus
skills: translation-expertise, engineering-terminology
permissionMode: default
---
# Professional Translator
You are an expert translator with deep knowledge of English, Japanese, and Chinese.
[Agent system prompt...]Skills:
translation-expertise: Translation methodology and best practicesengineering-terminology: Technical term translations
Benefits:
- User-friendly interface via command
- Expert translation via specialized agent
- Domain knowledge via loaded skills
- Clean separation of concerns
---
Related Documentation
- Agent Creation Guide - Detailed agent development
- Skills Creation Guide - Detailed skill development
- Commands Creation Guide - Detailed command development
- Hooks Reference Guide - Complete hooks documentation
For official documentation, see SKILL.md.
Skills Creation Guide
Complete guide for creating and configuring Claude Code skills.
Overview
Skills are reusable knowledge packages that can be loaded into conversations or subagents. They provide:
- Domain Expertise: Specialized knowledge Claude lacks
- Terminology: Domain-specific vocabulary and patterns
- Best Practices: Guidelines for specific tasks
- Progressive Disclosure: Split large content across files
File Structure
File Format: Markdown with YAML frontmatter Location: .claude/skills/[skill-name]/SKILL.md
---
name: skill-name
description: What this skill does and when to use it
allowed-tools: Read, Bash
model: sonnet
context: fork
user-invocable: true
---
# Skill Name
## Overview
[Brief overview of skill purpose]
## Core Content
[Main knowledge organized with clear headings]
## Examples
[Concrete usage examples]
## Best Practices
[Guidelines for applying this knowledge]Frontmatter Fields
Required Fields
name (string, max 64 chars)
- Skill identifier
- Must be lowercase with hyphens only
- Gerund form preferred:
analyzing-data,processing-pdfs - Also acceptable:
data-analysis,pdf-processing - Avoid vague names:
helper,utils,tools - Examples:
api-design-patterns,security-best-practices
description (string, max 1024 chars)
- What the skill does and when to use it
- Include trigger terms users would naturally say
- Be specific about the skill's domain
- Examples:
- "REST API design patterns and best practices. Use when designing or reviewing APIs."
- "Python testing with pytest. Use when writing or debugging Python tests."
- "SQL query optimization techniques. Use when analyzing or improving database queries."
Optional Fields
allowed-tools (array or comma-separated string)
- Tools Claude can use without asking permission when this skill is active
- Only applies during skill execution scope
- Syntax:
allowed-tools: Read, Bash(python:*) - Supports comma-separated values or YAML-style lists
- Use for skills that need specific tool access
model (string)
- Model to use when skill is active
- Can be a model alias (
sonnet,opus,haiku) or specific model string (e.g.,claude-sonnet-4-20250514) - Default: inherits from parent context
- Use when skill requires specific model capabilities
context (string)
- Set to
forkto run skill in isolated sub-agent context with its own conversation history - Creates separate conversation thread
- Useful for complex multi-step workflows
- Default: runs in current context
agent (string)
- Specify which agent type to use when
context: forkis set - Can reference:
Explore,Plan,general-purpose, or a custom agent name from.claude/agents/ - Defaults to
general-purposeif not specified - Only valid with
context: fork
hooks (object)
- Lifecycle hooks scoped to skill execution
- Supports
PreToolUse,PostToolUse, andStopevents - See Hooks Reference Guide for details
- Hooks automatically cleaned up when skill completes
user-invocable (boolean)
- Controls whether the skill appears in the slash command menu
- Does not affect the
Skilltool or automatic discovery - Default:
true - Set to
falsefor skills only used internally by agents or Claude programmatically
Content Structure
Basic Skill Template
---
name: skill-name
description: Clear description with trigger terms
---
# Skill Name
## Overview
Brief 2-3 sentence overview of what this skill provides.
## Core Concepts
### Concept 1
[Explanation with examples]
### Concept 2
[Explanation with examples]
## Quick Reference
- Key point 1
- Key point 2
- Key point 3
## Examples
### Example 1: [Scenario]
[Concrete example with code or steps]
### Example 2: [Scenario]
[Concrete example with code or steps]
## Best Practices
1. [Practice 1]
2. [Practice 2]
3. [Practice 3]
## Common Pitfalls
- [Pitfall 1 and how to avoid]
- [Pitfall 2 and how to avoid]Content Best Practices
1. Be concise: Assume Claude is smart, avoid over-explaining 2. Use examples: Concrete examples beat abstract explanations 3. Stay current: Avoid time-sensitive information (dates, versions) 4. Structure clearly: Use headings, lists, and formatting 5. Focus on gaps: Only include what Claude doesn't already know 6. Provide context: Explain when and why to use techniques 7. Add references: Link to external documentation when helpful
Progressive Disclosure Pattern
For skills over 500 lines, split content across multiple files:
skill-name/
├── SKILL.md # Main overview with links (< 500 lines)
├── reference.md # Detailed reference information
├── examples.md # Extended usage examples
├── advanced.md # Advanced topics
└── scripts/
└── helper.py # Utility scripts (executed, not loaded)SKILL.md with Progressive Disclosure
---
name: large-skill
description: Comprehensive knowledge area
---
# Large Skill
## Quick Start
[Essential information for getting started]
## Core Concepts
[Fundamental concepts and patterns]
## Detailed Topics
For in-depth coverage, see:
- **API Reference**: [reference.md](reference.md) - Complete API documentation
- **Usage Examples**: [examples.md](examples.md) - Real-world usage patterns
- **Advanced Topics**: [advanced.md](advanced.md) - Complex scenarios and edge cases
## Quick Reference
[Most commonly used information]
## Utility Scripts
This skill includes helper scripts:
- `python scripts/validate.py <input>` - Validates input format
- `python scripts/generate.py <options>` - Generates boilerplate
Run from the skill directory: `.claude/skills/large-skill/`Progressive Disclosure Rules
1. One level deep: SKILL.md → reference.md, not SKILL.md → advanced.md → details.md 2. Clear boundaries: Each file covers distinct topics 3. Self-contained: Each file can be understood independently 4. Main file focus: SKILL.md should be immediately useful 5. Use TOC for long files: Files >100 lines need table of contents
When to Use Progressive Disclosure
Use progressive disclosure when:
- SKILL.md exceeds 500 lines
- Content has clear topic boundaries
- Some content is advanced/rarely needed
- Examples are extensive
Keep single file when:
- Content is under 500 lines
- Topics are tightly coupled
- All content is equally important
- Splitting would harm readability
Development Workflow
Step 1: Identify the Knowledge Gap
Ask yourself:
- What does Claude need to know?
- What domain-specific terms exist?
- What patterns or best practices apply?
- When would this knowledge be useful?
Step 2: Gather Information
Collect:
- Terminology and definitions
- Common patterns and anti-patterns
- Best practices and guidelines
- Concrete examples
- Reference documentation
Step 3: Organize Content
Structure with:
1. Overview (what and why) 2. Core concepts (fundamentals) 3. Quick reference (commonly used info) 4. Examples (concrete usage) 5. Best practices (how to use well) 6. Pitfalls (what to avoid)
Step 4: Create the Skill
1. Create directory: .claude/skills/[name]/ 2. Create SKILL.md with frontmatter 3. Write concise, focused content 4. Add concrete examples 5. Include trigger terms in description
Step 5: Test
1. Load skill manually or via agent 2. Test with tasks that should trigger it 3. Verify terminology is applied correctly 4. Check if examples are helpful 5. Validate skill triggers appropriately
Step 6: Refine
Based on observed behavior:
- Adjust description if skill doesn't trigger
- Simplify content if Claude seems confused
- Add examples for common misunderstandings
- Split into multiple files if too large
- Remove redundant information
Usage in Components
Skills in Subagents
Load skills into agents via the skills frontmatter field:
---
name: api-developer
description: Develops REST APIs
tools: Read, Write, Edit
skills: api-design-patterns, openapi-spec, security-best-practices
---Key points:
- Full skill content is injected at agent startup
- Skills are in agent's context immediately
- Keep skills list minimal to avoid context bloat
- Skills persist for entire agent session
Skills in Commands
Commands can reference skills indirectly through agents:
---
description: Design a REST API
allowed-tools: Task(api-developer)
---
## Your Task
The api-developer agent has api-design-patterns skill loaded.
Delegate to that agent for API design tasks.Skills with Forked Context
Advanced pattern for isolated skill execution:
---
name: complex-analysis
description: Complex data analysis with isolation
context: fork
agent: data-analyzer
allowed-tools: Read, Bash(python:*)
---Benefits:
- Isolated context for focused work
- Can use specialized agent
- Cleanup automatic when complete
Troubleshooting
Skill Not Loading
Symptoms: Skill doesn't appear or isn't available
Solutions:
1. Check file location: .claude/skills/[name]/SKILL.md 2. Verify YAML frontmatter is valid 3. Ensure name and description fields present 4. Check for YAML syntax errors (no tabs) 5. Restart Claude Code session 6. For agent skills, verify skills list in agent frontmatter
Skill Not Being Applied
Symptoms: Skill loaded but knowledge not used
Solutions:
1. Check description includes clear trigger terms 2. Make description more specific 3. Verify content is concise and clear 4. Reduce content if overly verbose 5. Add concrete examples showing usage 6. Check if multiple skills conflict
Skill Causing Confusion
Symptoms: Claude behaves incorrectly with skill loaded
Solutions:
1. Simplify content - less is often more 2. Remove information Claude already knows 3. Focus on gaps in Claude's knowledge 4. Add clear examples of correct usage 5. Split into smaller, focused skills 6. Check for contradictory information
Progressive Disclosure Not Working
Symptoms: Linked files not being read
Solutions:
1. Verify relative paths are correct 2. Ensure linked files exist in skill directory 3. Check markdown link syntax: [text](file.md) 4. Don't nest more than one level deep 5. Make each file self-contained 6. Test links manually
Common Patterns
Domain Terminology Skill
Use case: Industry-specific vocabulary
---
name: kubernetes-terminology
description: Kubernetes architecture and terminology. Use when working with K8s.
---
# Kubernetes Terminology
## Core Concepts
- **Pod**: Smallest deployable unit, one or more containers
- **Deployment**: Manages replica sets and rolling updates
- **Service**: Stable network endpoint for pods
- **Ingress**: HTTP/HTTPS routing to services
## Quick Reference
[Essential commands and patterns]
## Examples
[Concrete K8s configuration examples]API/Library Reference Skill
Use case: Framework-specific knowledge
---
name: fastapi-patterns
description: FastAPI web framework patterns. Use when building FastAPI applications.
allowed-tools: Read, Bash(python:*)
---
# FastAPI Patterns
## Quick Start
[Basic app structure]
## Core Patterns
### Dependency Injection
[Explanation with code examples]
### Request Validation
[Explanation with code examples]
## Detailed Reference
See [reference.md](reference.md) for complete API documentation.Best Practices Skill
Use case: Guidelines and conventions
---
name: code-review-guidelines
description: Code review best practices. Use when reviewing code or providing feedback.
---
# Code Review Guidelines
## Principles
1. Be constructive and specific
2. Focus on code, not author
3. Explain the "why" behind suggestions
4. Prioritize by severity
## Review Checklist
- [ ] Security vulnerabilities
- [ ] Performance issues
- [ ] Code clarity and maintainability
- [ ] Test coverage
## Examples
[Good and bad review comments]Process/Workflow Skill
Use case: Step-by-step procedures
---
name: deployment-workflow
description: Production deployment process. Use when deploying to production.
---
# Deployment Workflow
## Pre-Deployment Checklist
1. All tests passing
2. Code reviewed and approved
3. Staging validation complete
4. Rollback plan prepared
## Deployment Steps
1. [Step 1]
2. [Step 2]
3. [Step 3]
## Post-Deployment Verification
[Validation steps]
## Rollback Procedure
[Emergency rollback steps]Best Practices Summary
1. Be concise: Only include what Claude doesn't know 2. Use progressive disclosure: Split files over 500 lines 3. Keep references one level deep: Don't nest deeply 4. Include trigger terms: Help skill load automatically 5. Provide examples: Concrete beats abstract 6. Stay current: Avoid time-sensitive information 7. Structure clearly: Use headings and formatting 8. Test thoroughly: Verify skill improves behavior 9. Focus on gaps: Don't explain what Claude knows 10. Add TOC for long files: Files >100 lines need contents
Advanced Topics
Tool Permissions in Skills
Skills can specify allowed tools:
---
name: python-testing
description: Python testing with pytest
allowed-tools: Read, Bash(python:*, pytest:*)
---Benefits:
- Tools available without permission during skill execution
- Scoped to skill's operation
- Automatically cleaned up
Limitations:
- Only applies when skill is actively executing
- Parent context permissions still apply
- Use sparingly for security
Model Selection in Skills
Skills can specify required model:
---
name: creative-writing
description: Creative writing techniques and styles
model: opus
---Use cases:
- Complex reasoning tasks need opus
- Simple lookup tasks can use haiku
- Most skills work with default (sonnet)
Forked Context Skills
Advanced isolation pattern:
---
name: sensitive-analysis
description: Analyzes sensitive data in isolation
context: fork
agent: data-analyzer
allowed-tools: Read
---When to use:
- Sensitive data processing
- Complex multi-step workflows
- Need complete context isolation
- Want automatic cleanup
Trade-offs:
- Higher overhead (separate context)
- Can't access parent context easily
- Good for security and isolation
Hook Integration
Skills can include lifecycle hooks:
---
name: validated-edits
description: File editing with validation
hooks:
PreToolUse:
- matcher: 'Write|Edit'
hooks:
- type: command
command: './scripts/validate-syntax.sh $TOOL_INPUT'
---Use cases:
- Pre-validation before operations
- Post-processing after tool use
- Logging and monitoring
- Cleanup operations
Related Documentation
- Agent Creation Guide - Loading skills into agents
- Commands Creation Guide - Using skills in commands
- Hooks Reference Guide - Adding hooks to skills
- Common Patterns & Examples - More skill examples
For official documentation, see SKILL.md.