Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:57:35 +08:00
commit 6aae23c1d2
19 changed files with 4572 additions and 0 deletions

View File

@@ -0,0 +1,605 @@
# Hooks Guide
## Overview
Hooks are scripts that run in response to Claude Code events, enabling validation, automation, and control over tool execution. Plugins can define hooks to ensure prerequisites are met before operations execute.
**Official Documentation**:
- Hooks: https://docs.claude.com/en/docs/claude-code/hooks
- Plugin Hooks: https://docs.claude.com/en/docs/claude-code/hooks#plugin-hooks
## Hook Types
### PreToolUse
Executes **after** Claude creates tool parameters but **before** the tool actually runs. This allows you to:
- Validate prerequisites (dependencies installed, config set)
- Control tool execution (allow, deny, ask for confirmation)
- Provide context to Claude about environment state
- Block operations that would fail due to missing setup
**Common Use Cases**:
- Check MCP server installation before MCP tool calls
- Verify API keys/credentials before external service calls
- Validate file paths before destructive operations
- Enforce project-specific constraints
- Provide setup guidance when prerequisites are missing
### Other Hook Types
See official documentation for:
- `SessionStart`: Runs when session begins
- `UserPromptSubmit`: Runs when user submits a message
- `BeforeToolUse`: Additional validation before tool execution
- `AfterToolUse`: Post-execution actions
## Directory Structure
```
plugin-name/
├── .claude-plugin/
│ └── plugin.json
├── hooks/
│ └── hooks.json # Hook configuration (required location)
├── scripts/ # Hook scripts (recommended location)
│ ├── check-setup.sh
│ └── validate-config.py
└── README.md
```
**Key Points**:
- `hooks/hooks.json` must be in the `hooks/` directory (or specify custom path in plugin.json)
- Scripts can be anywhere, commonly in `scripts/` directory
- Use `${CLAUDE_PLUGIN_ROOT}` to reference plugin root path in hooks
## Hook Configuration
### hooks.json
```json
{
"PreToolUse": [
{
"matcher": "mcp__plugin_name_server__*",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/check-setup.sh"
}
]
}
```
### Matcher Patterns
**Exact match**:
```json
"matcher": "Write"
```
Matches only the Write tool.
**Regex pattern**:
```json
"matcher": "Edit|Write|MultiEdit"
```
Matches multiple specific tools.
**Wildcard**:
```json
"matcher": "*"
```
Matches all tools (use cautiously).
**MCP tools**:
```json
"matcher": "mcp__*" // All MCP tools
"matcher": "mcp__server__*" // All tools from a server
"matcher": "mcp__server__specific_tool" // Specific MCP tool
```
**Tool name patterns**:
- Built-in: `Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `Task`, `WebFetch`, `WebSearch`
- Notebooks: `NotebookEdit`, `NotebookExecute`
- MCP: `mcp__<server>__<tool>`
### Command Field
Use `${CLAUDE_PLUGIN_ROOT}` to reference scripts:
```json
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/check-setup.sh"
```
This ensures the hook works regardless of where the plugin is installed.
## Writing PreToolUse Hook Scripts
### Input
Your script receives JSON via **stdin**:
```json
{
"hook_event_name": "PreToolUse",
"tool_name": "mcp__grafana__create_incident",
"tool_input": {
"title": "Production outage",
"severity": "critical",
"roomPrefix": "incident"
},
"session_id": "abc123",
"transcript_path": "/path/to/transcript.md",
"cwd": "/current/working/directory"
}
```
**Fields**:
- `hook_event_name`: Always "PreToolUse"
- `tool_name`: Name of the tool being called
- `tool_input`: Parameters Claude wants to pass to the tool (schema varies by tool)
- `session_id`: Unique session identifier
- `transcript_path`: Path to session transcript
- `cwd`: Current working directory
### Output
Your script must output JSON via **stdout**:
```json
{
"hookSpecificOutput": {
"permissionDecision": "allow|deny|ask",
"permissionDecisionReason": "Why this decision was made",
"additionalContext": "Optional message shown to Claude"
}
}
```
**Required Fields**:
**`permissionDecision`** (string, required):
- `"allow"`: Auto-approve tool execution, bypass normal permissions
- `"deny"`: Block tool execution entirely
- `"ask"`: Prompt user for confirmation in UI
**`permissionDecisionReason`** (string, required):
- Brief explanation of why this decision was made
- Shown in logs/UI
- Examples: "Setup verified", "Missing API key", "User confirmation required"
**Optional Fields**:
**`additionalContext`** (string, optional):
- Additional information shown to Claude
- Use for detailed error messages, warnings, setup instructions
- Supports formatted text (newlines, bullets, etc.)
### Exit Codes
**`0` - Success**:
- Hook executed successfully
- Permission decision should be respected
**`2` - Blocking Error**:
- Hook failed, block tool execution
- stderr shown to Claude
- Use for critical validation failures
**Other codes**:
- Treated as errors, behavior may vary
### Best Practices
**1. Always return permission decision**:
```bash
# BAD: Missing permissionDecision
{
"hookSpecificOutput": {
"additionalContext": "Some message"
}
}
# GOOD: Includes required fields
{
"hookSpecificOutput": {
"permissionDecision": "allow",
"permissionDecisionReason": "Setup verified"
}
}
```
**2. Use exit code 2 for blocking**:
```bash
# BAD: Using exit 1
if [ ${#ERRORS[@]} -gt 0 ]; then
echo '{"hookSpecificOutput": {"permissionDecision": "deny", ...}}'
exit 1 # Wrong exit code
fi
# GOOD: Using exit 2
if [ ${#ERRORS[@]} -gt 0 ]; then
echo '{"hookSpecificOutput": {"permissionDecision": "deny", ...}}'
exit 2 # Correct blocking exit code
fi
```
**3. Provide helpful error messages**:
```bash
# GOOD: Actionable error message
"additionalContext": "❌ Setup Issues:\n\n • mcp-server not installed\n • Install from: https://example.com/install\n • Set API_KEY environment variable\n\nPlease resolve these issues to continue."
```
**4. Silent success is OK**:
```bash
# When everything is fine, minimal output is acceptable
{
"hookSpecificOutput": {
"permissionDecision": "allow",
"permissionDecisionReason": "Setup verified"
}
}
# No additionalContext needed
```
**5. Use warnings for non-critical issues**:
```bash
# Allow execution but inform about warnings
{
"hookSpecificOutput": {
"permissionDecision": "allow",
"permissionDecisionReason": "Setup verified with warnings",
"additionalContext": "⚠️ Warnings:\n\n • Connection slow\n • Using fallback config"
}
}
```
## Example: MCP Setup Validation
### hooks/hooks.json
```json
{
"PreToolUse": [
{
"matcher": "mcp__grafana__*",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/check-grafana-setup.sh"
}
]
}
```
### scripts/check-grafana-setup.sh
```bash
#!/bin/bash
set -e
ERRORS=()
WARNINGS=()
# Check if mcp-grafana is installed
if ! command -v mcp-grafana &> /dev/null; then
ERRORS+=("mcp-grafana is not installed. Install from: https://github.com/grafana/mcp-grafana")
fi
# Check if API key is set
if [ -z "${GRAFANA_API_KEY}" ]; then
ERRORS+=("GRAFANA_API_KEY environment variable is not set. Add to ~/.zshrc: export GRAFANA_API_KEY='your-key'")
fi
# Check connectivity (optional, warns but doesn't block)
GRAFANA_URL="${GRAFANA_URL:-https://grafana.example.com}"
if [ -n "${GRAFANA_API_KEY}" ]; then
if ! curl -sf -H "Authorization: Bearer ${GRAFANA_API_KEY}" "${GRAFANA_URL}/api/health" &> /dev/null; then
WARNINGS+=("Unable to connect to Grafana at ${GRAFANA_URL}")
fi
fi
# Build output message
OUTPUT=""
if [ ${#ERRORS[@]} -gt 0 ]; then
OUTPUT="❌ Grafana Plugin Setup Issues:\n\n"
for error in "${ERRORS[@]}"; do
OUTPUT+="${error}\n"
done
OUTPUT+="\nPlease resolve these issues to use Grafana features.\n"
elif [ ${#WARNINGS[@]} -gt 0 ]; then
OUTPUT="⚠️ Grafana Plugin Warnings:\n\n"
for warning in "${WARNINGS[@]}"; do
OUTPUT+="${warning}\n"
done
fi
# Return JSON with permission decision
if [ ${#ERRORS[@]} -gt 0 ]; then
cat << EOF
{
"hookSpecificOutput": {
"permissionDecision": "deny",
"permissionDecisionReason": "Grafana plugin setup is incomplete",
"additionalContext": "$(echo -e "$OUTPUT")"
}
}
EOF
exit 2
elif [ ${#WARNINGS[@]} -gt 0 ]; then
cat << EOF
{
"hookSpecificOutput": {
"permissionDecision": "allow",
"permissionDecisionReason": "Setup verified with warnings",
"additionalContext": "$(echo -e "$OUTPUT")"
}
}
EOF
exit 0
else
cat << EOF
{
"hookSpecificOutput": {
"permissionDecision": "allow",
"permissionDecisionReason": "Grafana plugin setup verified"
}
}
EOF
exit 0
fi
```
### What This Hook Does
1. **Blocks tool execution** if:
- `mcp-grafana` command not found
- `GRAFANA_API_KEY` environment variable not set
2. **Allows with warnings** if:
- Setup is complete but connectivity check fails
3. **Allows silently** if:
- All checks pass
4. **Provides guidance** when blocked:
- Installation instructions
- Configuration steps
- Clear error messages
## Testing Hooks
### Manual Testing
Create a test input file:
```bash
cat > test-input.json << 'EOF'
{
"hook_event_name": "PreToolUse",
"tool_name": "mcp__grafana__create_incident",
"tool_input": {
"title": "Test",
"severity": "critical"
},
"session_id": "test",
"transcript_path": "/tmp/test.md",
"cwd": "/tmp"
}
EOF
```
Test the hook script:
```bash
# Test without setup (should deny)
cat test-input.json | ./scripts/check-setup.sh
echo "Exit code: $?"
# Test with setup (should allow)
export GRAFANA_API_KEY="test-key"
cat test-input.json | ./scripts/check-setup.sh
echo "Exit code: $?"
```
### Validation Checklist
- [ ] Script is executable (`chmod +x`)
- [ ] Returns valid JSON to stdout
- [ ] Includes `permissionDecision` field
- [ ] Includes `permissionDecisionReason` field
- [ ] Uses exit code 2 for blocking errors
- [ ] Uses exit code 0 for success/warnings
- [ ] Error messages are actionable
- [ ] Script handles missing environment variables
- [ ] Matcher pattern is correct in hooks.json
- [ ] Command path uses `${CLAUDE_PLUGIN_ROOT}`
## Common Patterns
### Environment Validation
```bash
# Check required environment variables
REQUIRED_VARS=("API_KEY" "API_URL" "PROJECT_ID")
for var in "${REQUIRED_VARS[@]}"; do
if [ -z "${!var}" ]; then
ERRORS+=("$var environment variable not set")
fi
done
```
### Command Availability
```bash
# Check if command exists
REQUIRED_COMMANDS=("docker" "kubectl" "helm")
for cmd in "${REQUIRED_COMMANDS[@]}"; do
if ! command -v "$cmd" &> /dev/null; then
ERRORS+=("$cmd is not installed")
fi
done
```
### File/Directory Existence
```bash
# Check if required files exist
if [ ! -f "config.yaml" ]; then
ERRORS+=("config.yaml not found")
fi
if [ ! -d ".git" ]; then
ERRORS+=("Not in a git repository")
fi
```
### API Connectivity
```bash
# Check if API is reachable (warning, not error)
if ! curl -sf "${API_URL}/health" &> /dev/null; then
WARNINGS+=("API at ${API_URL} is not reachable")
fi
```
### Conditional Blocking
```bash
# Block only specific tools
if [[ "$tool_name" == *"create_incident"* ]]; then
# Strict validation for incident creation
if [ -z "${ONCALL_SCHEDULE}" ]; then
ERRORS+=("ONCALL_SCHEDULE required for incident creation")
fi
fi
```
## Troubleshooting
### Hook Not Running
**Check**:
- `hooks/hooks.json` exists in correct location
- JSON is valid (`cat hooks/hooks.json | python -m json.tool`)
- Matcher pattern matches the tool name
- Script path is correct and uses `${CLAUDE_PLUGIN_ROOT}`
### Invalid JSON Output
**Check**:
- Script outputs to stdout (not stderr)
- JSON is properly formatted
- No extra output before/after JSON
- Special characters are escaped in strings
### Exit Code Issues
**Remember**:
- Use `exit 2` for blocking (not `exit 1`)
- Use `exit 0` for success
- Check exit code: `echo $?` after running script
### Permission Decision Not Respected
**Ensure**:
- `permissionDecision` field is present
- Value is exactly `"allow"`, `"deny"`, or `"ask"`
- Exit code is 0 or 2 (not other values)
## Best Practices Summary
1. **Always validate** before allowing operations
2. **Provide helpful errors** with clear resolution steps
3. **Use exit code 2** for blocking errors
4. **Return proper JSON** with required fields
5. **Test thoroughly** with and without prerequisites
6. **Make scripts executable** (`chmod +x`)
7. **Use environment variables** for configuration
8. **Handle missing dependencies** gracefully
9. **Warn don't block** for non-critical issues
10. **Keep hooks fast** (< 1 second when possible)
## Security Considerations
### Input Validation
Hooks receive tool parameters from Claude. Be cautious with:
- File paths (could be outside expected directories)
- Command arguments (could contain injection attempts)
- URLs (could point to unexpected destinations)
### Credential Handling
Never:
- Log credentials or API keys
- Include credentials in error messages
- Write credentials to files
Always:
- Read from environment variables
- Validate credential format before use
- Fail safely if credentials are missing
### Least Privilege
Hooks run with user's permissions. Ensure:
- Scripts don't require sudo
- File operations are scoped appropriately
- Network calls are to expected endpoints only
## Advanced Patterns
### Multi-Stage Validation
```bash
# Stage 1: Critical requirements (block if missing)
check_critical_requirements
# Stage 2: Optional requirements (warn if missing)
check_optional_requirements
# Stage 3: Connectivity (warn if unreachable)
check_connectivity
```
### Caching Validation Results
```bash
# Cache validation for performance
CACHE_FILE="/tmp/plugin-validation-cache"
CACHE_TTL=300 # 5 minutes
if [ -f "$CACHE_FILE" ]; then
CACHE_AGE=$(($(date +%s) - $(stat -f %m "$CACHE_FILE")))
if [ $CACHE_AGE -lt $CACHE_TTL ]; then
cat "$CACHE_FILE"
exit 0
fi
fi
# Run validation and cache result
validate > "$CACHE_FILE"
cat "$CACHE_FILE"
```
### Tool-Specific Validation
```bash
# Read tool_name from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
case "$TOOL_NAME" in
"mcp__server__read_only")
# Light validation for read operations
;;
"mcp__server__write")
# Strict validation for write operations
;;
"mcp__server__delete")
# Extra confirmation for destructive operations
echo '{"hookSpecificOutput": {"permissionDecision": "ask", ...}}'
;;
esac
```
## References
- Official Hooks Documentation: https://docs.claude.com/en/docs/claude-code/hooks
- Plugin Hooks: https://docs.claude.com/en/docs/claude-code/hooks#plugin-hooks
- JSON Specification: https://www.json.org/
- Bash Best Practices: https://google.github.io/styleguide/shellguide.html

View File

@@ -0,0 +1,691 @@
# Plugins and Marketplaces Guide
## Overview
Plugins are collections of Claude Code components (agents, commands, skills) packaged for distribution and installation. Plugin marketplaces enable discovery and installation of plugins from repositories.
**Official Documentation**:
- Plugins: https://docs.claude.com/en/docs/claude-code/plugins.md
- Marketplaces: https://docs.claude.com/en/docs/claude-code/plugin-marketplaces.md
## Plugin Structure
A plugin is a directory containing Claude Code components with a marketplace configuration:
```
plugin-name/
├── .claude-plugin/
│ └── marketplace.json # Plugin metadata and component mapping
├── agents/ # Optional: custom agents
│ ├── agent-one.md
│ └── agent-two.md
├── commands/ # Optional: slash commands
│ ├── command-one.md
│ └── command-two.md
├── skills/ # Optional: skills
│ ├── skill-one/
│ │ └── SKILL.md
│ └── skill-two/
│ └── SKILL.md
├── SKILLS.md # Required if skills/ exists
└── README.md # Plugin documentation
```
## Plugin Metadata: plugin.json
Each plugin should include a `plugin.json` file in the `.claude-plugin/` directory:
```json
{
"name": "plugin-name",
"version": "1.0.0",
"description": "Brief description of what the plugin provides",
"author": "Your Name",
"repository": "https://github.com/username/repo",
"keywords": ["swift", "ios", "mobile"],
"category": "development"
}
```
### Fields
**`name`** (string, required)
- Unique identifier for the plugin
- Use kebab-case
- Example: `swift-engineer`, `technical-writer`
**`version`** (string, required)
- Semantic version number
- Format: `MAJOR.MINOR.PATCH`
- Example: `1.0.0`, `2.1.3`
**`description`** (string, required)
- Brief explanation of plugin purpose
- What components it provides
- Who should use it
**`author`** (string, optional)
- Plugin author name or organization
**`repository`** (string, optional)
- URL to source repository
- Enables users to browse code and contribute
**`keywords`** (array of strings, optional)
- Searchable tags
- Technologies, frameworks, use cases
- Example: `["swift", "ios", "xcode"]`
**`category`** (string, optional)
- Plugin category for organization
- Examples: `development`, `documentation`, `testing`, `deployment`
## Marketplace Configuration: marketplace.json
The `.claude-plugin/marketplace.json` file maps plugin components to their file locations:
```json
{
"marketplaceName": "marketplace-name",
"pluginRoot": "./plugins",
"plugins": [
{
"name": "plugin-name",
"source": "./plugins/plugin-name",
"version": "1.0.0",
"description": "Plugin description",
"keywords": ["keyword1", "keyword2"],
"category": "development",
"agents": {
"agent-name": "./agents/agent-name.md"
},
"commands": {
"command-name": "./commands/command-name.md"
},
"skills": {
"skill-name": "./skills/skill-name"
}
}
]
}
```
### Marketplace Fields
**`marketplaceName`** (string)
- Unique identifier for the marketplace
- Used in installation: `/plugin install name@marketplace-name`
**`pluginRoot`** (string)
- Relative path to directory containing all plugins
- Usually `"./plugins"`
**`plugins`** (array)
- List of all plugins in the marketplace
- Each plugin has metadata and component mappings
### Plugin Entry Fields
**`name`** (string, required)
- Plugin identifier
- Must match plugin.json name
**`source`** (string, required)
- Relative path from repository root to plugin directory
- **Must use `./` prefix**: `"./plugins/plugin-name"`
- This is critical for proper plugin discovery
**`version`** (string, required)
- Plugin version, should match plugin.json
**`description`** (string, required)
- Plugin description, should match plugin.json
**`keywords`** (array, optional)
- Searchable keywords
**`category`** (string, optional)
- Plugin category
**`agents`** (object, optional)
- Maps agent names to file paths
- Paths relative to plugin source directory
- Example: `{"ios-expert": "./agents/ios-expert.md"}`
**`commands`** (object, optional)
- Maps command names to file paths
- Paths relative to plugin source directory
- Example: `{"swift-lint": "./commands/swift-lint.md"}`
**`skills`** (object, optional)
- Maps skill names to directory paths
- Paths relative to plugin source directory
- Example: `{"ios-swift-expert": "./skills/ios-swift-expert"}`
### Path Requirements
**Critical**: All paths in marketplace.json must:
1. Be relative, not absolute
2. Use `./` prefix for the `source` field
3. Use forward slashes, even on Windows
4. Point to actual files/directories
**Good**:
```json
"source": "./plugins/swift-engineer"
"agents": {
"ios-expert": "./agents/ios-expert.md"
}
```
**Bad**:
```json
"source": "plugins/swift-engineer" // Missing ./
"source": "/absolute/path/to/plugin" // Absolute path
"agents": {
"ios-expert": "agents\\ios-expert.md" // Backslashes
}
```
## Creating a Plugin
### 1. Plan Your Plugin
Determine:
- What problem does it solve?
- What components are needed (agents, commands, skills)?
- Who is the target audience?
- What tools and workflows will it provide?
### 2. Create Directory Structure
```bash
mkdir -p plugin-name/.claude-plugin
mkdir -p plugin-name/agents
mkdir -p plugin-name/commands
mkdir -p plugin-name/skills
```
### 3. Create plugin.json
```bash
cat > plugin-name/.claude-plugin/plugin.json << 'EOF'
{
"name": "plugin-name",
"version": "1.0.0",
"description": "Your plugin description",
"author": "Your Name",
"keywords": ["tag1", "tag2"],
"category": "development"
}
EOF
```
### 4. Add Components
Create agents, commands, and/or skills following their respective guides:
- See `subagents-guide.md` for agent creation
- See `slash-commands-guide.md` for command creation
- See `skills-guide.md` for skill creation
### 5. Create Documentation
**README.md**:
```markdown
# Plugin Name
Brief description of what the plugin does.
## Components
### Agents
- **agent-name**: Description of agent
### Commands
- **/command-name**: Description of command
### Skills
- **skill-name**: Description of skill
## Installation
Add the marketplace:
\`\`\`
/plugin marketplace add <repository-url>
\`\`\`
Install the plugin:
\`\`\`
/plugin install plugin-name@marketplace-name
\`\`\`
## Usage
[Usage examples and documentation]
```
**SKILLS.md** (if plugin includes skills):
```markdown
# Plugin Skills
## skill-name
Description of what the skill does and when it activates.
### What It Provides
- Capability 1
- Capability 2
### Example Usage
[Brief example]
```
### 6. Register in Marketplace
Add plugin entry to marketplace.json:
```json
{
"marketplaceName": "your-marketplace",
"pluginRoot": "./plugins",
"plugins": [
{
"name": "plugin-name",
"source": "./plugins/plugin-name",
"version": "1.0.0",
"description": "Your plugin description",
"keywords": ["tag1", "tag2"],
"category": "development",
"agents": {
"agent-name": "./agents/agent-name.md"
},
"commands": {
"command-name": "./commands/command-name.md"
},
"skills": {
"skill-name": "./skills/skill-name"
}
}
]
}
```
## Installing Plugins
### Add Marketplace
```bash
/plugin marketplace add /path/to/marketplace
# or
/plugin marketplace add https://github.com/user/marketplace
```
### List Available Plugins
```bash
/plugin list marketplace-name
```
### Install Plugin
```bash
/plugin install plugin-name@marketplace-name
```
### Verify Installation
Check that agents, commands, and skills are available:
- Agents: Use Task tool with subagent_type
- Commands: Type `/command-name`
- Skills: Should activate automatically based on context
## Best Practices
### Plugin Design
**Do:**
- Focus on a specific domain or use case
- Provide comprehensive documentation
- Include usage examples
- Follow semantic versioning
- Test all components before publishing
**Don't:**
- Create overly broad, unfocused plugins
- Duplicate existing functionality
- Include untested components
- Use absolute paths in configurations
### Component Organization
**Agents**: Use when delegatable workflows need isolation
**Commands**: Use for keyboard shortcuts and parameterized tasks
**Skills**: Use for automatic, context-aware guidance
Most plugins should favor **skills** over agents for better UX (automatic activation).
### Documentation
Include in README:
- What problem the plugin solves
- Complete component listing
- Installation instructions
- Usage examples
- Common workflows
- Troubleshooting
Include in SKILLS.md:
- Detailed skill descriptions
- Activation triggers
- What capabilities each skill provides
- Usage examples
### Versioning
Follow semantic versioning:
- **MAJOR**: Breaking changes, incompatible updates
- **MINOR**: New features, backward compatible
- **PATCH**: Bug fixes, backward compatible
Update version in both:
- `plugin.json`
- `marketplace.json` plugin entry
### Testing
Before publishing:
1. **Validate JSON**:
```bash
cat .claude-plugin/marketplace.json | python -m json.tool
cat .claude-plugin/plugin.json | python -m json.tool
```
2. **Test installation**:
```bash
/plugin marketplace add /path/to/your/repo
/plugin install plugin-name@marketplace-name
```
3. **Test components**:
- Invoke each agent
- Run each command
- Trigger each skill
- Verify all work as expected
4. **Verify paths**:
- All files referenced in marketplace.json exist
- Paths are relative with proper `./` prefix
- No broken links in documentation
## Common Patterns
### Single-Purpose Plugin
Plugin with one focused capability:
```
swift-engineer/
├── .claude-plugin/
│ └── plugin.json
├── skills/
│ └── ios-swift-expert/
│ └── SKILL.md
├── commands/
│ └── swift-lint.md
├── SKILLS.md
└── README.md
```
### Multi-Component Plugin
Plugin with multiple related capabilities:
```
web-development/
├── .claude-plugin/
│ └── plugin.json
├── agents/
│ ├── react-expert.md
│ └── api-designer.md
├── commands/
│ ├── create-component.md
│ └── run-dev-server.md
├── skills/
│ ├── react-patterns/
│ │ └── SKILL.md
│ └── api-testing/
│ └── SKILL.md
├── SKILLS.md
└── README.md
```
### Plugin Collection Marketplace
Multiple related plugins in one marketplace:
```
marketplace/
├── .claude-plugin/
│ └── marketplace.json
└── plugins/
├── plugin-one/
│ ├── .claude-plugin/
│ │ └── plugin.json
│ └── [components]
├── plugin-two/
│ ├── .claude-plugin/
│ │ └── plugin.json
│ └── [components]
└── plugin-three/
├── .claude-plugin/
│ └── plugin.json
└── [components]
```
## Marketplace Management
### Adding New Plugins
1. Create plugin directory in `plugins/`
2. Add plugin metadata to `.claude-plugin/plugin.json`
3. Create components
4. Register in `.claude-plugin/marketplace.json`
5. Update main README
6. Test installation
### Updating Plugins
1. Make changes to plugin components
2. Update version in `plugin.json`
3. Update version in `marketplace.json`
4. Document changes in plugin README
5. Test updated plugin
6. Commit and push
### Deprecating Plugins
1. Mark as deprecated in description
2. Add deprecation notice to README
3. Suggest alternative plugins
4. Keep available for backward compatibility
5. Eventually remove from marketplace
## Distribution
### Local Distribution
Share repository path:
```bash
/plugin marketplace add /path/to/marketplace
```
### Git Repository
Host on GitHub/GitLab:
```bash
/plugin marketplace add https://github.com/user/marketplace
```
### Documentation
Provide clear instructions:
1. How to add the marketplace
2. How to install plugins
3. What each plugin provides
4. Usage examples
5. Troubleshooting
## Troubleshooting
### Plugin Not Found
**Issue**: `/plugin install plugin-name@marketplace-name` fails
**Solutions**:
- Verify marketplace is added: `/plugin marketplace list`
- Check plugin name matches marketplace.json
- Ensure marketplace.json is valid JSON
- Verify `source` path has `./` prefix
### Components Not Available
**Issue**: Installed plugin components don't appear
**Solutions**:
- Check component paths in marketplace.json
- Verify files exist at specified paths
- Ensure YAML frontmatter is valid (agents, skills)
- Restart Claude Code session
### Invalid Marketplace JSON
**Issue**: Marketplace JSON validation fails
**Solutions**:
- Validate with JSON linter
- Check for trailing commas
- Verify all paths use forward slashes
- Ensure proper quote escaping
### Skill Not Activating
**Issue**: Skill doesn't trigger in expected contexts
**Solutions**:
- Review skill description for trigger keywords
- Add more specific context triggers
- Verify SKILL.md has valid frontmatter
- Check skill is registered in marketplace.json
## Example: Complete Plugin
**Directory structure**:
```
swift-engineer/
├── .claude-plugin/
│ └── plugin.json
├── agents/
│ └── ios-swift-expert.md
├── commands/
│ └── swift-lint.md
├── skills/
│ └── ios-swift-expert/
│ ├── SKILL.md
│ └── references/
│ └── swift-style-guide.md
├── SKILLS.md
└── README.md
```
**plugin.json**:
```json
{
"name": "swift-engineer",
"version": "1.0.0",
"description": "iOS and macOS development expertise with Swift tooling",
"author": "Scott Jungling",
"repository": "https://github.com/username/claude-plugins",
"keywords": ["swift", "ios", "macos", "xcode", "swiftui"],
"category": "development"
}
```
**marketplace.json entry**:
```json
{
"name": "swift-engineer",
"source": "./plugins/swift-engineer",
"version": "1.0.0",
"description": "iOS and macOS development expertise with Swift tooling",
"keywords": ["swift", "ios", "macos", "xcode", "swiftui"],
"category": "development",
"agents": {
"ios-swift-expert": "./agents/ios-swift-expert.md"
},
"commands": {
"swift-lint": "./commands/swift-lint.md"
},
"skills": {
"ios-swift-expert": "./skills/ios-swift-expert"
}
}
```
**README.md**:
```markdown
# Swift Engineer Plugin
Expert iOS and macOS development assistance with Swift tooling.
## Components
### Skills
**ios-swift-expert**: Automatically activates when working with Swift, SwiftUI, UIKit, Xcode projects, or Apple frameworks. Provides expert guidance on iOS/macOS development.
### Commands
**/swift-lint**: Format and lint Swift code using swift-format
### Agents
**ios-swift-expert**: Delegatable iOS/macOS development expert (prefer using the skill for automatic activation)
## Installation
Add the marketplace:
\`\`\`
/plugin marketplace add https://github.com/username/claude-plugins
\`\`\`
Install the plugin:
\`\`\`
/plugin install swift-engineer@claude-plugins
\`\`\`
## Usage
The ios-swift-expert skill activates automatically when working with Swift code. For example:
- Opening .swift files
- Discussing SwiftUI layouts
- Debugging iOS apps
- Configuring Xcode projects
Use the `/swift-lint` command to format code:
\`\`\`
/swift-lint
\`\`\`
## Requirements
- swift-format installed for linting command
- Xcode for iOS/macOS development
## License
MIT
```
This comprehensive setup provides users with automatic expertise (skill), convenient shortcuts (command), and delegatable workflows (agent).

View File

@@ -0,0 +1,768 @@
# Skills Creation Guide
## Overview
Skills are reusable prompt templates that Claude Code automatically invokes based on context. They provide guidance, patterns, and workflows that activate when relevant without explicit user invocation.
**Official Documentation**: https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview.md
## When to Create a Skill
Create a skill when you need:
- Automatic activation based on context or keywords
- Always-available guidance for specific tasks
- Reusable patterns that apply across projects
- Reference materials bundled with prompts
- Workflows that should be followed consistently
## Directory Structure
Skills are directories containing a `SKILL.md` file and optional bundled resources:
```
skill-name/
├── SKILL.md # Required: main skill definition
├── references/ # Optional: docs loaded into context as needed
│ ├── guide.md
│ └── examples.md
├── assets/ # Optional: files used in output (not loaded into context)
│ ├── templates/
│ │ └── component.tsx
│ └── logo.png
└── scripts/ # Optional: executable utilities
└── helper.py
```
### Location
- Personal: `~/.claude/skills/`
- Plugin: `<plugin-root>/skills/`
- Project: `.claude/skills/`
## SKILL.md Format
Skills require YAML frontmatter followed by the skill content:
```markdown
---
name: skill-name
description: Detailed description including when to use this skill and specific triggers
---
[Skill prompt content with instructions, examples, and guidance]
```
## YAML Frontmatter Fields
**CRITICAL**: Skills support ONLY two frontmatter fields. Do not add any other fields.
### Required Fields
**`name`** (string, max 64 characters)
- Unique identifier for the skill
- Use kebab-case
- Should match directory name
- Example: `ios-swift-expert`, `test-driven-development`
**`description`** (string, max 1024 characters)
- Comprehensive description of what the skill does
- **Critical**: Must include when to use the skill and specific trigger contexts
- Should mention key technologies, frameworks, or patterns
- Used by Claude Code to determine when to activate the skill
- Example:
```yaml
description: Use when working with iOS or macOS development projects, including Swift code, SwiftUI interfaces, Xcode project configuration, iOS frameworks, app architecture, debugging iOS apps, or any Apple platform development tasks.
```
### No Other Fields Are Supported
Unlike subagents, skills only support `name` and `description` in frontmatter. Configuration is done through the skill content itself.
**INVALID - Do Not Use:**
```yaml
---
name: my-skill
description: Valid description
version: 1.0.0 # ❌ NOT SUPPORTED
when_to_use: ... # ❌ NOT SUPPORTED
author: ... # ❌ NOT SUPPORTED
tags: ... # ❌ NOT SUPPORTED
---
```
**Note**: You may encounter skills from other repositories (e.g., superpowers) that use additional fields like `version` or `when_to_use`. These are custom conventions specific to those repositories and are NOT part of the official Claude Code skill specification. Do not copy these fields into Claude Code skills.
## Description Best Practices
The description is **critical** for skill activation. It should:
1. **Use third-person voice**: Write "Expert in X. Automatically activates when..." rather than "Use when..."
2. **List specific technologies**: Mention frameworks, languages, tools
3. **Include task types**: Design, debugging, testing, refactoring, etc.
4. **Reference file patterns**: File extensions, naming patterns
5. **Specify contexts**: Project types, scenarios, workflows
**Good Examples:**
```yaml
description: Expert in iterative design refinement. Automatically activates when creating or developing anything before writing code or implementation plans - refines rough ideas into fully-formed designs through structured Socratic questioning, alternative exploration, and incremental validation
```
```yaml
description: Expert in systematic debugging. Automatically activates when encountering any bug, test failure, or unexpected behavior before proposing fixes - four-phase framework (root cause investigation, pattern analysis, hypothesis testing, implementation) that ensures understanding before attempting solutions
```
```yaml
description: Expert in iOS and macOS development. Automatically activates when working with Swift code, SwiftUI interfaces, Xcode project configuration, iOS frameworks, app architecture, debugging iOS apps, or any Apple platform development tasks
```
**Poor Examples:**
```yaml
description: Helps with Swift development
# Too vague - no trigger contexts, not third-person
```
```yaml
description: Use when building microservices
# Second-person voice instead of third-person
```
```yaml
description: A comprehensive guide to building scalable microservices architectures using cloud-native patterns
# Doesn't clearly state when to activate
```
## Writing Style
Write the entire skill using **imperative/infinitive form** (verb-first instructions), not second person. Use objective, instructional language that Claude can follow directly.
**Do** (Imperative/Infinitive):
- "To accomplish X, do Y"
- "Start with step 1"
- "Analyze the code for patterns"
- "Create a test file"
- "Avoid using global state"
**Don't** (Second Person):
- "You should do X"
- "If you need to do X"
- "You can analyze the code"
- "You will create a test file"
- "You shouldn't use global state"
This style maintains consistency and clarity for AI consumption while keeping the skill content focused on actionable instructions rather than conversational guidance.
## Skill Creation Workflow
Follow this structured process to create effective skills:
### Step 1: Understand the Skill with Concrete Examples
Skip this step only when the skill's usage patterns are already clearly understood.
Clearly understand concrete examples of how the skill will be used. Gather these through:
- Direct user examples of tasks they perform repeatedly
- Generated examples that are validated with user feedback
- Real-world scenarios from past work
**Key questions to answer**:
- What functionality should the skill support?
- What specific tasks would trigger this skill?
- What would a user say or do that should activate it?
- What file types, technologies, or contexts are involved?
Avoid overwhelming with too many questions at once. Start with the most important and follow up as needed.
**Conclude when**: There is a clear sense of the functionality the skill should support.
### Step 2: Plan the Reusable Skill Contents
Analyze each concrete example to identify what bundled resources would help:
For each example, consider:
1. How to execute the task from scratch
2. What gets rewritten repeatedly (→ candidate for `scripts/`)
3. What documentation would help (→ candidate for `references/`)
4. What templates or assets would help (→ candidate for `assets/`)
**Example analysis**:
- "Help me rotate this PDF" → `scripts/rotate_pdf.py` (same code rewritten each time)
- "Build me a todo app" → `assets/frontend-template/` (same boilerplate each time)
- "Query user data from BigQuery" → `references/schema.md` (need to rediscover schemas each time)
**Output**: A list of scripts, references, and assets to include in the skill.
### Step 3: Initialize the Skill
Create the skill structure using the initialization script from the Anthropic skills repository:
```bash
uvx --from git+https://github.com/anthropics/skills init_skill.py <skill-name> --path <output-directory>
```
This script:
- Creates the skill directory at the specified path
- Generates a SKILL.md template with proper frontmatter and placeholders
- Creates example resource directories: `scripts/`, `references/`, and `assets/`
- Adds example files in each directory that can be customized or deleted
**Alternative**: Manually create the directory structure if the script is not available, but the script ensures proper formatting and structure.
### Step 4: Implement the Skill
**Start with bundled resources**:
1. Create the scripts, references, and assets identified in Step 2
2. This may require user input (e.g., brand assets, company documentation)
3. Delete any example files/directories not needed for the skill
**Update SKILL.md**:
Answer these questions in the skill content:
1. What is the purpose of the skill? (brief overview)
2. When should the skill be used? (activation contexts)
3. How should Claude use the skill in practice?
**Remember**:
- Use third-person voice in description
- Use imperative/infinitive form in skill content
- Reference all bundled resources so Claude knows how to use them
- Keep SKILL.md lean; move detailed content to references files
- Include concrete examples where helpful
### Step 5: Package and Validate the Skill
Package the skill into a distributable format using the packaging script:
```bash
uvx --from git+https://github.com/anthropics/skills package_skill.py <path/to/skill-folder> [output-directory]
```
The script will:
1. **Validate** the skill automatically:
- YAML frontmatter format and required fields
- Skill naming conventions and directory structure
- Description completeness and quality
- File organization and resource references
2. **Package** the skill if validation passes:
- Creates a zip file named after the skill (e.g., `my-skill.zip`)
- Includes all files with proper directory structure
- Ready for distribution or installation
If validation fails, fix the reported errors and run again.
### Step 6: Test and Iterate
After testing the skill in real usage:
1. Use the skill on real tasks
2. Notice struggles or inefficiencies
3. Identify how SKILL.md or bundled resources should be updated
4. Implement changes and test again
**Common iterations**:
- Refining description to improve activation triggers
- Moving content between SKILL.md and references files
- Adding missing examples or patterns
- Creating additional scripts for repeated tasks
## Skill Content Structure
### Recommended Sections
1. **Quick Start** - Immediate, actionable guidance
```markdown
## Quick Start
When [trigger context], follow these steps:
1. [Step 1]
2. [Step 2]
3. [Step 3]
```
2. **Core Principles** - Fundamental concepts
```markdown
## Core Principles
- Principle 1: [explanation]
- Principle 2: [explanation]
```
3. **Workflows** - Step-by-step processes
```markdown
## Workflow
### [Specific Task]
1. [Step with details]
2. [Step with details]
```
4. **Examples** - Concrete usage scenarios
```markdown
## Examples
<example>
Context: [scenario]
user: [user request]
assistant: [correct response]
</example>
```
5. **Common Pitfalls** - What to avoid
```markdown
## Common Pitfalls
**Don't:**
- [Pitfall 1]
- [Pitfall 2]
**Do:**
- [Best practice 1]
- [Best practice 2]
```
6. **References** - Links to bundled materials
```markdown
## Bundled Resources
See `references/guide.md` for detailed patterns.
See `assets/templates/template.txt` for starter code.
```
## Bundling Reference Materials
Skills can include supporting files in the skill directory. Understanding when and how to use each type is critical for effective skill design.
### Progressive Disclosure: 3-Level Loading System
Skills use a three-level loading system to manage context efficiently:
1. **Metadata (name + description)** - Always loaded into context (~100 words)
2. **SKILL.md body** - Loaded when skill triggers (<5k words recommended)
3. **Bundled resources** - Loaded as needed by Claude (varies by type)
This design keeps the context window lean while making specialized knowledge available when needed.
### Resource Types and Context Loading
**Critical distinction**: Different resource types have different relationships with the context window.
#### Scripts (`scripts/`)
**Purpose**: Executable code (Python, Bash, etc.) for tasks requiring deterministic reliability or repeatedly rewritten code.
**Context loading**: May be executed **without loading into context window**
**When to include**:
- Same code is being rewritten repeatedly
- Deterministic reliability is needed
- Task is procedural and automatable
**Examples**:
- `scripts/rotate_pdf.py` - PDF rotation utility
- `scripts/validate_schema.sh` - Schema validation
- `scripts/generate_boilerplate.py` - Code generation
**Benefits**: Token efficient, deterministic, can execute without reading into context
**Note**: Scripts may still need to be read by Claude for patching or environment-specific adjustments
#### References (`references/`)
**Purpose**: Documentation and reference material **loaded INTO context as needed** to inform Claude's process and thinking.
**Context loading**: **YES** - Loaded into context when Claude determines it's needed
**When to include**:
- Documentation that Claude should reference while working
- Detailed information too extensive for SKILL.md
- Domain knowledge, schemas, or specifications
- Detailed workflow guides or examples
**Examples**:
- `references/database_schema.md` - Database table structures
- `references/api_docs.md` - API specifications
- `references/company_policies.md` - Company-specific guidelines
- `references/advanced_patterns.md` - Detailed implementation patterns
**Benefits**: Keeps SKILL.md lean while making detailed information discoverable and loadable on demand
**Best practice for large files**: If reference files exceed 10k words, include grep search patterns in SKILL.md to help Claude find relevant sections efficiently.
#### Assets (`assets/`)
**Purpose**: Files **NOT intended to be loaded into context**, but rather **used within the output** Claude produces.
**Context loading**: **NO** - Not loaded into context; copied, modified, or used in final output
**When to include**:
- Files that will be used in the final output
- Templates that get copied or modified
- Images, fonts, or other binary resources
- Boilerplate code or project scaffolding
**Examples**:
- `assets/templates/component-template.tsx` - React component boilerplate
- `assets/logo.png` - Brand assets
- `assets/slides-template.pptx` - PowerPoint template
- `assets/frontend-skeleton/` - Complete project starter
**Benefits**: Separates output resources from documentation, enables Claude to use files without loading them into context
### Avoid Duplication
**Important principle**: Information should live in either SKILL.md or references files, **not both**.
Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window. Keep only essential procedural instructions and workflow guidance in SKILL.md; move detailed reference material, schemas, and examples to references files.
### Runtime Environment Constraints
**Important**: Skills run in Claude Code's runtime environment:
- No network access during skill execution
- No package installation during execution
- Must be self-contained
- Can reference bundled materials
- Scripts can execute if dependencies are available in the environment
## Naming Conventions
- Use **kebab-case** for skill directory names
- Be descriptive and searchable
- Indicate domain or capability
- Match the `name` field in SKILL.md
- Examples:
- `ios-swift-expert`
- `test-driven-development`
- `systematic-debugging`
- `brainstorming`
## Skills vs Subagents vs Commands
**Use Skills when:**
- Guidance should activate automatically
- Users shouldn't need to remember to invoke it
- Pattern applies across many contexts
- You want always-available best practices
- Example: Code style guides, testing patterns
**Use Subagents when:**
- You need explicit invocation control
- Workflow is delegatable and isolated
- You need different tool restrictions
- Context isolation is important
- Example: Specialized code reviews, complex migrations
**Use Commands when:**
- Workflow is simple and linear
- You want a keyboard shortcut
- No complex decision-making needed
- Example: Format code, run tests
## Testing Your Skill
1. **Verify Activation Context**
- Create test scenarios matching your description
- Check if skill activates appropriately
- Refine description triggers if needed
2. **Test Instructions**
- Follow the skill guidance yourself
- Ensure steps are clear and actionable
- Verify examples are correct
3. **Validate References**
- Ensure bundled files are accessible
- Check file paths are correct
- Test any included scripts
4. **YAML Validation**
- Verify frontmatter is valid YAML
- Check name/description lengths
- Ensure no unsupported fields
## Plugin Integration
When including skills in plugins:
1. Create `skills/` subdirectory in plugin root
2. Place each skill in its own directory under `skills/`
3. Create `SKILLS.md` index file (required for plugin skills)
4. Register in `.claude-plugin/marketplace.json`:
```json
{
"skills": {
"skill-name": "./skills/skill-name"
}
}
```
### SKILLS.md Index Format
The `SKILLS.md` file documents all skills in the plugin:
```markdown
# Plugin Skills
This plugin provides the following skills:
## skill-name
[Description from SKILL.md]
### When to Use
- [Trigger scenario 1]
- [Trigger scenario 2]
### What It Provides
- [Capability 1]
- [Capability 2]
### Example Usage
[Brief example]
---
## another-skill
[Description and details for next skill]
```
## Example: Complete Skill
```markdown
---
name: api-testing-patterns
description: Expert in API testing patterns. Automatically activates when writing tests for REST APIs, GraphQL endpoints, or API integration tests - provides patterns for request mocking, response validation, authentication testing, and error scenario coverage
---
# API Testing Patterns
## Quick Start
When testing API endpoints:
1. **Arrange**: Set up test data and mocks
2. **Act**: Make the API request
3. **Assert**: Validate response status, headers, and body
4. **Cleanup**: Reset state for next test
## Core Principles
- **Test contracts, not implementation**: Focus on API behavior and response formats
- **Cover happy path and edge cases**: Success, validation errors, authentication failures
- **Mock external dependencies**: Don't hit real external APIs in tests
- **Use test fixtures**: Maintain consistent test data
- **Validate schemas**: Ensure responses match expected structure
## REST API Testing Patterns
### Basic Request/Response Test
```javascript
test('GET /users/:id returns user', async () => {
const response = await request(app)
.get('/users/123')
.set('Authorization', 'Bearer test-token')
.expect(200)
.expect('Content-Type', /json/);
expect(response.body).toMatchObject({
id: '123',
name: expect.any(String),
email: expect.any(String)
});
});
```
### Testing Error Scenarios
```javascript
test('GET /users/:id returns 404 for missing user', async () => {
const response = await request(app)
.get('/users/nonexistent')
.set('Authorization', 'Bearer test-token')
.expect(404);
expect(response.body).toEqual({
error: 'User not found',
code: 'USER_NOT_FOUND'
});
});
```
### Testing Authentication
```javascript
test('requires valid authentication token', async () => {
await request(app)
.get('/users/123')
.expect(401);
await request(app)
.get('/users/123')
.set('Authorization', 'Bearer invalid-token')
.expect(401);
});
```
## GraphQL Testing Patterns
### Query Testing
```javascript
test('users query returns list of users', async () => {
const query = `
query {
users {
id
name
email
}
}
`;
const response = await request(app)
.post('/graphql')
.send({ query })
.expect(200);
expect(response.body.data.users).toBeInstanceOf(Array);
expect(response.body.errors).toBeUndefined();
});
```
### Mutation Testing
```javascript
test('createUser mutation creates user', async () => {
const mutation = `
mutation CreateUser($input: UserInput!) {
createUser(input: $input) {
id
name
email
}
}
`;
const variables = {
input: {
name: 'Test User',
email: 'test@example.com'
}
};
const response = await request(app)
.post('/graphql')
.send({ query: mutation, variables })
.expect(200);
expect(response.body.data.createUser).toMatchObject({
id: expect.any(String),
name: 'Test User',
email: 'test@example.com'
});
});
```
## Common Pitfalls
**Don't:**
- Test internal implementation details
- Make real API calls to external services
- Share state between tests
- Use hardcoded timestamps or IDs
- Skip error scenario testing
**Do:**
- Mock external dependencies
- Use test fixtures and factories
- Validate response schemas
- Test all status codes
- Clean up after each test
## Test Organization
```
tests/
├── api/
│ ├── users.test.js
│ ├── posts.test.js
│ └── auth.test.js
├── fixtures/
│ ├── users.js
│ └── posts.js
└── helpers/
├── setup.js
└── mock-server.js
```
## References
- See `references/http-status-codes.md` for complete status code reference
- See `assets/templates/api-test-template.js` for test boilerplate
- See `references/examples/complete-api-test-suite.js` for comprehensive examples
```
## Advanced Patterns
### Conditional Guidance
Use examples with different contexts to show when to apply different approaches:
```markdown
<example>
Context: Simple CRUD API with few endpoints
Recommended: Use inline test data
</example>
<example>
Context: Complex API with many interdependent resources
Recommended: Use factory pattern with test fixtures
</example>
```
### Progressive Disclosure
Start with quick patterns, then link to detailed references:
```markdown
## Quick Pattern
Use this for most cases:
[Simple example]
## Advanced Scenarios
For complex cases, see `references/advanced-patterns.md`:
- Nested resource testing
- Streaming response validation
- Webhook testing
```
### Checklists
Include actionable checklists for systematic execution:
```markdown
## API Test Checklist
Before merging API changes:
- [ ] Happy path tested with valid input
- [ ] Validation errors tested with invalid input
- [ ] Authentication/authorization tested
- [ ] Rate limiting tested
- [ ] Response schema validated
- [ ] Error responses follow format
- [ ] Documentation updated
```
## Skill Discovery
Skills are automatically discovered by Claude Code when:
- Placed in recognized skill directories
- SKILL.md has valid YAML frontmatter
- Name and description fields are present
- Plugin marketplace.json correctly references the skill
Claude Code uses the description to determine when to activate each skill, so make descriptions comprehensive and trigger-focused.

View File

@@ -0,0 +1,607 @@
# Slash Commands Creation Guide
## Overview
Slash commands are custom shortcuts that execute specific workflows or expand into prompts. They provide quick access to common operations and can accept arguments for dynamic behavior.
**Official Documentation**: https://docs.claude.com/en/docs/claude-code/slash-commands.md
## When to Create a Slash Command
Create a slash command when you need:
- Quick keyboard shortcuts for common tasks
- Parameterized workflows with user input
- Simple, linear execution flows
- Convenience wrappers around common operations
- Reusable prompts with argument substitution
## File Structure
Slash commands are markdown files that can optionally include YAML frontmatter:
```markdown
---
description: Clear one-line description of what this command does
allowed-tools:
- Bash(npm run build:*)
- Bash(npm test:*)
args:
- name: target
description: The build target to compile
---
[Command prompt content with instructions and optional argument placeholders]
```
### Location
- Personal: `~/.claude/commands/`
- Plugin: `<plugin-root>/commands/`
- Project: `.claude/commands/`
### Naming
- Use **kebab-case** for command file names
- File name becomes the command name
- `format-code.md``/format-code`
- `run-tests.md``/run-tests`
## YAML Frontmatter
Frontmatter is **optional** but recommended for:
- Documenting command purpose
- Preapproving tools and bash commands
- Defining expected arguments
### Fields
**`description`** (string, optional)
- One-line explanation of command purpose
- Shown in command lists and help
- Example: `Format and lint Swift code using swift-format`
**`allowed-tools`** (array, optional)
- Preapprove bash commands and tools for execution
- Uses glob patterns for flexibility
- Reduces user approval friction
- Example:
```yaml
allowed-tools:
- Bash(echo:*)
- Bash(git:*)
- Bash(npm run build:*)
- Bash(swift-format:*)
```
**`args`** (array of objects, optional)
- Document expected command arguments
- Each arg has `name` and `description`
- For documentation only - doesn't enforce validation
- Example:
```yaml
args:
- name: environment
description: Target environment (dev, staging, prod)
- name: version
description: Version tag to deploy
```
## Tool Preapprovals
The `allowed-tools` field uses specific syntax:
### Bash Commands
```yaml
allowed-tools:
- Bash(command:*) # Allow command with any arguments
- Bash(git:*) # Allow all git commands
- Bash(npm run build:*) # Allow npm run build variants
- Bash(echo:*) # Allow echo
- Bash(find:*) # Allow find
```
### Other Tools
You can also preapprove Claude Code tools:
```yaml
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash(*) # Allow all bash commands (use carefully)
```
### Best Practices
**Do:**
- Be specific with command patterns
- Use wildcards for argument flexibility
- Include only necessary commands
- Consider security implications
**Don't:**
- Preapprove dangerous commands (rm -rf, etc.) unless absolutely necessary
- Use `Bash(*)` unless you fully trust the command
- Preapprove commands not used by the workflow
## Argument Handling
Commands can accept and use arguments through placeholders:
### Argument Placeholders
- `$ARGUMENTS` - All arguments as a single string
- `$1`, `$2`, `$3`, etc. - Individual positional arguments
- `$N` - Nth argument (1-indexed)
### Example: Parameterized Command
```markdown
---
description: Deploy application to specified environment
allowed-tools:
- Bash(git:*)
- Bash(npm run deploy:*)
args:
- name: environment
description: Target environment (dev, staging, prod)
---
Deploy the application to the $1 environment.
Steps:
1. Verify the git branch is clean
2. Run the deployment script for $1
3. Verify deployment succeeded
4. Update deployment tracking
Use: /deploy prod
```
Usage: `/deploy staging` → `$1` becomes `staging`
### Example: Multiple Arguments
```markdown
---
description: Create a new feature branch
allowed-tools:
- Bash(git:*)
args:
- name: branch-name
description: Name of the feature branch
- name: base-branch
description: Base branch to branch from (default: main)
---
Create a new feature branch named "$1" from base branch "$2".
1. Checkout the base branch: $2
2. Pull latest changes
3. Create and checkout new branch: $1
4. Push the new branch to remote
Use: /create-branch my-feature main
```
Usage: `/create-branch user-auth develop` → `$1` = `user-auth`, `$2` = `develop`
## Command Content
The markdown content after frontmatter is the command's prompt/instructions:
### Simple Commands
Direct instructions that execute immediately:
```markdown
---
description: Run the test suite
allowed-tools:
- Bash(npm test:*)
---
Run the complete test suite using npm test. Report any failures with details.
```
### Workflow Commands
Multi-step processes with clear guidance:
```markdown
---
description: Prepare a release
allowed-tools:
- Bash(git:*)
- Bash(npm:*)
args:
- name: version
description: Semantic version for the release (e.g., 1.2.3)
---
Prepare a new release version $1:
1. Update version in package.json to $1
2. Update CHANGELOG.md with version $1 and today's date
3. Commit changes with message "chore: prepare release $1"
4. Create git tag v$1
5. Build the project
6. Ask user if ready to push tag and publish
Use: /prepare-release 1.2.3
```
### Commands with Subagents
Delegate complex work to specialized agents:
```markdown
---
description: Write comprehensive API documentation
allowed-tools:
- Task
---
Use the technical-writer agent to create comprehensive API documentation for the current project.
The documentation should include:
- API overview and getting started
- Authentication guide
- Endpoint reference with examples
- Error handling
- Rate limiting
- Code examples in multiple languages
Analyze the codebase first, then delegate to the technical-writer agent.
```
## Common Patterns
### Code Quality Commands
```markdown
---
description: Format and lint Swift code
allowed-tools:
- Bash(swift-format:*)
- Bash(find:*)
---
Format and lint all Swift code in the project:
1. Find all .swift files
2. Run swift-format on each file
3. Report any formatting issues
4. Fix issues automatically where possible
```
### Git Workflow Commands
```markdown
---
description: Create a conventional commit
allowed-tools:
- Bash(git:*)
---
Create a conventional commit following the format:
type(scope): description
Where type is one of: feat, fix, docs, style, refactor, test, chore
1. Show current git status
2. Ask user for commit type and scope
3. Ask for commit description
4. Create commit with conventional format
5. Include Claude Code co-author
```
### Project Setup Commands
```markdown
---
description: Initialize a new TypeScript project
allowed-tools:
- Bash(npm:*)
- Bash(mkdir:*)
- Write
---
Initialize a new TypeScript project with best practices:
1. Create directory structure (src/, tests/, dist/)
2. Initialize npm package
3. Install TypeScript and development dependencies
4. Create tsconfig.json with strict settings
5. Create initial src/index.ts
6. Set up test framework
7. Create README.md
Ask user for project name and description first.
```
### Deployment Commands
```markdown
---
description: Deploy to production
allowed-tools:
- Bash(git:*)
- Bash(npm run build:*)
- Bash(gh:*)
args:
- name: version
description: Version to deploy (defaults to current)
---
Deploy version $1 to production:
⚠️ WARNING: This will deploy to PRODUCTION
1. Confirm with user before proceeding
2. Verify git branch is main
3. Verify working directory is clean
4. Run production build
5. Run smoke tests
6. Create GitHub release
7. Trigger deployment pipeline
8. Monitor deployment status
Use: /deploy-prod 1.2.3
```
## Testing Your Command
1. **Invoke the command**:
```
/your-command arg1 arg2
```
2. **Verify behavior**:
- Do arguments substitute correctly?
- Are tools preapproved appropriately?
- Does the workflow execute as expected?
3. **Test edge cases**:
- Missing arguments
- Invalid arguments
- Error conditions
4. **Refine**:
- Update allowed-tools if approval prompts appear
- Clarify instructions if behavior is unexpected
- Add error handling guidance
## Commands vs Skills vs Subagents
**Use Commands when:**
- Workflow is straightforward and linear
- You want a quick keyboard shortcut
- Users will invoke explicitly
- Arguments customize behavior
- Example: /format-code, /run-tests, /deploy
**Use Skills when:**
- Guidance should activate automatically
- Pattern applies across contexts
- Always-available best practices
- No explicit invocation needed
- Example: Code style patterns, debugging workflows
**Use Subagents when:**
- Complex decision-making required
- Context isolation needed
- Delegatable, self-contained workflows
- Specialized tool restrictions
- Example: Code reviews, technical writing
## Plugin Integration
When including commands in plugins:
1. Place command markdown files in `commands/` subdirectory
2. Register in `.claude-plugin/marketplace.json`:
```json
{
"commands": {
"command-name": "./commands/command-name.md"
}
}
```
3. Document in plugin README.md
4. Test command installation and execution
## Example: Complete Command
```markdown
---
description: Create a new React component with tests and storybook
allowed-tools:
- Bash(mkdir:*)
- Write
- Edit
args:
- name: component-name
description: Name of the component (PascalCase)
- name: component-type
description: Type of component (functional or class, defaults to functional)
---
# Create React Component: $1
Create a new React component named $1 as a $2 component.
## Steps
1. **Create component directory**:
```
src/components/$1/
```
2. **Create component file**: `src/components/$1/$1.tsx`
```tsx
import React from 'react';
import styles from './$1.module.css';
interface ${1}Props {
// TODO: Define props
}
export const $1: React.FC<${1}Props> = (props) => {
return (
<div className={styles.container}>
<h2>$1</h2>
</div>
);
};
```
3. **Create styles**: `src/components/$1/$1.module.css`
```css
.container {
/* Component styles */
}
```
4. **Create test file**: `src/components/$1/$1.test.tsx`
```tsx
import { render, screen } from '@testing-library/react';
import { $1 } from './$1';
describe('$1', () => {
it('renders without crashing', () => {
render(<$1 />);
expect(screen.getByText('$1')).toBeInTheDocument();
});
});
```
5. **Create Storybook story**: `src/components/$1/$1.stories.tsx`
```tsx
import type { Meta, StoryObj } from '@storybook/react';
import { $1 } from './$1';
const meta: Meta<typeof $1> = {
title: 'Components/$1',
component: $1,
};
export default meta;
type Story = StoryObj<typeof $1>;
export const Default: Story = {
args: {},
};
```
6. **Create index file**: `src/components/$1/index.ts`
```ts
export { $1 } from './$1';
export type { ${1}Props } from './$1';
```
7. **Update main components index**: Add to `src/components/index.ts`:
```ts
export { $1 } from './$1';
```
## Usage Examples
```bash
# Create functional component (default)
/create-component Button
# Create class component
/create-component Modal class
```
## Next Steps
After creating the component:
1. Define the component props interface
2. Implement component logic
3. Add styles
4. Write comprehensive tests
5. Create Storybook stories for different states
6. Update documentation
```
## Advanced Techniques
### Conditional Logic
Guide Claude to make decisions based on arguments:
```markdown
If $1 is "production":
- Use production configuration
- Require manual confirmation
- Enable extra validation
If $1 is "development":
- Use development configuration
- Skip confirmation
- Allow warnings
```
### Error Handling
Include guidance for error scenarios:
```markdown
If the build fails:
1. Show the error output
2. Suggest common fixes
3. Ask user if they want to retry
If tests fail:
1. Report which tests failed
2. Show failure details
3. Ask if user wants to run only failed tests
```
### Checklists
Provide systematic validation:
```markdown
Before deploying:
- [ ] All tests pass
- [ ] Build succeeds
- [ ] Version updated
- [ ] CHANGELOG updated
- [ ] Git working directory clean
- [ ] On correct branch
```
## Security Considerations
**Be careful with:**
- Commands that modify production systems
- Commands that delete files or data
- Commands with elevated privileges
- Commands that expose secrets
**Best practices:**
- Require confirmation for destructive operations
- Validate inputs before execution
- Limit preapproved commands to minimum necessary
- Document security implications
- Consider using read-only operations where possible
## Discoverability
Users discover commands through:
- `/help` command output
- Plugin documentation
- Tab completion in Claude Code
- README files
Make commands discoverable by:
- Using clear, descriptive names
- Writing good descriptions in frontmatter
- Documenting in plugin README
- Using conventional naming patterns

View File

@@ -0,0 +1,339 @@
# Subagent Creation Guide
## Overview
Subagents are specialized AI agents with custom system prompts and behaviors. They extend Claude Code's capabilities by providing domain expertise and focused workflows.
**Official Documentation**: https://docs.claude.com/en/docs/claude-code/sub-agents.md
## When to Create a Subagent
Create a subagent when you need:
- Specialized domain expertise (e.g., iOS development, technical writing)
- Consistent behavior patterns for specific tasks
- Delegatable workflows that run independently
- Context isolation from the main session
## File Structure
Subagents are markdown files with YAML frontmatter:
```markdown
---
name: agent-name
description: Agent description with usage examples
model: inherit
color: green
tools: Read, Write, Edit, Bash, Glob
---
[Agent system prompt content]
```
### Location
- Personal: `~/.claude/agents/`
- Plugin: `<plugin-root>/agents/`
- Project: `.claude/agents/`
## YAML Frontmatter Fields
### Required Fields
**`name`** (string, kebab-case)
- Unique identifier for the agent
- Used in Task tool invocations
- Example: `ios-swift-expert`, `technical-writer`
**`description`** (string)
- Clear explanation of what the agent does
- Should include usage examples wrapped in `<example>` tags
- Visible to users when selecting agents
- Example:
```yaml
description: Expert in Python linting and code quality analysis. Use when reviewing Python code for style violations, potential bugs, or best practice violations. Examples: <example>user: "Review my Python code for linting issues" assistant: "Let me use the python-linter agent to analyze your code for quality issues" <commentary>Python linting requires knowledge of PEP 8 and common Python anti-patterns.</commentary></example>
```
### Optional Fields
**`model`** (string)
- Specifies which model to use
- Use `inherit` to use the same model as the parent session
- Default: `inherit`
- Other options: specific model identifiers (use sparingly)
**`color`** (string)
- Display color in the UI
- Options: `blue`, `green`, `yellow`, `red`, `purple`, `cyan`, `magenta`
- Default: system default
**`tools`** (comma-separated list)
- Pre-approve specific tools for the agent
- Common tools: `Read`, `Write`, `Edit`, `Bash`, `Glob`, `Grep`, `WebFetch`
- Restricts agent to only listed tools (improves focus and safety)
- Example: `tools: Read, Write, Edit`
## System Prompt Best Practices
### Structure
1. **Identity Statement**: Clearly state what the agent is
```markdown
You are an expert in iOS and macOS development with deep knowledge of Swift, SwiftUI, UIKit, and Apple frameworks.
```
2. **Expertise Areas**: List specific capabilities
```markdown
## Your Expertise
You specialize in:
- Swift language features and best practices
- SwiftUI declarative interface design
- UIKit view hierarchies and lifecycle
```
3. **Workflow Guidance**: Provide step-by-step processes
```markdown
## Workflow
When implementing features:
1. Analyze requirements
2. Design data models
3. Create views
4. Test functionality
```
4. **Reference Resources**: Link to documentation
```markdown
## Documentation References
- Apple Developer: https://developer.apple.com/documentation/
- Swift.org: https://swift.org/documentation/
```
5. **Success Criteria**: Define what good looks like
```markdown
## Success Criteria
Your code is successful when:
- It compiles without warnings
- It follows Swift API design guidelines
- It handles errors appropriately
```
### Writing Effective Prompts
**Do:**
- Be specific about the agent's expertise boundaries
- Include concrete examples of when to use the agent
- Provide step-by-step workflows for common tasks
- Reference authoritative documentation
- Define clear success criteria
**Don't:**
- Make the agent too general-purpose
- Include tasks better suited for skills or commands
- Duplicate main Claude Code capabilities
- Create overly complex nested workflows
## Naming Conventions
- Use **kebab-case** for agent names
- Be descriptive but concise
- Indicate domain or specialty
- Examples:
- `ios-swift-expert`
- `technical-writer`
- `cli-ux-designer`
- `yaml-recipe-expert`
## Testing Your Subagent
1. **Invoke with Task tool**:
```
Use the Task tool with subagent_type="your-agent-name"
```
2. **Verify behavior**:
- Does it stay focused on its domain?
- Does it follow the workflow you defined?
- Does it have appropriate tool access?
3. **Iterate**:
- Refine system prompt based on actual usage
- Adjust tool preapprovals as needed
- Update examples in description
## Common Patterns
### Domain Expert Pattern
```markdown
---
name: domain-expert
description: Expert in specific technology or domain
model: inherit
color: blue
tools: Read, Write, Edit, Bash
---
You are an expert in [specific domain].
## Your Expertise
[List specific capabilities]
## Workflow
[Define standard processes]
## Best Practices
[Domain-specific guidelines]
```
### Workflow Automation Pattern
```markdown
---
name: workflow-automator
description: Automates specific multi-step workflows
model: inherit
color: green
tools: Read, Write, Edit, Bash, Grep, Glob
---
You automate [specific workflow].
## Workflow Steps
1. [Step 1]
2. [Step 2]
3. [Step 3]
## Tool Usage
[How to use preapproved tools]
## Success Criteria
[What constitutes successful completion]
```
## Integration with Plugins
When creating subagents as part of plugins:
1. Place in `agents/` subdirectory of plugin
2. Register in `.claude-plugin/marketplace.json`:
```json
{
"agents": {
"agent-name": "./agents/agent-name.md"
}
}
```
3. Document in plugin README.md
4. Consider whether a **skill** might be more appropriate (skills auto-activate based on context)
## Subagents vs Skills vs Commands
**Use Subagents when:**
- You need context isolation
- Workflow is delegatable and self-contained
- You want explicit invocation control
- Agent requires specialized model or tools
**Use Skills when:**
- You want automatic activation based on context
- Guidance should always be available
- Users shouldn't need to remember to invoke it
- Example: Code formatting rules, design patterns
**Use Commands when:**
- Workflow is simple and linear
- You want a quick shortcut
- No complex decision-making needed
- Example: Run tests, format code
## Example: Complete Subagent
```markdown
---
name: api-designer
description: Expert API designer specializing in RESTful and GraphQL APIs. Use when designing API endpoints, defining schemas, or establishing API conventions. Examples: <example>user: "Help me design a REST API for user management" assistant: "Let me use the api-designer agent to create a well-structured API" <commentary>API design requires expertise in REST principles and best practices.</commentary></example>
model: inherit
color: cyan
tools: Read, Write, Edit
---
You are an expert API designer with deep knowledge of REST, GraphQL, OpenAPI, and API best practices.
## Your Expertise
You specialize in:
- RESTful API design following Richardson Maturity Model
- GraphQL schema design and query optimization
- OpenAPI/Swagger specification authoring
- API versioning strategies
- Authentication and authorization patterns (OAuth 2.0, JWT, API keys)
- Rate limiting and pagination patterns
- Error response design
- API documentation
## Workflow
When designing APIs:
1. **Understand Requirements**
- Identify resources and relationships
- Determine access patterns
- Consider scalability needs
2. **Choose Architecture**
- REST for resource-oriented APIs
- GraphQL for flexible data fetching
- Consider hybrid approaches
3. **Design Endpoints/Schema**
- Follow naming conventions
- Use appropriate HTTP methods
- Design consistent response formats
- Handle errors gracefully
4. **Document**
- Create OpenAPI specification (REST)
- Generate schema documentation (GraphQL)
- Provide usage examples
- Document authentication
## Best Practices
### REST APIs
- Use nouns for resources, not verbs
- Leverage HTTP methods (GET, POST, PUT, PATCH, DELETE)
- Version using URL path (`/v1/users`) or headers
- Return appropriate status codes
- Use HATEOAS for discoverability (Level 3 maturity)
### GraphQL APIs
- Design schema-first
- Use meaningful type names
- Implement proper error handling
- Optimize for N+1 query problem
- Provide pagination using cursor-based approach
### Common Patterns
- Use UUIDs for public IDs
- Implement request/response logging
- Support filtering, sorting, pagination
- Include rate limit headers
- Use JSON:API or HAL for hypermedia
## Reference Documentation
- REST: https://restfulapi.net/
- GraphQL: https://graphql.org/learn/
- OpenAPI: https://swagger.io/specification/
- HTTP Status Codes: https://httpstatuses.com/
## Success Criteria
Your API design is successful when:
- It follows industry standards and conventions
- Resources and endpoints are intuitive
- Error handling is comprehensive and clear
- Documentation enables easy integration
- Design scales with usage growth
```