anthropics/claude-code
GitHub将代码和提示词从 Sonnet 4.0/4.5 或 Opus 4.1 迁移至 Opus 4.5。更新模型标识、移除不支持的 Beta 头并添加 effort 参数,根据反馈调整因行为差异导致的工具过度触发问题。
安装全部 Skills
npx skills add anthropics/claude-code --all -g -y
更多选项
预览集合内 Skills
npx skills add anthropics/claude-code --list
集合内 Skills (10)
plugins/claude-opus-4-5-migration/skills/claude-opus-4-5-migration/SKILL.md
npx skills add anthropics/claude-code --skill claude-opus-4-5-migration -g -y
SKILL.md
Frontmatter
{
"name": "claude-opus-4-5-migration",
"description": "Migrate prompts and code from Claude Sonnet 4.0, Sonnet 4.5, or Opus 4.1 to Opus 4.5. Use when the user wants to update their codebase, prompts, or API calls to use Opus 4.5. Handles model string updates and prompt adjustments for known Opus 4.5 behavioral differences. Does NOT migrate Haiku 4.5."
}
Opus 4.5 Migration Guide
One-shot migration from Sonnet 4.0, Sonnet 4.5, or Opus 4.1 to Opus 4.5.
Migration Workflow
- Search codebase for model strings and API calls
- Update model strings to Opus 4.5 (see platform-specific strings below)
- Remove unsupported beta headers
- Add effort parameter set to
"high"(seereferences/effort.md) - Summarize all changes made
- Tell the user: "If you encounter any issues with Opus 4.5, let me know and I can help adjust your prompts."
Model String Updates
Identify which platform the codebase uses, then replace model strings accordingly.
Unsupported Beta Headers
Remove the context-1m-2025-08-07 beta header if present—it is not yet supported with Opus 4.5. Leave a comment noting this:
# Note: 1M context beta (context-1m-2025-08-07) not yet supported with Opus 4.5
Target Model Strings (Opus 4.5)
| Platform | Opus 4.5 Model String |
|---|---|
| Anthropic API (1P) | claude-opus-4-5-20251101 |
| AWS Bedrock | anthropic.claude-opus-4-5-20251101-v1:0 |
| Google Vertex AI | claude-opus-4-5@20251101 |
| Azure AI Foundry | claude-opus-4-5-20251101 |
Source Model Strings to Replace
| Source Model | Anthropic API (1P) | AWS Bedrock | Google Vertex AI |
|---|---|---|---|
| Sonnet 4.0 | claude-sonnet-4-20250514 |
anthropic.claude-sonnet-4-20250514-v1:0 |
claude-sonnet-4@20250514 |
| Sonnet 4.5 | claude-sonnet-4-5-20250929 |
anthropic.claude-sonnet-4-5-20250929-v1:0 |
claude-sonnet-4-5@20250929 |
| Opus 4.1 | claude-opus-4-1-20250422 |
anthropic.claude-opus-4-1-20250422-v1:0 |
claude-opus-4-1@20250422 |
Do NOT migrate: Any Haiku models (e.g., claude-haiku-4-5-20251001).
Prompt Adjustments
Opus 4.5 has known behavioral differences from previous models. Only apply these fixes if the user explicitly requests them or reports a specific issue. By default, just update model strings.
Integration guidelines: When adding snippets, don't just append them to prompts. Integrate them thoughtfully:
- Use XML tags (e.g.,
<code_guidelines>,<tool_usage>) to organize additions - Match the style and structure of the existing prompt
- Place snippets in logical locations (e.g., coding guidelines near other coding instructions)
- If the prompt already uses XML tags, add new content within appropriate existing tags or create consistent new ones
1. Tool Overtriggering
Opus 4.5 is more responsive to system prompts. Aggressive language that prevented undertriggering on previous models may now cause overtriggering.
Apply if: User reports tools being called too frequently or unnecessarily.
Find and soften:
CRITICAL:→ remove or softenYou MUST...→You should...ALWAYS do X→Do XNEVER skip...→Don't skip...REQUIRED→ remove or soften
Only apply to tool-triggering instructions. Leave other uses of emphasis alone.
2. Over-Engineering Prevention
Opus 4.5 tends to create extra files, add unnecessary abstractions, or build unrequested flexibility.
Apply if: User reports unwanted files, excessive abstraction, or unrequested features. Add the snippet from references/prompt-snippets.md.
3. Code Exploration
Opus 4.5 can be overly conservative about exploring code, proposing solutions without reading files.
Apply if: User reports the model proposing fixes without inspecting relevant code. Add the snippet from references/prompt-snippets.md.
4. Frontend Design
Apply if: User requests improved frontend design quality or reports generic-looking outputs.
Add the frontend aesthetics snippet from references/prompt-snippets.md.
5. Thinking Sensitivity
When extended thinking is not enabled (the default), Opus 4.5 is particularly sensitive to the word "think" and its variants. Extended thinking is enabled only if the API request contains a thinking parameter.
Apply if: User reports issues related to "thinking" while extended thinking is not enabled (no thinking parameter in request).
Replace "think" with alternatives like "consider," "believe," or "evaluate."
Reference
See references/prompt-snippets.md for the full text of each snippet to add.
See references/effort.md for configuring the effort parameter (only if user requests it).
plugins/frontend-design/skills/frontend-design/SKILL.md
npx skills add anthropics/claude-code --skill frontend-design -g -y
SKILL.md
Frontmatter
{
"name": "frontend-design",
"license": "Complete terms in LICENSE.txt",
"description": "Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults."
}
Frontend Design
Approach this as the design lead at a small studio known for giving every client a visual identity that could not be mistaken for anyone else's. This client has already rejected proposals that felt templated, and is paying for a distinctive point of view: make deliberate, opinionated choices about palette, typography, and layout that are specific to this brief, and take one real aesthetic risk you can justify.
Ground it in the subject
If the brief does not pin down what the product or subject is, pin it yourself before designing: name one concrete subject, its audience, and the page's single job, and state your choice. If there's any information in your memory about the human's preferences, context about what they're building, or designs you've made before – use that as a hint. The subject's own world, its materials, instruments, artifacts, and vernacular, is where distinctive choices come from. Build with the brief's real content and subject matter throughout.
Design principles
For web designs, the hero is a thesis. Open with the most characteristic thing in the subject's world, in whatever form makes sense for it: a headline, an image, an animation, a live demo, an interactive moment. Be deliberate with your choice: a big number with a small label, supporting stats, and a gradient accent is the template answer, only use if that's truly the best option.
Typography carries the personality of the page. Pair the display and body faces deliberately, not the same families you would reach for on any other project, and set a clear type scale with intentional weights, widths, and spacing. Make the type treatment itself a memorable part of the design, not a neutral delivery vehicle for the content.
Structure is information. Structural devices, numbering, eyebrows, dividers, labels, should encode something true about the content, not decorate it. Many generic designs use numbered markers (01 / 02 / 03), but that's only appropriate if the content actually is a sequence - like a real process or a typed timeline where order carries information the reader needs. Question if choices like numbered markers actually make sense before incorporating them.
Leverage motion deliberately. Think about where and if animation can serve the subject: a page-load sequence, a scroll-triggered reveal, hover micro-interactions, ambient atmosphere. An orchestrated moment usually lands harder than scattered effects; choose what the direction calls for. However, sometimes less is more, and extra animation contributes to the feeling that the design is AI-generated.
Match complexity to the vision. Maximalist directions need elaborate execution; minimal directions need precision in spacing, type, and detail. Elegance is executing the chosen vision well.
Consider written content carefully. Often a design brief may not contain real content, and it's up to you to come up with copy. Copy can make a design feel as templated as the design itself. See the below section on writing for more guidance.
Process: brainstorm, explore, plan, critique, build, critique again
For calibration: AI-generated design right now clusters around three looks: (1) a warm cream background (near #F4F1EA) with a high-contrast serif display and a terracotta accent; (2) a near-black background with a single bright acid-green or vermilion accent; (3) a broadsheet-style layout with hairline rules, zero border-radius, and dense newspaper-like columns. All three are legitimate for some briefs, but they are defaults rather than choices, and they appear regardless of subject. Where the brief pins down a visual direction, follow it exactly — the brief's own words always win, including when it asks for one of these looks. Where it leaves an axis free, don't spend that freedom on one of these defaults. Just like a human designer who's hired, there's often a careful balance between doing what you're good at and taking each project as a chance to experiment and learn.
Work in two passes. First, brainstorm a short design plan based on the human's design brief: create a compact token system with color, type, layout, and signature. Color: describe the palette as 4–6 named hex values. Type: the typefaces for 2+ roles (a characterful display face that's used with restraint, a complementary body face, and a utility face for captions or data if needed). Layout: a layout concept, using one-sentence prose descriptions and ASCII wireframes to ideate and compare. Signature: the single unique element this page will be remembered by that embodies the brief in an appropriate way.
Then review that plan against the brief before building: if any part of it reads like the generic default you would produce for any similar page (work through a similar prompt to see if you arrive somewhere similar) rather than a choice made for this specific brief — revise that part, say what you changed and why. Only after you've confirmed the relative uniqueness of your design plan should you start to write the code, following the revised plan exactly and deriving every color and type decision from it.
When writing the code, be careful of structuring your CSS selector specificities. It's easy to generate CSS classes that cancel each other out (especially with a type-based selector like .section and a element-based selector like .cta). This can happen often with paddings/margins between sections.
Try to do a lot of this planning and iteration in your thinking, and only show ideas to the user when you have higher confidence it'll delight them.
Restraint and self-critique
Spend your boldness in one place. Let the signature element be the one memorable thing, keep everything around it quiet and disciplined, and cut any decoration that does not serve the brief. Not taking a risk can be a risk itself! Build to a quality floor without announcing it: responsive down to mobile, visible keyboard focus, reduced motion respected. Critique your own work as you build, taking screenshots if your environment supports it – a picture is worth 1000 tokens. Consider Chanel's advice: before leaving the house, take a look in the mirror and remove one accessory. Human creators have memory and always try to do something new, so if you have a space to quickly jot down notes about what you've tried, it can help you in future passes.
More on writing in design
Words appear in a design for one reason: to make it easier to understand, and therefore easier to use. They are design material, not decoration. Bring the same intentionality to copy that you would bring to spacing and color. Before writing anything, ask what the design needs to say, and how it can best be said to help the person navigate the experience.
Write from the end user's side of the screen. Name things by what people control and recognize, never by how the system is built. A person manages notifications, not webhook config. Describe what something does in plain terms rather than selling it. Being specific is always better than being clever.
Use active voice as default. A control should say exactly what happens when it's used: "Save changes," not "Submit." An action keeps the same name through the whole flow, so the button that says "Publish" produces a toast that says "Published." The vocabulary of an interface is the signposting for someone navigating the product. Cohesion and consistency are how people learn their way around.
Treat failure and emptiness as moments for direction, not mood. Explain what went wrong and how to fix it, in the interface's voice rather than a person's. Errors don't apologize, and they are never vague about what happened. An empty screen is an invitation to act.
Keep the register conversational and tuned: plain verbs, sentence case, no filler, with tone matched to the brand and the audience. Let each element do exactly one job. A label labels, an example demonstrates, and nothing quietly does double duty.
plugins/hookify/skills/writing-rules/SKILL.md
npx skills add anthropics/claude-code --skill Writing Hookify Rules -g -y
SKILL.md
Frontmatter
{
"name": "Writing Hookify Rules",
"version": "0.1.0",
"description": "This skill should be used when the user asks to \"create a hookify rule\", \"write a hook rule\", \"configure hookify\", \"add a hookify rule\", or needs guidance on hookify rule syntax and patterns."
}
Writing Hookify Rules
Overview
Hookify rules are markdown files with YAML frontmatter that define patterns to watch for and messages to show when those patterns match. Rules are stored in .claude/hookify.{rule-name}.local.md files.
Rule File Format
Basic Structure
---
name: rule-identifier
enabled: true
event: bash|file|stop|prompt|all
pattern: regex-pattern-here
---
Message to show Claude when this rule triggers.
Can include markdown formatting, warnings, suggestions, etc.
Frontmatter Fields
name (required): Unique identifier for the rule
- Use kebab-case:
warn-dangerous-rm,block-console-log - Be descriptive and action-oriented
- Start with verb: warn, prevent, block, require, check
enabled (required): Boolean to activate/deactivate
true: Rule is activefalse: Rule is disabled (won't trigger)- Can toggle without deleting rule
event (required): Which hook event to trigger on
bash: Bash tool commandsfile: Edit, Write, MultiEdit toolsstop: When agent wants to stopprompt: When user submits a promptall: All events
action (optional): What to do when rule matches
warn: Show message but allow operation (default)block: Prevent operation (PreToolUse) or stop session (Stop events)- If omitted, defaults to
warn
pattern (simple format): Regex pattern to match
- Used for simple single-condition rules
- Matches against command (bash) or new_text (file)
- Python regex syntax
Example:
event: bash
pattern: rm\s+-rf
Advanced Format (Multiple Conditions)
For complex rules with multiple conditions:
---
name: warn-env-file-edits
enabled: true
event: file
conditions:
- field: file_path
operator: regex_match
pattern: \.env$
- field: new_text
operator: contains
pattern: API_KEY
---
You're adding an API key to a .env file. Ensure this file is in .gitignore!
Condition fields:
field: Which field to check- For bash:
command - For file:
file_path,new_text,old_text,content
- For bash:
operator: How to matchregex_match: Regex pattern matchingcontains: Substring checkequals: Exact matchnot_contains: Substring must NOT be presentstarts_with: Prefix checkends_with: Suffix check
pattern: Pattern or string to match
All conditions must match for rule to trigger.
Message Body
The markdown content after frontmatter is shown to Claude when the rule triggers.
Good messages:
- Explain what was detected
- Explain why it's problematic
- Suggest alternatives or best practices
- Use formatting for clarity (bold, lists, etc.)
Example:
⚠️ **Console.log detected!**
You're adding console.log to production code.
**Why this matters:**
- Debug logs shouldn't ship to production
- Console.log can expose sensitive data
- Impacts browser performance
**Alternatives:**
- Use a proper logging library
- Remove before committing
- Use conditional debug builds
Event Type Guide
bash Events
Match Bash command patterns:
---
event: bash
pattern: sudo\s+|rm\s+-rf|chmod\s+777
---
Dangerous command detected!
Common patterns:
- Dangerous commands:
rm\s+-rf,dd\s+if=,mkfs - Privilege escalation:
sudo\s+,su\s+ - Permission issues:
chmod\s+777,chown\s+root
file Events
Match Edit/Write/MultiEdit operations:
---
event: file
pattern: console\.log\(|eval\(|innerHTML\s*=
---
Potentially problematic code pattern detected!
Match on different fields:
---
event: file
conditions:
- field: file_path
operator: regex_match
pattern: \.tsx?$
- field: new_text
operator: regex_match
pattern: console\.log\(
---
Console.log in TypeScript file!
Common patterns:
- Debug code:
console\.log\(,debugger,print\( - Security risks:
eval\(,innerHTML\s*=,dangerouslySetInnerHTML - Sensitive files:
\.env$,credentials,\.pem$ - Generated files:
node_modules/,dist/,build/
stop Events
Match when agent wants to stop (completion checks):
---
event: stop
pattern: .*
---
Before stopping, verify:
- [ ] Tests were run
- [ ] Build succeeded
- [ ] Documentation updated
Use for:
- Reminders about required steps
- Completion checklists
- Process enforcement
prompt Events
Match user prompt content (advanced):
---
event: prompt
conditions:
- field: user_prompt
operator: contains
pattern: deploy to production
---
Production deployment checklist:
- [ ] Tests passing?
- [ ] Reviewed by team?
- [ ] Monitoring ready?
Pattern Writing Tips
Regex Basics
Literal characters: Most characters match themselves
rmmatches "rm"console.logmatches "console.log"
Special characters need escaping:
.(any char) →\.(literal dot)()→\(\)(literal parens)[]→\[\](literal brackets)
Common metacharacters:
\s- whitespace (space, tab, newline)\d- digit (0-9)\w- word character (a-z, A-Z, 0-9, _).- any character+- one or more*- zero or more?- zero or one|- OR
Examples:
rm\s+-rf Matches: rm -rf, rm -rf
console\.log\( Matches: console.log(
(eval|exec)\( Matches: eval( or exec(
chmod\s+777 Matches: chmod 777, chmod 777
API_KEY\s*= Matches: API_KEY=, API_KEY =
Testing Patterns
Test regex patterns before using:
python3 -c "import re; print(re.search(r'your_pattern', 'test text'))"
Or use online regex testers (regex101.com with Python flavor).
Common Pitfalls
Too broad:
pattern: log # Matches "log", "login", "dialog", "catalog"
Better: console\.log\(|logger\.
Too specific:
pattern: rm -rf /tmp # Only matches exact path
Better: rm\s+-rf
Escaping issues:
- YAML quoted strings:
"pattern"requires double backslashes\\s - YAML unquoted:
pattern: \sworks as-is - Recommendation: Use unquoted patterns in YAML
File Organization
Location: All rules in .claude/ directory
Naming: .claude/hookify.{descriptive-name}.local.md
Gitignore: Add .claude/*.local.md to .gitignore
Good names:
hookify.dangerous-rm.local.mdhookify.console-log.local.mdhookify.require-tests.local.mdhookify.sensitive-files.local.md
Bad names:
hookify.rule1.local.md(not descriptive)hookify.md(missing .local)danger.local.md(missing hookify prefix)
Workflow
Creating a Rule
- Identify unwanted behavior
- Determine which tool is involved (Bash, Edit, etc.)
- Choose event type (bash, file, stop, etc.)
- Write regex pattern
- Create
.claude/hookify.{name}.local.mdfile in project root - Test immediately - rules are read dynamically on next tool use
Refining a Rule
- Edit the
.local.mdfile - Adjust pattern or message
- Test immediately - changes take effect on next tool use
Disabling a Rule
Temporary: Set enabled: false in frontmatter
Permanent: Delete the .local.md file
Examples
See ${CLAUDE_PLUGIN_ROOT}/examples/ for complete examples:
dangerous-rm.local.md- Block dangerous rm commandsconsole-log-warning.local.md- Warn about console.logsensitive-files-warning.local.md- Warn about editing .env files
Quick Reference
Minimum viable rule:
---
name: my-rule
enabled: true
event: bash
pattern: dangerous_command
---
Warning message here
Rule with conditions:
---
name: my-rule
enabled: true
event: file
conditions:
- field: file_path
operator: regex_match
pattern: \.ts$
- field: new_text
operator: contains
pattern: any
---
Warning message
Event types:
bash- Bash commandsfile- File editsstop- Completion checksprompt- User inputall- All events
Field options:
- Bash:
command - File:
file_path,new_text,old_text,content - Prompt:
user_prompt
Operators:
regex_match,contains,equals,not_contains,starts_with,ends_with
plugins/plugin-dev/skills/agent-development/SKILL.md
npx skills add anthropics/claude-code --skill Agent Development -g -y
SKILL.md
Frontmatter
{
"name": "Agent Development",
"version": "0.1.0",
"description": "This skill should be used when the user asks to \"create an agent\", \"add an agent\", \"write a subagent\", \"agent frontmatter\", \"when to use description\", \"agent examples\", \"agent tools\", \"agent colors\", \"autonomous agent\", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins."
}
Agent Development for Claude Code Plugins
Overview
Agents are autonomous subprocesses that handle complex, multi-step tasks independently. Understanding agent structure, triggering conditions, and system prompt design enables creating powerful autonomous capabilities.
Key concepts:
- Agents are FOR autonomous work, commands are FOR user-initiated actions
- Markdown file format with YAML frontmatter
- Triggering via description field with examples
- System prompt defines agent behavior
- Model and color customization
Agent File Structure
Complete Format
---
name: agent-identifier
description: Use this agent when [triggering conditions]. Examples:
<example>
Context: [Situation description]
user: "[User request]"
assistant: "[How assistant should respond and use this agent]"
<commentary>
[Why this agent should be triggered]
</commentary>
</example>
<example>
[Additional example...]
</example>
model: inherit
color: blue
tools: ["Read", "Write", "Grep"]
---
You are [agent role description]...
**Your Core Responsibilities:**
1. [Responsibility 1]
2. [Responsibility 2]
**Analysis Process:**
[Step-by-step workflow]
**Output Format:**
[What to return]
Frontmatter Fields
name (required)
Agent identifier used for namespacing and invocation.
Format: lowercase, numbers, hyphens only Length: 3-50 characters Pattern: Must start and end with alphanumeric
Good examples:
code-reviewertest-generatorapi-docs-writersecurity-analyzer
Bad examples:
helper(too generic)-agent-(starts/ends with hyphen)my_agent(underscores not allowed)ag(too short, < 3 chars)
description (required)
Defines when Claude should trigger this agent. This is the most critical field.
Must include:
- Triggering conditions ("Use this agent when...")
- Multiple
<example>blocks showing usage - Context, user request, and assistant response in each example
<commentary>explaining why agent triggers
Format:
Use this agent when [conditions]. Examples:
<example>
Context: [Scenario description]
user: "[What user says]"
assistant: "[How Claude should respond]"
<commentary>
[Why this agent is appropriate]
</commentary>
</example>
[More examples...]
Best practices:
- Include 2-4 concrete examples
- Show proactive and reactive triggering
- Cover different phrasings of same intent
- Explain reasoning in commentary
- Be specific about when NOT to use the agent
model (required)
Which model the agent should use.
Options:
inherit- Use same model as parent (recommended)sonnet- Claude Sonnet (balanced)opus- Claude Opus (most capable, expensive)haiku- Claude Haiku (fast, cheap)
Recommendation: Use inherit unless agent needs specific model capabilities.
color (required)
Visual identifier for agent in UI.
Options: blue, cyan, green, yellow, magenta, red
Guidelines:
- Choose distinct colors for different agents in same plugin
- Use consistent colors for similar agent types
- Blue/cyan: Analysis, review
- Green: Success-oriented tasks
- Yellow: Caution, validation
- Red: Critical, security
- Magenta: Creative, generation
tools (optional)
Restrict agent to specific tools.
Format: Array of tool names
tools: ["Read", "Write", "Grep", "Bash"]
Default: If omitted, agent has access to all tools
Best practice: Limit tools to minimum needed (principle of least privilege)
Common tool sets:
- Read-only analysis:
["Read", "Grep", "Glob"] - Code generation:
["Read", "Write", "Grep"] - Testing:
["Read", "Bash", "Grep"] - Full access: Omit field or use
["*"]
System Prompt Design
The markdown body becomes the agent's system prompt. Write in second person, addressing the agent directly.
Structure
Standard template:
You are [role] specializing in [domain].
**Your Core Responsibilities:**
1. [Primary responsibility]
2. [Secondary responsibility]
3. [Additional responsibilities...]
**Analysis Process:**
1. [Step one]
2. [Step two]
3. [Step three]
[...]
**Quality Standards:**
- [Standard 1]
- [Standard 2]
**Output Format:**
Provide results in this format:
- [What to include]
- [How to structure]
**Edge Cases:**
Handle these situations:
- [Edge case 1]: [How to handle]
- [Edge case 2]: [How to handle]
Best Practices
✅ DO:
- Write in second person ("You are...", "You will...")
- Be specific about responsibilities
- Provide step-by-step process
- Define output format
- Include quality standards
- Address edge cases
- Keep under 10,000 characters
❌ DON'T:
- Write in first person ("I am...", "I will...")
- Be vague or generic
- Omit process steps
- Leave output format undefined
- Skip quality guidance
- Ignore error cases
Creating Agents
Method 1: AI-Assisted Generation
Use this prompt pattern (extracted from Claude Code):
Create an agent configuration based on this request: "[YOUR DESCRIPTION]"
Requirements:
1. Extract core intent and responsibilities
2. Design expert persona for the domain
3. Create comprehensive system prompt with:
- Clear behavioral boundaries
- Specific methodologies
- Edge case handling
- Output format
4. Create identifier (lowercase, hyphens, 3-50 chars)
5. Write description with triggering conditions
6. Include 2-3 <example> blocks showing when to use
Return JSON with:
{
"identifier": "agent-name",
"whenToUse": "Use this agent when... Examples: <example>...</example>",
"systemPrompt": "You are..."
}
Then convert to agent file format with frontmatter.
See examples/agent-creation-prompt.md for complete template.
Method 2: Manual Creation
- Choose agent identifier (3-50 chars, lowercase, hyphens)
- Write description with examples
- Select model (usually
inherit) - Choose color for visual identification
- Define tools (if restricting access)
- Write system prompt with structure above
- Save as
agents/agent-name.md
Validation Rules
Identifier Validation
✅ Valid: code-reviewer, test-gen, api-analyzer-v2
❌ Invalid: ag (too short), -start (starts with hyphen), my_agent (underscore)
Rules:
- 3-50 characters
- Lowercase letters, numbers, hyphens only
- Must start and end with alphanumeric
- No underscores, spaces, or special characters
Description Validation
Length: 10-5,000 characters Must include: Triggering conditions and examples Best: 200-1,000 characters with 2-4 examples
System Prompt Validation
Length: 20-10,000 characters Best: 500-3,000 characters Structure: Clear responsibilities, process, output format
Agent Organization
Plugin Agents Directory
plugin-name/
└── agents/
├── analyzer.md
├── reviewer.md
└── generator.md
All .md files in agents/ are auto-discovered.
Namespacing
Agents are namespaced automatically:
- Single plugin:
agent-name - With subdirectories:
plugin:subdir:agent-name
Testing Agents
Test Triggering
Create test scenarios to verify agent triggers correctly:
- Write agent with specific triggering examples
- Use similar phrasing to examples in test
- Check Claude loads the agent
- Verify agent provides expected functionality
Test System Prompt
Ensure system prompt is complete:
- Give agent typical task
- Check it follows process steps
- Verify output format is correct
- Test edge cases mentioned in prompt
- Confirm quality standards are met
Quick Reference
Minimal Agent
---
name: simple-agent
description: Use this agent when... Examples: <example>...</example>
model: inherit
color: blue
---
You are an agent that [does X].
Process:
1. [Step 1]
2. [Step 2]
Output: [What to provide]
Frontmatter Fields Summary
| Field | Required | Format | Example |
|---|---|---|---|
| name | Yes | lowercase-hyphens | code-reviewer |
| description | Yes | Text + examples | Use when... |
| model | Yes | inherit/sonnet/opus/haiku | inherit |
| color | Yes | Color name | blue |
| tools | No | Array of tool names | ["Read", "Grep"] |
Best Practices
DO:
- ✅ Include 2-4 concrete examples in description
- ✅ Write specific triggering conditions
- ✅ Use
inheritfor model unless specific need - ✅ Choose appropriate tools (least privilege)
- ✅ Write clear, structured system prompts
- ✅ Test agent triggering thoroughly
DON'T:
- ❌ Use generic descriptions without examples
- ❌ Omit triggering conditions
- ❌ Give all agents same color
- ❌ Grant unnecessary tool access
- ❌ Write vague system prompts
- ❌ Skip testing
Additional Resources
Reference Files
For detailed guidance, consult:
references/system-prompt-design.md- Complete system prompt patternsreferences/triggering-examples.md- Example formats and best practicesreferences/agent-creation-system-prompt.md- The exact prompt from Claude Code
Example Files
Working examples in examples/:
agent-creation-prompt.md- AI-assisted agent generation templatecomplete-agent-examples.md- Full agent examples for different use cases
Utility Scripts
Development tools in scripts/:
validate-agent.sh- Validate agent file structuretest-agent-trigger.sh- Test if agent triggers correctly
Implementation Workflow
To create an agent for a plugin:
- Define agent purpose and triggering conditions
- Choose creation method (AI-assisted or manual)
- Create
agents/agent-name.mdfile - Write frontmatter with all required fields
- Write system prompt following best practices
- Include 2-4 triggering examples in description
- Validate with
scripts/validate-agent.sh - Test triggering with real scenarios
- Document agent in plugin README
Focus on clear triggering conditions and comprehensive system prompts for autonomous operation.
plugins/plugin-dev/skills/command-development/SKILL.md
npx skills add anthropics/claude-code --skill Command Development -g -y
SKILL.md
Frontmatter
{
"name": "Command Development",
"version": "0.2.0",
"description": "This skill should be used when the user asks to \"create a slash command\", \"add a command\", \"write a custom command\", \"define command arguments\", \"use command frontmatter\", \"organize commands\", \"create command with file references\", \"interactive command\", \"use AskUserQuestion in command\", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code."
}
Command Development for Claude Code
Overview
Slash commands are frequently-used prompts defined as Markdown files that Claude executes during interactive sessions. Understanding command structure, frontmatter options, and dynamic features enables creating powerful, reusable workflows.
Key concepts:
- Markdown file format for commands
- YAML frontmatter for configuration
- Dynamic arguments and file references
- Bash execution for context
- Command organization and namespacing
Command Basics
What is a Slash Command?
A slash command is a Markdown file containing a prompt that Claude executes when invoked. Commands provide:
- Reusability: Define once, use repeatedly
- Consistency: Standardize common workflows
- Sharing: Distribute across team or projects
- Efficiency: Quick access to complex prompts
Critical: Commands are Instructions FOR Claude
Commands are written for agent consumption, not human consumption.
When a user invokes /command-name, the command content becomes Claude's instructions. Write commands as directives TO Claude about what to do, not as messages TO the user.
Correct approach (instructions for Claude):
Review this code for security vulnerabilities including:
- SQL injection
- XSS attacks
- Authentication issues
Provide specific line numbers and severity ratings.
Incorrect approach (messages to user):
This command will review your code for security issues.
You'll receive a report with vulnerability details.
The first example tells Claude what to do. The second tells the user what will happen but doesn't instruct Claude. Always use the first approach.
Command Locations
Project commands (shared with team):
- Location:
.claude/commands/ - Scope: Available in specific project
- Label: Shown as "(project)" in
/help - Use for: Team workflows, project-specific tasks
Personal commands (available everywhere):
- Location:
~/.claude/commands/ - Scope: Available in all projects
- Label: Shown as "(user)" in
/help - Use for: Personal workflows, cross-project utilities
Plugin commands (bundled with plugins):
- Location:
plugin-name/commands/ - Scope: Available when plugin installed
- Label: Shown as "(plugin-name)" in
/help - Use for: Plugin-specific functionality
File Format
Basic Structure
Commands are Markdown files with .md extension:
.claude/commands/
├── review.md # /review command
├── test.md # /test command
└── deploy.md # /deploy command
Simple command:
Review this code for security vulnerabilities including:
- SQL injection
- XSS attacks
- Authentication bypass
- Insecure data handling
No frontmatter needed for basic commands.
With YAML Frontmatter
Add configuration using YAML frontmatter:
---
description: Review code for security issues
allowed-tools: Read, Grep, Bash(git:*)
model: sonnet
---
Review this code for security vulnerabilities...
YAML Frontmatter Fields
description
Purpose: Brief description shown in /help
Type: String
Default: First line of command prompt
---
description: Review pull request for code quality
---
Best practice: Clear, actionable description (under 60 characters)
allowed-tools
Purpose: Specify which tools command can use Type: String or Array Default: Inherits from conversation
---
allowed-tools: Read, Write, Edit, Bash(git:*)
---
Patterns:
Read, Write, Edit- Specific toolsBash(git:*)- Bash with git commands only*- All tools (rarely needed)
Use when: Command requires specific tool access
model
Purpose: Specify model for command execution Type: String (sonnet, opus, haiku) Default: Inherits from conversation
---
model: haiku
---
Use cases:
haiku- Fast, simple commandssonnet- Standard workflowsopus- Complex analysis
argument-hint
Purpose: Document expected arguments for autocomplete Type: String Default: None
---
argument-hint: [pr-number] [priority] [assignee]
---
Benefits:
- Helps users understand command arguments
- Improves command discovery
- Documents command interface
disable-model-invocation
Purpose: Prevent SlashCommand tool from programmatically calling command Type: Boolean Default: false
---
disable-model-invocation: true
---
Use when: Command should only be manually invoked
Dynamic Arguments
Using $ARGUMENTS
Capture all arguments as single string:
---
description: Fix issue by number
argument-hint: [issue-number]
---
Fix issue #$ARGUMENTS following our coding standards and best practices.
Usage:
> /fix-issue 123
> /fix-issue 456
Expands to:
Fix issue #123 following our coding standards...
Fix issue #456 following our coding standards...
Using Positional Arguments
Capture individual arguments with $1, $2, $3, etc.:
---
description: Review PR with priority and assignee
argument-hint: [pr-number] [priority] [assignee]
---
Review pull request #$1 with priority level $2.
After review, assign to $3 for follow-up.
Usage:
> /review-pr 123 high alice
Expands to:
Review pull request #123 with priority level high.
After review, assign to alice for follow-up.
Combining Arguments
Mix positional and remaining arguments:
Deploy $1 to $2 environment with options: $3
Usage:
> /deploy api staging --force --skip-tests
Expands to:
Deploy api to staging environment with options: --force --skip-tests
File References
Using @ Syntax
Include file contents in command:
---
description: Review specific file
argument-hint: [file-path]
---
Review @$1 for:
- Code quality
- Best practices
- Potential bugs
Usage:
> /review-file src/api/users.ts
Effect: Claude reads src/api/users.ts before processing command
Multiple File References
Reference multiple files:
Compare @src/old-version.js with @src/new-version.js
Identify:
- Breaking changes
- New features
- Bug fixes
Static File References
Reference known files without arguments:
Review @package.json and @tsconfig.json for consistency
Ensure:
- TypeScript version matches
- Dependencies are aligned
- Build configuration is correct
Bash Execution in Commands
Commands can execute bash commands inline to dynamically gather context before Claude processes the command. This is useful for including repository state, environment information, or project-specific context.
When to use:
- Include dynamic context (git status, environment vars, etc.)
- Gather project/repository state
- Build context-aware workflows
Implementation details:
For complete syntax, examples, and best practices, see references/plugin-features-reference.md section on bash execution. The reference includes the exact syntax and multiple working examples to avoid execution issues
Command Organization
Flat Structure
Simple organization for small command sets:
.claude/commands/
├── build.md
├── test.md
├── deploy.md
├── review.md
└── docs.md
Use when: 5-15 commands, no clear categories
Namespaced Structure
Organize commands in subdirectories:
.claude/commands/
├── ci/
│ ├── build.md # /build (project:ci)
│ ├── test.md # /test (project:ci)
│ └── lint.md # /lint (project:ci)
├── git/
│ ├── commit.md # /commit (project:git)
│ └── pr.md # /pr (project:git)
└── docs/
├── generate.md # /generate (project:docs)
└── publish.md # /publish (project:docs)
Benefits:
- Logical grouping by category
- Namespace shown in
/help - Easier to find related commands
Use when: 15+ commands, clear categories
Best Practices
Command Design
- Single responsibility: One command, one task
- Clear descriptions: Self-explanatory in
/help - Explicit dependencies: Use
allowed-toolswhen needed - Document arguments: Always provide
argument-hint - Consistent naming: Use verb-noun pattern (review-pr, fix-issue)
Argument Handling
- Validate arguments: Check for required arguments in prompt
- Provide defaults: Suggest defaults when arguments missing
- Document format: Explain expected argument format
- Handle edge cases: Consider missing or invalid arguments
---
argument-hint: [pr-number]
---
$IF($1,
Review PR #$1,
Please provide a PR number. Usage: /review-pr [number]
)
File References
- Explicit paths: Use clear file paths
- Check existence: Handle missing files gracefully
- Relative paths: Use project-relative paths
- Glob support: Consider using Glob tool for patterns
Bash Commands
- Limit scope: Use
Bash(git:*)notBash(*) - Safe commands: Avoid destructive operations
- Handle errors: Consider command failures
- Keep fast: Long-running commands slow invocation
Documentation
- Add comments: Explain complex logic
- Provide examples: Show usage in comments
- List requirements: Document dependencies
- Version commands: Note breaking changes
---
description: Deploy application to environment
argument-hint: [environment] [version]
---
<!--
Usage: /deploy [staging|production] [version]
Requires: AWS credentials configured
Example: /deploy staging v1.2.3
-->
Deploy application to $1 environment using version $2...
Common Patterns
Review Pattern
---
description: Review code changes
allowed-tools: Read, Bash(git:*)
---
Files changed: !`git diff --name-only`
Review each file for:
1. Code quality and style
2. Potential bugs or issues
3. Test coverage
4. Documentation needs
Provide specific feedback for each file.
Testing Pattern
---
description: Run tests for specific file
argument-hint: [test-file]
allowed-tools: Bash(npm:*)
---
Run tests: !`npm test $1`
Analyze results and suggest fixes for failures.
Documentation Pattern
---
description: Generate documentation for file
argument-hint: [source-file]
---
Generate comprehensive documentation for @$1 including:
- Function/class descriptions
- Parameter documentation
- Return value descriptions
- Usage examples
- Edge cases and errors
Workflow Pattern
---
description: Complete PR workflow
argument-hint: [pr-number]
allowed-tools: Bash(gh:*), Read
---
PR #$1 Workflow:
1. Fetch PR: !`gh pr view $1`
2. Review changes
3. Run checks
4. Approve or request changes
Troubleshooting
Command not appearing:
- Check file is in correct directory
- Verify
.mdextension present - Ensure valid Markdown format
- Restart Claude Code
Arguments not working:
- Verify
$1,$2syntax correct - Check
argument-hintmatches usage - Ensure no extra spaces
Bash execution failing:
- Check
allowed-toolsincludes Bash - Verify command syntax in backticks
- Test command in terminal first
- Check for required permissions
File references not working:
- Verify
@syntax correct - Check file path is valid
- Ensure Read tool allowed
- Use absolute or project-relative paths
Plugin-Specific Features
CLAUDE_PLUGIN_ROOT Variable
Plugin commands have access to ${CLAUDE_PLUGIN_ROOT}, an environment variable that resolves to the plugin's absolute path.
Purpose:
- Reference plugin files portably
- Execute plugin scripts
- Load plugin configuration
- Access plugin templates
Basic usage:
---
description: Analyze using plugin script
allowed-tools: Bash(node:*)
---
Run analysis: !`node ${CLAUDE_PLUGIN_ROOT}/scripts/analyze.js $1`
Review results and report findings.
Common patterns:
# Execute plugin script
!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/script.sh`
# Load plugin configuration
@${CLAUDE_PLUGIN_ROOT}/config/settings.json
# Use plugin template
@${CLAUDE_PLUGIN_ROOT}/templates/report.md
# Access plugin resources
@${CLAUDE_PLUGIN_ROOT}/docs/reference.md
Why use it:
- Works across all installations
- Portable between systems
- No hardcoded paths needed
- Essential for multi-file plugins
Plugin Command Organization
Plugin commands discovered automatically from commands/ directory:
plugin-name/
├── commands/
│ ├── foo.md # /foo (plugin:plugin-name)
│ ├── bar.md # /bar (plugin:plugin-name)
│ └── utils/
│ └── helper.md # /helper (plugin:plugin-name:utils)
└── plugin.json
Namespace benefits:
- Logical command grouping
- Shown in
/helpoutput - Avoid name conflicts
- Organize related commands
Naming conventions:
- Use descriptive action names
- Avoid generic names (test, run)
- Consider plugin-specific prefix
- Use hyphens for multi-word names
Plugin Command Patterns
Configuration-based pattern:
---
description: Deploy using plugin configuration
argument-hint: [environment]
allowed-tools: Read, Bash(*)
---
Load configuration: @${CLAUDE_PLUGIN_ROOT}/config/$1-deploy.json
Deploy to $1 using configuration settings.
Monitor deployment and report status.
Template-based pattern:
---
description: Generate docs from template
argument-hint: [component]
---
Template: @${CLAUDE_PLUGIN_ROOT}/templates/docs.md
Generate documentation for $1 following template structure.
Multi-script pattern:
---
description: Complete build workflow
allowed-tools: Bash(*)
---
Build: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh`
Test: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/test.sh`
Package: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/package.sh`
Review outputs and report workflow status.
See references/plugin-features-reference.md for detailed patterns.
Integration with Plugin Components
Commands can integrate with other plugin components for powerful workflows.
Agent Integration
Launch plugin agents for complex tasks:
---
description: Deep code review
argument-hint: [file-path]
---
Initiate comprehensive review of @$1 using the code-reviewer agent.
The agent will analyze:
- Code structure
- Security issues
- Performance
- Best practices
Agent uses plugin resources:
- ${CLAUDE_PLUGIN_ROOT}/config/rules.json
- ${CLAUDE_PLUGIN_ROOT}/checklists/review.md
Key points:
- Agent must exist in
plugin/agents/directory - Claude uses Task tool to launch agent
- Document agent capabilities
- Reference plugin resources agent uses
Skill Integration
Leverage plugin skills for specialized knowledge:
---
description: Document API with standards
argument-hint: [api-file]
---
Document API in @$1 following plugin standards.
Use the api-docs-standards skill to ensure:
- Complete endpoint documentation
- Consistent formatting
- Example quality
- Error documentation
Generate production-ready API docs.
Key points:
- Skill must exist in
plugin/skills/directory - Mention skill name to trigger invocation
- Document skill purpose
- Explain what skill provides
Hook Coordination
Design commands that work with plugin hooks:
- Commands can prepare state for hooks to process
- Hooks execute automatically on tool events
- Commands should document expected hook behavior
- Guide Claude on interpreting hook output
See references/plugin-features-reference.md for examples of commands that coordinate with hooks
Multi-Component Workflows
Combine agents, skills, and scripts:
---
description: Comprehensive review workflow
argument-hint: [file]
allowed-tools: Bash(node:*), Read
---
Target: @$1
Phase 1 - Static Analysis:
!`node ${CLAUDE_PLUGIN_ROOT}/scripts/lint.js $1`
Phase 2 - Deep Review:
Launch code-reviewer agent for detailed analysis.
Phase 3 - Standards Check:
Use coding-standards skill for validation.
Phase 4 - Report:
Template: @${CLAUDE_PLUGIN_ROOT}/templates/review.md
Compile findings into report following template.
When to use:
- Complex multi-step workflows
- Leverage multiple plugin capabilities
- Require specialized analysis
- Need structured outputs
Validation Patterns
Commands should validate inputs and resources before processing.
Argument Validation
---
description: Deploy with validation
argument-hint: [environment]
---
Validate environment: !`echo "$1" | grep -E "^(dev|staging|prod)$" || echo "INVALID"`
If $1 is valid environment:
Deploy to $1
Otherwise:
Explain valid environments: dev, staging, prod
Show usage: /deploy [environment]
File Existence Checks
---
description: Process configuration
argument-hint: [config-file]
---
Check file exists: !`test -f $1 && echo "EXISTS" || echo "MISSING"`
If file exists:
Process configuration: @$1
Otherwise:
Explain where to place config file
Show expected format
Provide example configuration
Plugin Resource Validation
---
description: Run plugin analyzer
allowed-tools: Bash(test:*)
---
Validate plugin setup:
- Script: !`test -x ${CLAUDE_PLUGIN_ROOT}/bin/analyze && echo "✓" || echo "✗"`
- Config: !`test -f ${CLAUDE_PLUGIN_ROOT}/config.json && echo "✓" || echo "✗"`
If all checks pass, run analysis.
Otherwise, report missing components.
Error Handling
---
description: Build with error handling
allowed-tools: Bash(*)
---
Execute build: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh 2>&1 || echo "BUILD_FAILED"`
If build succeeded:
Report success and output location
If build failed:
Analyze error output
Suggest likely causes
Provide troubleshooting steps
Best practices:
- Validate early in command
- Provide helpful error messages
- Suggest corrective actions
- Handle edge cases gracefully
For detailed frontmatter field specifications, see references/frontmatter-reference.md.
For plugin-specific features and patterns, see references/plugin-features-reference.md.
For command pattern examples, see examples/ directory.
plugins/plugin-dev/skills/mcp-integration/SKILL.md
npx skills add anthropics/claude-code --skill MCP Integration -g -y
SKILL.md
Frontmatter
{
"name": "MCP Integration",
"version": "0.1.0",
"description": "This skill should be used when the user asks to \"add MCP server\", \"integrate MCP\", \"configure MCP in plugin\", \"use .mcp.json\", \"set up Model Context Protocol\", \"connect external service\", mentions \"${CLAUDE_PLUGIN_ROOT} with MCP\", or discusses MCP server types (SSE, stdio, HTTP, WebSocket). Provides comprehensive guidance for integrating Model Context Protocol servers into Claude Code plugins for external tool and service integration."
}
MCP Integration for Claude Code Plugins
Overview
Model Context Protocol (MCP) enables Claude Code plugins to integrate with external services and APIs by providing structured tool access. Use MCP integration to expose external service capabilities as tools within Claude Code.
Key capabilities:
- Connect to external services (databases, APIs, file systems)
- Provide 10+ related tools from a single service
- Handle OAuth and complex authentication flows
- Bundle MCP servers with plugins for automatic setup
MCP Server Configuration Methods
Plugins can bundle MCP servers in two ways:
Method 1: Dedicated .mcp.json (Recommended)
Create .mcp.json at plugin root:
{
"database-tools": {
"command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",
"args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"],
"env": {
"DB_URL": "${DB_URL}"
}
}
}
Benefits:
- Clear separation of concerns
- Easier to maintain
- Better for multiple servers
Method 2: Inline in plugin.json
Add mcpServers field to plugin.json:
{
"name": "my-plugin",
"version": "1.0.0",
"mcpServers": {
"plugin-api": {
"command": "${CLAUDE_PLUGIN_ROOT}/servers/api-server",
"args": ["--port", "8080"]
}
}
}
Benefits:
- Single configuration file
- Good for simple single-server plugins
MCP Server Types
stdio (Local Process)
Execute local MCP servers as child processes. Best for local tools and custom servers.
Configuration:
{
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"],
"env": {
"LOG_LEVEL": "debug"
}
}
}
Use cases:
- File system access
- Local database connections
- Custom MCP servers
- NPM-packaged MCP servers
Process management:
- Claude Code spawns and manages the process
- Communicates via stdin/stdout
- Terminates when Claude Code exits
SSE (Server-Sent Events)
Connect to hosted MCP servers with OAuth support. Best for cloud services.
Configuration:
{
"asana": {
"type": "sse",
"url": "https://mcp.asana.com/sse"
}
}
Use cases:
- Official hosted MCP servers (Asana, GitHub, etc.)
- Cloud services with MCP endpoints
- OAuth-based authentication
- No local installation needed
Authentication:
- OAuth flows handled automatically
- User prompted on first use
- Tokens managed by Claude Code
HTTP (REST API)
Connect to RESTful MCP servers with token authentication.
Configuration:
{
"api-service": {
"type": "http",
"url": "https://api.example.com/mcp",
"headers": {
"Authorization": "Bearer ${API_TOKEN}",
"X-Custom-Header": "value"
}
}
}
Use cases:
- REST API-based MCP servers
- Token-based authentication
- Custom API backends
- Stateless interactions
WebSocket (Real-time)
Connect to WebSocket MCP servers for real-time bidirectional communication.
Configuration:
{
"realtime-service": {
"type": "ws",
"url": "wss://mcp.example.com/ws",
"headers": {
"Authorization": "Bearer ${TOKEN}"
}
}
}
Use cases:
- Real-time data streaming
- Persistent connections
- Push notifications from server
- Low-latency requirements
Environment Variable Expansion
All MCP configurations support environment variable substitution:
${CLAUDE_PLUGIN_ROOT} - Plugin directory (always use for portability):
{
"command": "${CLAUDE_PLUGIN_ROOT}/servers/my-server"
}
User environment variables - From user's shell:
{
"env": {
"API_KEY": "${MY_API_KEY}",
"DATABASE_URL": "${DB_URL}"
}
}
Best practice: Document all required environment variables in plugin README.
MCP Tool Naming
When MCP servers provide tools, they're automatically prefixed:
Format: mcp__plugin_<plugin-name>_<server-name>__<tool-name>
Example:
- Plugin:
asana - Server:
asana - Tool:
create_task - Full name:
mcp__plugin_asana_asana__asana_create_task
Using MCP Tools in Commands
Pre-allow specific MCP tools in command frontmatter:
---
allowed-tools: [
"mcp__plugin_asana_asana__asana_create_task",
"mcp__plugin_asana_asana__asana_search_tasks"
]
---
Wildcard (use sparingly):
---
allowed-tools: ["mcp__plugin_asana_asana__*"]
---
Best practice: Pre-allow specific tools, not wildcards, for security.
Lifecycle Management
Automatic startup:
- MCP servers start when plugin enables
- Connection established before first tool use
- Restart required for configuration changes
Lifecycle:
- Plugin loads
- MCP configuration parsed
- Server process started (stdio) or connection established (SSE/HTTP/WS)
- Tools discovered and registered
- Tools available as
mcp__plugin_...__...
Viewing servers:
Use /mcp command to see all servers including plugin-provided ones.
Authentication Patterns
OAuth (SSE/HTTP)
OAuth handled automatically by Claude Code:
{
"type": "sse",
"url": "https://mcp.example.com/sse"
}
User authenticates in browser on first use. No additional configuration needed.
Token-Based (Headers)
Static or environment variable tokens:
{
"type": "http",
"url": "https://api.example.com",
"headers": {
"Authorization": "Bearer ${API_TOKEN}"
}
}
Document required environment variables in README.
Environment Variables (stdio)
Pass configuration to MCP server:
{
"command": "python",
"args": ["-m", "my_mcp_server"],
"env": {
"DATABASE_URL": "${DB_URL}",
"API_KEY": "${API_KEY}",
"LOG_LEVEL": "info"
}
}
Integration Patterns
Pattern 1: Simple Tool Wrapper
Commands use MCP tools with user interaction:
# Command: create-item.md
---
allowed-tools: ["mcp__plugin_name_server__create_item"]
---
Steps:
1. Gather item details from user
2. Use mcp__plugin_name_server__create_item
3. Confirm creation
Use for: Adding validation or preprocessing before MCP calls.
Pattern 2: Autonomous Agent
Agents use MCP tools autonomously:
# Agent: data-analyzer.md
Analysis Process:
1. Query data via mcp__plugin_db_server__query
2. Process and analyze results
3. Generate insights report
Use for: Multi-step MCP workflows without user interaction.
Pattern 3: Multi-Server Plugin
Integrate multiple MCP servers:
{
"github": {
"type": "sse",
"url": "https://mcp.github.com/sse"
},
"jira": {
"type": "sse",
"url": "https://mcp.jira.com/sse"
}
}
Use for: Workflows spanning multiple services.
Security Best Practices
Use HTTPS/WSS
Always use secure connections:
✅ "url": "https://mcp.example.com/sse"
❌ "url": "http://mcp.example.com/sse"
Token Management
DO:
- ✅ Use environment variables for tokens
- ✅ Document required env vars in README
- ✅ Let OAuth flow handle authentication
DON'T:
- ❌ Hardcode tokens in configuration
- ❌ Commit tokens to git
- ❌ Share tokens in documentation
Permission Scoping
Pre-allow only necessary MCP tools:
✅ allowed-tools: [
"mcp__plugin_api_server__read_data",
"mcp__plugin_api_server__create_item"
]
❌ allowed-tools: ["mcp__plugin_api_server__*"]
Error Handling
Connection Failures
Handle MCP server unavailability:
- Provide fallback behavior in commands
- Inform user of connection issues
- Check server URL and configuration
Tool Call Errors
Handle failed MCP operations:
- Validate inputs before calling MCP tools
- Provide clear error messages
- Check rate limiting and quotas
Configuration Errors
Validate MCP configuration:
- Test server connectivity during development
- Validate JSON syntax
- Check required environment variables
Performance Considerations
Lazy Loading
MCP servers connect on-demand:
- Not all servers connect at startup
- First tool use triggers connection
- Connection pooling managed automatically
Batching
Batch similar requests when possible:
# Good: Single query with filters
tasks = search_tasks(project="X", assignee="me", limit=50)
# Avoid: Many individual queries
for id in task_ids:
task = get_task(id)
Testing MCP Integration
Local Testing
- Configure MCP server in
.mcp.json - Install plugin locally (
.claude-plugin/) - Run
/mcpto verify server appears - Test tool calls in commands
- Check
claude --debuglogs for connection issues
Validation Checklist
- MCP configuration is valid JSON
- Server URL is correct and accessible
- Required environment variables documented
- Tools appear in
/mcpoutput - Authentication works (OAuth or tokens)
- Tool calls succeed from commands
- Error cases handled gracefully
Debugging
Enable Debug Logging
claude --debug
Look for:
- MCP server connection attempts
- Tool discovery logs
- Authentication flows
- Tool call errors
Common Issues
Server not connecting:
- Check URL is correct
- Verify server is running (stdio)
- Check network connectivity
- Review authentication configuration
Tools not available:
- Verify server connected successfully
- Check tool names match exactly
- Run
/mcpto see available tools - Restart Claude Code after config changes
Authentication failing:
- Clear cached auth tokens
- Re-authenticate
- Check token scopes and permissions
- Verify environment variables set
Quick Reference
MCP Server Types
| Type | Transport | Best For | Auth |
|---|---|---|---|
| stdio | Process | Local tools, custom servers | Env vars |
| SSE | HTTP | Hosted services, cloud APIs | OAuth |
| HTTP | REST | API backends, token auth | Tokens |
| ws | WebSocket | Real-time, streaming | Tokens |
Configuration Checklist
- Server type specified (stdio/SSE/HTTP/ws)
- Type-specific fields complete (command or url)
- Authentication configured
- Environment variables documented
- HTTPS/WSS used (not HTTP/WS)
- ${CLAUDE_PLUGIN_ROOT} used for paths
Best Practices
DO:
- ✅ Use ${CLAUDE_PLUGIN_ROOT} for portable paths
- ✅ Document required environment variables
- ✅ Use secure connections (HTTPS/WSS)
- ✅ Pre-allow specific MCP tools in commands
- ✅ Test MCP integration before publishing
- ✅ Handle connection and tool errors gracefully
DON'T:
- ❌ Hardcode absolute paths
- ❌ Commit credentials to git
- ❌ Use HTTP instead of HTTPS
- ❌ Pre-allow all tools with wildcards
- ❌ Skip error handling
- ❌ Forget to document setup
Additional Resources
Reference Files
For detailed information, consult:
references/server-types.md- Deep dive on each server typereferences/authentication.md- Authentication patterns and OAuthreferences/tool-usage.md- Using MCP tools in commands and agents
Example Configurations
Working examples in examples/:
stdio-server.json- Local stdio MCP serversse-server.json- Hosted SSE server with OAuthhttp-server.json- REST API with token auth
External Resources
- Official MCP Docs: https://modelcontextprotocol.io/
- Claude Code MCP Docs: https://docs.claude.com/en/docs/claude-code/mcp
- MCP SDK: @modelcontextprotocol/sdk
- Testing: Use
claude --debugand/mcpcommand
Implementation Workflow
To add MCP integration to a plugin:
- Choose MCP server type (stdio, SSE, HTTP, ws)
- Create
.mcp.jsonat plugin root with configuration - Use ${CLAUDE_PLUGIN_ROOT} for all file references
- Document required environment variables in README
- Test locally with
/mcpcommand - Pre-allow MCP tools in relevant commands
- Handle authentication (OAuth or tokens)
- Test error cases (connection failures, auth errors)
- Document MCP integration in plugin README
Focus on stdio for custom/local servers, SSE for hosted services with OAuth.
plugins/plugin-dev/skills/plugin-settings/SKILL.md
npx skills add anthropics/claude-code --skill Plugin Settings -g -y
SKILL.md
Frontmatter
{
"name": "Plugin Settings",
"version": "0.1.0",
"description": "This skill should be used when the user asks about \"plugin settings\", \"store plugin configuration\", \"user-configurable plugin\", \".local.md files\", \"plugin state files\", \"read YAML frontmatter\", \"per-project plugin settings\", or wants to make plugin behavior configurable. Documents the .claude\/plugin-name.local.md pattern for storing plugin-specific configuration with YAML frontmatter and markdown content."
}
Plugin Settings Pattern for Claude Code Plugins
Overview
Plugins can store user-configurable settings and state in .claude/plugin-name.local.md files within the project directory. This pattern uses YAML frontmatter for structured configuration and markdown content for prompts or additional context.
Key characteristics:
- File location:
.claude/plugin-name.local.mdin project root - Structure: YAML frontmatter + markdown body
- Purpose: Per-project plugin configuration and state
- Usage: Read from hooks, commands, and agents
- Lifecycle: User-managed (not in git, should be in
.gitignore)
File Structure
Basic Template
---
enabled: true
setting1: value1
setting2: value2
numeric_setting: 42
list_setting: ["item1", "item2"]
---
# Additional Context
This markdown body can contain:
- Task descriptions
- Additional instructions
- Prompts to feed back to Claude
- Documentation or notes
Example: Plugin State File
.claude/my-plugin.local.md:
---
enabled: true
strict_mode: false
max_retries: 3
notification_level: info
coordinator_session: team-leader
---
# Plugin Configuration
This plugin is configured for standard validation mode.
Contact @team-lead with questions.
Reading Settings Files
From Hooks (Bash Scripts)
Pattern: Check existence and parse frontmatter
#!/bin/bash
set -euo pipefail
# Define state file path
STATE_FILE=".claude/my-plugin.local.md"
# Quick exit if file doesn't exist
if [[ ! -f "$STATE_FILE" ]]; then
exit 0 # Plugin not configured, skip
fi
# Parse YAML frontmatter (between --- markers)
FRONTMATTER=$(sed -n '/^---$/,/^---$/{ /^---$/d; p; }' "$STATE_FILE")
# Extract individual fields
ENABLED=$(echo "$FRONTMATTER" | grep '^enabled:' | sed 's/enabled: *//' | sed 's/^"\(.*\)"$/\1/')
STRICT_MODE=$(echo "$FRONTMATTER" | grep '^strict_mode:' | sed 's/strict_mode: *//' | sed 's/^"\(.*\)"$/\1/')
# Check if enabled
if [[ "$ENABLED" != "true" ]]; then
exit 0 # Disabled
fi
# Use configuration in hook logic
if [[ "$STRICT_MODE" == "true" ]]; then
# Apply strict validation
# ...
fi
See examples/read-settings-hook.sh for complete working example.
From Commands
Commands can read settings files to customize behavior:
---
description: Process data with plugin
allowed-tools: ["Read", "Bash"]
---
# Process Command
Steps:
1. Check if settings exist at `.claude/my-plugin.local.md`
2. Read configuration using Read tool
3. Parse YAML frontmatter to extract settings
4. Apply settings to processing logic
5. Execute with configured behavior
From Agents
Agents can reference settings in their instructions:
---
name: configured-agent
description: Agent that adapts to project settings
---
Check for plugin settings at `.claude/my-plugin.local.md`.
If present, parse YAML frontmatter and adapt behavior according to:
- enabled: Whether plugin is active
- mode: Processing mode (strict, standard, lenient)
- Additional configuration fields
Parsing Techniques
Extract Frontmatter
# Extract everything between --- markers
FRONTMATTER=$(sed -n '/^---$/,/^---$/{ /^---$/d; p; }' "$FILE")
Read Individual Fields
String fields:
VALUE=$(echo "$FRONTMATTER" | grep '^field_name:' | sed 's/field_name: *//' | sed 's/^"\(.*\)"$/\1/')
Boolean fields:
ENABLED=$(echo "$FRONTMATTER" | grep '^enabled:' | sed 's/enabled: *//')
# Compare: if [[ "$ENABLED" == "true" ]]; then
Numeric fields:
MAX=$(echo "$FRONTMATTER" | grep '^max_value:' | sed 's/max_value: *//')
# Use: if [[ $MAX -gt 100 ]]; then
Read Markdown Body
Extract content after second ---:
# Get everything after closing ---
BODY=$(awk '/^---$/{i++; next} i>=2' "$FILE")
Common Patterns
Pattern 1: Temporarily Active Hooks
Use settings file to control hook activation:
#!/bin/bash
STATE_FILE=".claude/security-scan.local.md"
# Quick exit if not configured
if [[ ! -f "$STATE_FILE" ]]; then
exit 0
fi
# Read enabled flag
FRONTMATTER=$(sed -n '/^---$/,/^---$/{ /^---$/d; p; }' "$STATE_FILE")
ENABLED=$(echo "$FRONTMATTER" | grep '^enabled:' | sed 's/enabled: *//')
if [[ "$ENABLED" != "true" ]]; then
exit 0 # Disabled
fi
# Run hook logic
# ...
Use case: Enable/disable hooks without editing hooks.json (requires restart).
Pattern 2: Agent State Management
Store agent-specific state and configuration:
.claude/multi-agent-swarm.local.md:
---
agent_name: auth-agent
task_number: 3.5
pr_number: 1234
coordinator_session: team-leader
enabled: true
dependencies: ["Task 3.4"]
---
# Task Assignment
Implement JWT authentication for the API.
**Success Criteria:**
- Authentication endpoints created
- Tests passing
- PR created and CI green
Read from hooks to coordinate agents:
AGENT_NAME=$(echo "$FRONTMATTER" | grep '^agent_name:' | sed 's/agent_name: *//')
COORDINATOR=$(echo "$FRONTMATTER" | grep '^coordinator_session:' | sed 's/coordinator_session: *//')
# Send notification to coordinator
tmux send-keys -t "$COORDINATOR" "Agent $AGENT_NAME completed task" Enter
Pattern 3: Configuration-Driven Behavior
.claude/my-plugin.local.md:
---
validation_level: strict
max_file_size: 1000000
allowed_extensions: [".js", ".ts", ".tsx"]
enable_logging: true
---
# Validation Configuration
Strict mode enabled for this project.
All writes validated against security policies.
Use in hooks or commands:
LEVEL=$(echo "$FRONTMATTER" | grep '^validation_level:' | sed 's/validation_level: *//')
case "$LEVEL" in
strict)
# Apply strict validation
;;
standard)
# Apply standard validation
;;
lenient)
# Apply lenient validation
;;
esac
Creating Settings Files
From Commands
Commands can create settings files:
# Setup Command
Steps:
1. Ask user for configuration preferences
2. Create `.claude/my-plugin.local.md` with YAML frontmatter
3. Set appropriate values based on user input
4. Inform user that settings are saved
5. Remind user to restart Claude Code for hooks to recognize changes
Template Generation
Provide template in plugin README:
## Configuration
Create `.claude/my-plugin.local.md` in your project:
\`\`\`markdown
---
enabled: true
mode: standard
max_retries: 3
---
# Plugin Configuration
Your settings are active.
\`\`\`
After creating or editing, restart Claude Code for changes to take effect.
Best Practices
File Naming
✅ DO:
- Use
.claude/plugin-name.local.mdformat - Match plugin name exactly
- Use
.local.mdsuffix for user-local files
❌ DON'T:
- Use different directory (not
.claude/) - Use inconsistent naming
- Use
.mdwithout.local(might be committed)
Gitignore
Always add to .gitignore:
.claude/*.local.md
.claude/*.local.json
Document this in plugin README.
Defaults
Provide sensible defaults when settings file doesn't exist:
if [[ ! -f "$STATE_FILE" ]]; then
# Use defaults
ENABLED=true
MODE=standard
else
# Read from file
# ...
fi
Validation
Validate settings values:
MAX=$(echo "$FRONTMATTER" | grep '^max_value:' | sed 's/max_value: *//')
# Validate numeric range
if ! [[ "$MAX" =~ ^[0-9]+$ ]] || [[ $MAX -lt 1 ]] || [[ $MAX -gt 100 ]]; then
echo "⚠️ Invalid max_value in settings (must be 1-100)" >&2
MAX=10 # Use default
fi
Restart Requirement
Important: Settings changes require Claude Code restart.
Document in your README:
## Changing Settings
After editing `.claude/my-plugin.local.md`:
1. Save the file
2. Exit Claude Code
3. Restart: `claude` or `cc`
4. New settings will be loaded
Hooks cannot be hot-swapped within a session.
Security Considerations
Sanitize User Input
When writing settings files from user input:
# Escape quotes in user input
SAFE_VALUE=$(echo "$USER_INPUT" | sed 's/"/\\"/g')
# Write to file
cat > "$STATE_FILE" <<EOF
---
user_setting: "$SAFE_VALUE"
---
EOF
Validate File Paths
If settings contain file paths:
FILE_PATH=$(echo "$FRONTMATTER" | grep '^data_file:' | sed 's/data_file: *//')
# Check for path traversal
if [[ "$FILE_PATH" == *".."* ]]; then
echo "⚠️ Invalid path in settings (path traversal)" >&2
exit 2
fi
Permissions
Settings files should be:
- Readable by user only (
chmod 600) - Not committed to git
- Not shared between users
Real-World Examples
multi-agent-swarm Plugin
.claude/multi-agent-swarm.local.md:
---
agent_name: auth-implementation
task_number: 3.5
pr_number: 1234
coordinator_session: team-leader
enabled: true
dependencies: ["Task 3.4"]
additional_instructions: Use JWT tokens, not sessions
---
# Task: Implement Authentication
Build JWT-based authentication for the REST API.
Coordinate with auth-agent on shared types.
Hook usage (agent-stop-notification.sh):
- Checks if file exists (line 15-18: quick exit if not)
- Parses frontmatter to get coordinator_session, agent_name, enabled
- Sends notifications to coordinator if enabled
- Allows quick activation/deactivation via
enabled: true/false
ralph-wiggum Plugin
.claude/ralph-loop.local.md:
---
iteration: 1
max_iterations: 10
completion_promise: "All tests passing and build successful"
---
Fix all the linting errors in the project.
Make sure tests pass after each fix.
Hook usage (stop-hook.sh):
- Checks if file exists (line 15-18: quick exit if not active)
- Reads iteration count and max_iterations
- Extracts completion_promise for loop termination
- Reads body as the prompt to feed back
- Updates iteration count on each loop
Quick Reference
File Location
project-root/
└── .claude/
└── plugin-name.local.md
Frontmatter Parsing
# Extract frontmatter
FRONTMATTER=$(sed -n '/^---$/,/^---$/{ /^---$/d; p; }' "$FILE")
# Read field
VALUE=$(echo "$FRONTMATTER" | grep '^field:' | sed 's/field: *//' | sed 's/^"\(.*\)"$/\1/')
Body Parsing
# Extract body (after second ---)
BODY=$(awk '/^---$/{i++; next} i>=2' "$FILE")
Quick Exit Pattern
if [[ ! -f ".claude/my-plugin.local.md" ]]; then
exit 0 # Not configured
fi
Additional Resources
Reference Files
For detailed implementation patterns:
references/parsing-techniques.md- Complete guide to parsing YAML frontmatter and markdown bodiesreferences/real-world-examples.md- Deep dive into multi-agent-swarm and ralph-wiggum implementations
Example Files
Working examples in examples/:
read-settings-hook.sh- Hook that reads and uses settingscreate-settings-command.md- Command that creates settings fileexample-settings.md- Template settings file
Utility Scripts
Development tools in scripts/:
validate-settings.sh- Validate settings file structureparse-frontmatter.sh- Extract frontmatter fields
Implementation Workflow
To add settings to a plugin:
- Design settings schema (which fields, types, defaults)
- Create template file in plugin documentation
- Add gitignore entry for
.claude/*.local.md - Implement settings parsing in hooks/commands
- Use quick-exit pattern (check file exists, check enabled field)
- Document settings in plugin README with template
- Remind users that changes require Claude Code restart
Focus on keeping settings simple and providing good defaults when settings file doesn't exist.
plugins/plugin-dev/skills/plugin-structure/SKILL.md
npx skills add anthropics/claude-code --skill Plugin Structure -g -y
SKILL.md
Frontmatter
{
"name": "Plugin Structure",
"version": "0.1.0",
"description": "This skill should be used when the user asks to \"create a plugin\", \"scaffold a plugin\", \"understand plugin structure\", \"organize plugin components\", \"set up plugin.json\", \"use ${CLAUDE_PLUGIN_ROOT}\", \"add commands\/agents\/skills\/hooks\", \"configure auto-discovery\", or needs guidance on plugin directory layout, manifest configuration, component organization, file naming conventions, or Claude Code plugin architecture best practices."
}
Plugin Structure for Claude Code
Overview
Claude Code plugins follow a standardized directory structure with automatic component discovery. Understanding this structure enables creating well-organized, maintainable plugins that integrate seamlessly with Claude Code.
Key concepts:
- Conventional directory layout for automatic discovery
- Manifest-driven configuration in
.claude-plugin/plugin.json - Component-based organization (commands, agents, skills, hooks)
- Portable path references using
${CLAUDE_PLUGIN_ROOT} - Explicit vs. auto-discovered component loading
Directory Structure
Every Claude Code plugin follows this organizational pattern:
plugin-name/
├── .claude-plugin/
│ └── plugin.json # Required: Plugin manifest
├── commands/ # Slash commands (.md files)
├── agents/ # Subagent definitions (.md files)
├── skills/ # Agent skills (subdirectories)
│ └── skill-name/
│ └── SKILL.md # Required for each skill
├── hooks/
│ └── hooks.json # Event handler configuration
├── .mcp.json # MCP server definitions
└── scripts/ # Helper scripts and utilities
Critical rules:
- Manifest location: The
plugin.jsonmanifest MUST be in.claude-plugin/directory - Component locations: All component directories (commands, agents, skills, hooks) MUST be at plugin root level, NOT nested inside
.claude-plugin/ - Optional components: Only create directories for components the plugin actually uses
- Naming convention: Use kebab-case for all directory and file names
Plugin Manifest (plugin.json)
The manifest defines plugin metadata and configuration. Located at .claude-plugin/plugin.json:
Required Fields
{
"name": "plugin-name"
}
Name requirements:
- Use kebab-case format (lowercase with hyphens)
- Must be unique across installed plugins
- No spaces or special characters
- Example:
code-review-assistant,test-runner,api-docs
Recommended Metadata
{
"name": "plugin-name",
"version": "1.0.0",
"description": "Brief explanation of plugin purpose",
"author": {
"name": "Author Name",
"email": "author@example.com",
"url": "https://example.com"
},
"homepage": "https://docs.example.com",
"repository": "https://github.com/user/plugin-name",
"license": "MIT",
"keywords": ["testing", "automation", "ci-cd"]
}
Version format: Follow semantic versioning (MAJOR.MINOR.PATCH) Keywords: Use for plugin discovery and categorization
Component Path Configuration
Specify custom paths for components (supplements default directories):
{
"name": "plugin-name",
"commands": "./custom-commands",
"agents": ["./agents", "./specialized-agents"],
"hooks": "./config/hooks.json",
"mcpServers": "./.mcp.json"
}
Important: Custom paths supplement defaults—they don't replace them. Components in both default directories and custom paths will load.
Path rules:
- Must be relative to plugin root
- Must start with
./ - Cannot use absolute paths
- Support arrays for multiple locations
Component Organization
Commands
Location: commands/ directory
Format: Markdown files with YAML frontmatter
Auto-discovery: All .md files in commands/ load automatically
Example structure:
commands/
├── review.md # /review command
├── test.md # /test command
└── deploy.md # /deploy command
File format:
---
name: command-name
description: Command description
---
Command implementation instructions...
Usage: Commands integrate as native slash commands in Claude Code
Agents
Location: agents/ directory
Format: Markdown files with YAML frontmatter
Auto-discovery: All .md files in agents/ load automatically
Example structure:
agents/
├── code-reviewer.md
├── test-generator.md
└── refactorer.md
File format:
---
description: Agent role and expertise
capabilities:
- Specific task 1
- Specific task 2
---
Detailed agent instructions and knowledge...
Usage: Users can invoke agents manually, or Claude Code selects them automatically based on task context
Skills
Location: skills/ directory with subdirectories per skill
Format: Each skill in its own directory with SKILL.md file
Auto-discovery: All SKILL.md files in skill subdirectories load automatically
Example structure:
skills/
├── api-testing/
│ ├── SKILL.md
│ ├── scripts/
│ │ └── test-runner.py
│ └── references/
│ └── api-spec.md
└── database-migrations/
├── SKILL.md
└── examples/
└── migration-template.sql
SKILL.md format:
---
name: Skill Name
description: When to use this skill
version: 1.0.0
---
Skill instructions and guidance...
Supporting files: Skills can include scripts, references, examples, or assets in subdirectories
Usage: Claude Code autonomously activates skills based on task context matching the description
Hooks
Location: hooks/hooks.json or inline in plugin.json
Format: JSON configuration defining event handlers
Registration: Hooks register automatically when plugin enables
Example structure:
hooks/
├── hooks.json # Hook configuration
└── scripts/
├── validate.sh # Hook script
└── check-style.sh # Hook script
Configuration format:
{
"PreToolUse": [{
"matcher": "Write|Edit",
"hooks": [{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/hooks/scripts/validate.sh",
"timeout": 30
}]
}]
}
Available events: PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification
Usage: Hooks execute automatically in response to Claude Code events
MCP Servers
Location: .mcp.json at plugin root or inline in plugin.json
Format: JSON configuration for MCP server definitions
Auto-start: Servers start automatically when plugin enables
Example format:
{
"mcpServers": {
"server-name": {
"command": "node",
"args": ["${CLAUDE_PLUGIN_ROOT}/servers/server.js"],
"env": {
"API_KEY": "${API_KEY}"
}
}
}
}
Usage: MCP servers integrate seamlessly with Claude Code's tool system
Portable Path References
${CLAUDE_PLUGIN_ROOT}
Use ${CLAUDE_PLUGIN_ROOT} environment variable for all intra-plugin path references:
{
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/run.sh"
}
Why it matters: Plugins install in different locations depending on:
- User installation method (marketplace, local, npm)
- Operating system conventions
- User preferences
Where to use it:
- Hook command paths
- MCP server command arguments
- Script execution references
- Resource file paths
Never use:
- Hardcoded absolute paths (
/Users/name/plugins/...) - Relative paths from working directory (
./scripts/...in commands) - Home directory shortcuts (
~/plugins/...)
Path Resolution Rules
In manifest JSON fields (hooks, MCP servers):
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/tool.sh"
In component files (commands, agents, skills):
Reference scripts at: ${CLAUDE_PLUGIN_ROOT}/scripts/helper.py
In executed scripts:
#!/bin/bash
# ${CLAUDE_PLUGIN_ROOT} available as environment variable
source "${CLAUDE_PLUGIN_ROOT}/lib/common.sh"
File Naming Conventions
Component Files
Commands: Use kebab-case .md files
code-review.md→/code-reviewrun-tests.md→/run-testsapi-docs.md→/api-docs
Agents: Use kebab-case .md files describing role
test-generator.mdcode-reviewer.mdperformance-analyzer.md
Skills: Use kebab-case directory names
api-testing/database-migrations/error-handling/
Supporting Files
Scripts: Use descriptive kebab-case names with appropriate extensions
validate-input.shgenerate-report.pyprocess-data.js
Documentation: Use kebab-case markdown files
api-reference.mdmigration-guide.mdbest-practices.md
Configuration: Use standard names
hooks.json.mcp.jsonplugin.json
Auto-Discovery Mechanism
Claude Code automatically discovers and loads components:
- Plugin manifest: Reads
.claude-plugin/plugin.jsonwhen plugin enables - Commands: Scans
commands/directory for.mdfiles - Agents: Scans
agents/directory for.mdfiles - Skills: Scans
skills/for subdirectories containingSKILL.md - Hooks: Loads configuration from
hooks/hooks.jsonor manifest - MCP servers: Loads configuration from
.mcp.jsonor manifest
Discovery timing:
- Plugin installation: Components register with Claude Code
- Plugin enable: Components become available for use
- No restart required: Changes take effect on next Claude Code session
Override behavior: Custom paths in plugin.json supplement (not replace) default directories
Best Practices
Organization
-
Logical grouping: Group related components together
- Put test-related commands, agents, and skills together
- Create subdirectories in
scripts/for different purposes
-
Minimal manifest: Keep
plugin.jsonlean- Only specify custom paths when necessary
- Rely on auto-discovery for standard layouts
- Use inline configuration only for simple cases
-
Documentation: Include README files
- Plugin root: Overall purpose and usage
- Component directories: Specific guidance
- Script directories: Usage and requirements
Naming
-
Consistency: Use consistent naming across components
- If command is
test-runner, name related agenttest-runner-agent - Match skill directory names to their purpose
- If command is
-
Clarity: Use descriptive names that indicate purpose
- Good:
api-integration-testing/,code-quality-checker.md - Avoid:
utils/,misc.md,temp.sh
- Good:
-
Length: Balance brevity with clarity
- Commands: 2-3 words (
review-pr,run-ci) - Agents: Describe role clearly (
code-reviewer,test-generator) - Skills: Topic-focused (
error-handling,api-design)
- Commands: 2-3 words (
Portability
- Always use ${CLAUDE_PLUGIN_ROOT}: Never hardcode paths
- Test on multiple systems: Verify on macOS, Linux, Windows
- Document dependencies: List required tools and versions
- Avoid system-specific features: Use portable bash/Python constructs
Maintenance
- Version consistently: Update version in plugin.json for releases
- Deprecate gracefully: Mark old components clearly before removal
- Document breaking changes: Note changes affecting existing users
- Test thoroughly: Verify all components work after changes
Common Patterns
Minimal Plugin
Single command with no dependencies:
my-plugin/
├── .claude-plugin/
│ └── plugin.json # Just name field
└── commands/
└── hello.md # Single command
Full-Featured Plugin
Complete plugin with all component types:
my-plugin/
├── .claude-plugin/
│ └── plugin.json
├── commands/ # User-facing commands
├── agents/ # Specialized subagents
├── skills/ # Auto-activating skills
├── hooks/ # Event handlers
│ ├── hooks.json
│ └── scripts/
├── .mcp.json # External integrations
└── scripts/ # Shared utilities
Skill-Focused Plugin
Plugin providing only skills:
my-plugin/
├── .claude-plugin/
│ └── plugin.json
└── skills/
├── skill-one/
│ └── SKILL.md
└── skill-two/
└── SKILL.md
Troubleshooting
Component not loading:
- Verify file is in correct directory with correct extension
- Check YAML frontmatter syntax (commands, agents, skills)
- Ensure skill has
SKILL.md(notREADME.mdor other name) - Confirm plugin is enabled in Claude Code settings
Path resolution errors:
- Replace all hardcoded paths with
${CLAUDE_PLUGIN_ROOT} - Verify paths are relative and start with
./in manifest - Check that referenced files exist at specified paths
- Test with
echo $CLAUDE_PLUGIN_ROOTin hook scripts
Auto-discovery not working:
- Confirm directories are at plugin root (not in
.claude-plugin/) - Check file naming follows conventions (kebab-case, correct extensions)
- Verify custom paths in manifest are correct
- Restart Claude Code to reload plugin configuration
Conflicts between plugins:
- Use unique, descriptive component names
- Namespace commands with plugin name if needed
- Document potential conflicts in plugin README
- Consider command prefixes for related functionality
For detailed examples and advanced patterns, see files in references/ and examples/ directories.
plugins/plugin-dev/skills/skill-development/SKILL.md
npx skills add anthropics/claude-code --skill Skill Development -g -y
SKILL.md
Frontmatter
{
"name": "Skill Development",
"version": "0.1.0",
"description": "This skill should be used when the user wants to \"create a skill\", \"add a skill to plugin\", \"write a new skill\", \"improve skill description\", \"organize skill content\", or needs guidance on skill structure, progressive disclosure, or skill development best practices for Claude Code plugins."
}
Skill Development for Claude Code Plugins
This skill provides guidance for creating effective skills for Claude Code plugins.
About Skills
Skills are modular, self-contained packages that extend Claude's capabilities by providing specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific domains or tasks—they transform Claude from a general-purpose agent into a specialized agent equipped with procedural knowledge that no model can fully possess.
What Skills Provide
- Specialized workflows - Multi-step procedures for specific domains
- Tool integrations - Instructions for working with specific file formats or APIs
- Domain expertise - Company-specific knowledge, schemas, business logic
- Bundled resources - Scripts, references, and assets for complex and repetitive tasks
Anatomy of a Skill
Every skill consists of a required SKILL.md file and optional bundled resources:
skill-name/
├── SKILL.md (required)
│ ├── YAML frontmatter metadata (required)
│ │ ├── name: (required)
│ │ └── description: (required)
│ └── Markdown instructions (required)
└── Bundled Resources (optional)
├── scripts/ - Executable code (Python/Bash/etc.)
├── references/ - Documentation intended to be loaded into context as needed
└── assets/ - Files used in output (templates, icons, fonts, etc.)
SKILL.md (required)
Metadata Quality: The name and description in YAML frontmatter determine when Claude will use the skill. Be specific about what the skill does and when to use it. Use the third-person (e.g. "This skill should be used when..." instead of "Use this skill when...").
Bundled Resources (optional)
Scripts (scripts/)
Executable code (Python/Bash/etc.) for tasks that require deterministic reliability or are repeatedly rewritten.
- When to include: When the same code is being rewritten repeatedly or deterministic reliability is needed
- Example:
scripts/rotate_pdf.pyfor PDF rotation tasks - Benefits: Token efficient, deterministic, may be executed without loading into context
- Note: Scripts may still need to be read by Claude for patching or environment-specific adjustments
References (references/)
Documentation and reference material intended to be loaded as needed into context to inform Claude's process and thinking.
- When to include: For documentation that Claude should reference while working
- Examples:
references/finance.mdfor financial schemas,references/mnda.mdfor company NDA template,references/policies.mdfor company policies,references/api_docs.mdfor API specifications - Use cases: Database schemas, API documentation, domain knowledge, company policies, detailed workflow guides
- Benefits: Keeps SKILL.md lean, loaded only when Claude determines it's needed
- Best practice: If files are large (>10k words), include grep search patterns in SKILL.md
- Avoid duplication: 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.
Assets (assets/)
Files not intended to be loaded into context, but rather used within the output Claude produces.
- When to include: When the skill needs files that will be used in the final output
- Examples:
assets/logo.pngfor brand assets,assets/slides.pptxfor PowerPoint templates,assets/frontend-template/for HTML/React boilerplate,assets/font.ttffor typography - Use cases: Templates, images, icons, boilerplate code, fonts, sample documents that get copied or modified
- Benefits: Separates output resources from documentation, enables Claude to use files without loading them into context
Progressive Disclosure Design Principle
Skills use a three-level loading system to manage context efficiently:
- Metadata (name + description) - Always in context (~100 words)
- SKILL.md body - When skill triggers (<5k words)
- Bundled resources - As needed by Claude (Unlimited*)
*Unlimited because scripts can be executed without reading into context window.
Skill Creation Process
To create a skill, follow the "Skill Creation Process" in order, skipping steps only if there is a clear reason why they are not applicable.
Step 1: Understanding the Skill with Concrete Examples
Skip this step only when the skill's usage patterns are already clearly understood. It remains valuable even when working with an existing skill.
To create an effective skill, clearly understand concrete examples of how the skill will be used. This understanding can come from either direct user examples or generated examples that are validated with user feedback.
For example, when building an image-editor skill, relevant questions include:
- "What functionality should the image-editor skill support? Editing, rotating, anything else?"
- "Can you give some examples of how this skill would be used?"
- "I can imagine users asking for things like 'Remove the red-eye from this image' or 'Rotate this image'. Are there other ways you imagine this skill being used?"
- "What would a user say that should trigger this skill?"
To avoid overwhelming users, avoid asking too many questions in a single message. Start with the most important questions and follow up as needed for better effectiveness.
Conclude this step when there is a clear sense of the functionality the skill should support.
Step 2: Planning the Reusable Skill Contents
To turn concrete examples into an effective skill, analyze each example by:
- Considering how to execute on the example from scratch
- Identifying what scripts, references, and assets would be helpful when executing these workflows repeatedly
Example: When building a pdf-editor skill to handle queries like "Help me rotate this PDF," the analysis shows:
- Rotating a PDF requires re-writing the same code each time
- A
scripts/rotate_pdf.pyscript would be helpful to store in the skill
Example: When designing a frontend-webapp-builder skill for queries like "Build me a todo app" or "Build me a dashboard to track my steps," the analysis shows:
- Writing a frontend webapp requires the same boilerplate HTML/React each time
- An
assets/hello-world/template containing the boilerplate HTML/React project files would be helpful to store in the skill
Example: When building a big-query skill to handle queries like "How many users have logged in today?" the analysis shows:
- Querying BigQuery requires re-discovering the table schemas and relationships each time
- A
references/schema.mdfile documenting the table schemas would be helpful to store in the skill
For Claude Code plugins: When building a hooks skill, the analysis shows:
- Developers repeatedly need to validate hooks.json and test hook scripts
scripts/validate-hook-schema.shandscripts/test-hook.shutilities would be helpfulreferences/patterns.mdfor detailed hook patterns to avoid bloating SKILL.md
To establish the skill's contents, analyze each concrete example to create a list of the reusable resources to include: scripts, references, and assets.
Step 3: Create Skill Structure
For Claude Code plugins, create the skill directory structure:
mkdir -p plugin-name/skills/skill-name/{references,examples,scripts}
touch plugin-name/skills/skill-name/SKILL.md
Note: Unlike the generic skill-creator which uses init_skill.py, plugin skills are created directly in the plugin's skills/ directory with a simpler manual structure.
Step 4: Edit the Skill
When editing the (newly-created or existing) skill, remember that the skill is being created for another instance of Claude to use. Focus on including information that would be beneficial and non-obvious to Claude. Consider what procedural knowledge, domain-specific details, or reusable assets would help another Claude instance execute these tasks more effectively.
Start with Reusable Skill Contents
To begin implementation, start with the reusable resources identified above: scripts/, references/, and assets/ files. Note that this step may require user input. For example, when implementing a brand-guidelines skill, the user may need to provide brand assets or templates to store in assets/, or documentation to store in references/.
Also, delete any example files and directories not needed for the skill. Create only the directories you actually need (references/, examples/, scripts/).
Update SKILL.md
Writing Style: Write the entire skill using imperative/infinitive form (verb-first instructions), not second person. Use objective, instructional language (e.g., "To accomplish X, do Y" rather than "You should do X" or "If you need to do X"). This maintains consistency and clarity for AI consumption.
Description (Frontmatter): Use third-person format with specific trigger phrases:
---
name: Skill Name
description: This skill should be used when the user asks to "specific phrase 1", "specific phrase 2", "specific phrase 3". Include exact phrases users would say that should trigger this skill. Be concrete and specific.
version: 0.1.0
---
Good description examples:
description: This skill should be used when the user asks to "create a hook", "add a PreToolUse hook", "validate tool use", "implement prompt-based hooks", or mentions hook events (PreToolUse, PostToolUse, Stop).
Bad description examples:
description: Use this skill when working with hooks. # Wrong person, vague
description: Load when user needs hook help. # Not third person
description: Provides hook guidance. # No trigger phrases
To complete SKILL.md body, answer the following questions:
- What is the purpose of the skill, in a few sentences?
- When should the skill be used? (Include this in frontmatter description with specific triggers)
- In practice, how should Claude use the skill? All reusable skill contents developed above should be referenced so that Claude knows how to use them.
Keep SKILL.md lean: Target 1,500-2,000 words for the body. Move detailed content to references/:
- Detailed patterns →
references/patterns.md - Advanced techniques →
references/advanced.md - Migration guides →
references/migration.md - API references →
references/api-reference.md
Reference resources in SKILL.md:
## Additional Resources
### Reference Files
For detailed patterns and techniques, consult:
- **`references/patterns.md`** - Common patterns
- **`references/advanced.md`** - Advanced use cases
### Example Files
Working examples in `examples/`:
- **`example-script.sh`** - Working example
Step 5: Validate and Test
For plugin skills, validation is different from generic skills:
- Check structure: Skill directory in
plugin-name/skills/skill-name/ - Validate SKILL.md: Has frontmatter with name and description
- Check trigger phrases: Description includes specific user queries
- Verify writing style: Body uses imperative/infinitive form, not second person
- Test progressive disclosure: SKILL.md is lean (~1,500-2,000 words), detailed content in references/
- Check references: All referenced files exist
- Validate examples: Examples are complete and correct
- Test scripts: Scripts are executable and work correctly
Use the skill-reviewer agent:
Ask: "Review my skill and check if it follows best practices"
The skill-reviewer agent will check description quality, content organization, and progressive disclosure.
Step 6: Iterate
After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.
Iteration workflow:
- Use the skill on real tasks
- Notice struggles or inefficiencies
- Identify how SKILL.md or bundled resources should be updated
- Implement changes and test again
Common improvements:
- Strengthen trigger phrases in description
- Move long sections from SKILL.md to references/
- Add missing examples or scripts
- Clarify ambiguous instructions
- Add edge case handling
Plugin-Specific Considerations
Skill Location in Plugins
Plugin skills live in the plugin's skills/ directory:
my-plugin/
├── .claude-plugin/
│ └── plugin.json
├── commands/
├── agents/
└── skills/
└── my-skill/
├── SKILL.md
├── references/
├── examples/
└── scripts/
Auto-Discovery
Claude Code automatically discovers skills:
- Scans
skills/directory - Finds subdirectories containing
SKILL.md - Loads skill metadata (name + description) always
- Loads SKILL.md body when skill triggers
- Loads references/examples when needed
No Packaging Needed
Plugin skills are distributed as part of the plugin, not as separate ZIP files. Users get skills when they install the plugin.
Testing in Plugins
Test skills by installing plugin locally:
# Test with --plugin-dir
cc --plugin-dir /path/to/plugin
# Ask questions that should trigger the skill
# Verify skill loads correctly
Examples from Plugin-Dev
Study the skills in this plugin as examples of best practices:
hook-development skill:
- Excellent trigger phrases: "create a hook", "add a PreToolUse hook", etc.
- Lean SKILL.md (1,651 words)
- 3 references/ files for detailed content
- 3 examples/ of working hooks
- 3 scripts/ utilities
agent-development skill:
- Strong triggers: "create an agent", "agent frontmatter", etc.
- Focused SKILL.md (1,438 words)
- References include the AI generation prompt from Claude Code
- Complete agent examples
plugin-settings skill:
- Specific triggers: "plugin settings", ".local.md files", "YAML frontmatter"
- References show real implementations (multi-agent-swarm, ralph-wiggum)
- Working parsing scripts
Each demonstrates progressive disclosure and strong triggering.
Progressive Disclosure in Practice
What Goes in SKILL.md
Include (always loaded when skill triggers):
- Core concepts and overview
- Essential procedures and workflows
- Quick reference tables
- Pointers to references/examples/scripts
- Most common use cases
Keep under 3,000 words, ideally 1,500-2,000 words
What Goes in references/
Move to references/ (loaded as needed):
- Detailed patterns and advanced techniques
- Comprehensive API documentation
- Migration guides
- Edge cases and troubleshooting
- Extensive examples and walkthroughs
Each reference file can be large (2,000-5,000+ words)
What Goes in examples/
Working code examples:
- Complete, runnable scripts
- Configuration files
- Template files
- Real-world usage examples
Users can copy and adapt these directly
What Goes in scripts/
Utility scripts:
- Validation tools
- Testing helpers
- Parsing utilities
- Automation scripts
Should be executable and documented
Writing Style Requirements
Imperative/Infinitive Form
Write using verb-first instructions, not second person:
Correct (imperative):
To create a hook, define the event type.
Configure the MCP server with authentication.
Validate settings before use.
Incorrect (second person):
You should create a hook by defining the event type.
You need to configure the MCP server.
You must validate settings before use.
Third-Person in Description
The frontmatter description must use third person:
Correct:
description: This skill should be used when the user asks to "create X", "configure Y"...
Incorrect:
description: Use this skill when you want to create X...
description: Load this skill when user asks...
Objective, Instructional Language
Focus on what to do, not who should do it:
Correct:
Parse the frontmatter using sed.
Extract fields with grep.
Validate values before use.
Incorrect:
You can parse the frontmatter...
Claude should extract fields...
The user might validate values...
Validation Checklist
Before finalizing a skill:
Structure:
- SKILL.md file exists with valid YAML frontmatter
- Frontmatter has
nameanddescriptionfields - Markdown body is present and substantial
- Referenced files actually exist
Description Quality:
- Uses third person ("This skill should be used when...")
- Includes specific trigger phrases users would say
- Lists concrete scenarios ("create X", "configure Y")
- Not vague or generic
Content Quality:
- SKILL.md body uses imperative/infinitive form
- Body is focused and lean (1,500-2,000 words ideal, <5k max)
- Detailed content moved to references/
- Examples are complete and working
- Scripts are executable and documented
Progressive Disclosure:
- Core concepts in SKILL.md
- Detailed docs in references/
- Working code in examples/
- Utilities in scripts/
- SKILL.md references these resources
Testing:
- Skill triggers on expected user queries
- Content is helpful for intended tasks
- No duplicated information across files
- References load when needed
Common Mistakes to Avoid
Mistake 1: Weak Trigger Description
❌ Bad:
description: Provides guidance for working with hooks.
Why bad: Vague, no specific trigger phrases, not third person
✅ Good:
description: This skill should be used when the user asks to "create a hook", "add a PreToolUse hook", "validate tool use", or mentions hook events. Provides comprehensive hooks API guidance.
Why good: Third person, specific phrases, concrete scenarios
Mistake 2: Too Much in SKILL.md
❌ Bad:
skill-name/
└── SKILL.md (8,000 words - everything in one file)
Why bad: Bloats context when skill loads, detailed content always loaded
✅ Good:
skill-name/
├── SKILL.md (1,800 words - core essentials)
└── references/
├── patterns.md (2,500 words)
└── advanced.md (3,700 words)
Why good: Progressive disclosure, detailed content loaded only when needed
Mistake 3: Second Person Writing
❌ Bad:
You should start by reading the configuration file.
You need to validate the input.
You can use the grep tool to search.
Why bad: Second person, not imperative form
✅ Good:
Start by reading the configuration file.
Validate the input before processing.
Use the grep tool to search for patterns.
Why good: Imperative form, direct instructions
Mistake 4: Missing Resource References
❌ Bad:
# SKILL.md
[Core content]
[No mention of references/ or examples/]
Why bad: Claude doesn't know references exist
✅ Good:
# SKILL.md
[Core content]
## Additional Resources
### Reference Files
- **`references/patterns.md`** - Detailed patterns
- **`references/advanced.md`** - Advanced techniques
### Examples
- **`examples/script.sh`** - Working example
Why good: Claude knows where to find additional information
Quick Reference
Minimal Skill
skill-name/
└── SKILL.md
Good for: Simple knowledge, no complex resources needed
Standard Skill (Recommended)
skill-name/
├── SKILL.md
├── references/
│ └── detailed-guide.md
└── examples/
└── working-example.sh
Good for: Most plugin skills with detailed documentation
Complete Skill
skill-name/
├── SKILL.md
├── references/
│ ├── patterns.md
│ └── advanced.md
├── examples/
│ ├── example1.sh
│ └── example2.json
└── scripts/
└── validate.sh
Good for: Complex domains with validation utilities
Best Practices Summary
✅ DO:
- Use third-person in description ("This skill should be used when...")
- Include specific trigger phrases ("create X", "configure Y")
- Keep SKILL.md lean (1,500-2,000 words)
- Use progressive disclosure (move details to references/)
- Write in imperative/infinitive form
- Reference supporting files clearly
- Provide working examples
- Create utility scripts for common operations
- Study plugin-dev's skills as templates
❌ DON'T:
- Use second person anywhere
- Have vague trigger conditions
- Put everything in SKILL.md (>3,000 words without references/)
- Write in second person ("You should...")
- Leave resources unreferenced
- Include broken or incomplete examples
- Skip validation
Additional Resources
Study These Skills
Plugin-dev's skills demonstrate best practices:
../hook-development/- Progressive disclosure, utilities../agent-development/- AI-assisted creation, references../mcp-integration/- Comprehensive references../plugin-settings/- Real-world examples../command-development/- Clear critical concepts../plugin-structure/- Good organization
Reference Files
For complete skill-creator methodology:
references/skill-creator-original.md- Full original skill-creator content
Implementation Workflow
To create a skill for your plugin:
- Understand use cases: Identify concrete examples of skill usage
- Plan resources: Determine what scripts/references/examples needed
- Create structure:
mkdir -p skills/skill-name/{references,examples,scripts} - Write SKILL.md:
- Frontmatter with third-person description and trigger phrases
- Lean body (1,500-2,000 words) in imperative form
- Reference supporting files
- Add resources: Create references/, examples/, scripts/ as needed
- Validate: Check description, writing style, organization
- Test: Verify skill loads on expected triggers
- Iterate: Improve based on usage
Focus on strong trigger descriptions, progressive disclosure, and imperative writing style for effective skills that load when needed and provide targeted guidance.
plugins/plugin-dev/skills/hook-development/SKILL.md
npx skills add anthropics/claude-code --skill Hook Development -g -y
SKILL.md
Frontmatter
{
"name": "Hook Development",
"version": "0.1.0",
"description": "This skill should be used when the user asks to \"create a hook\", \"add a PreToolUse\/PostToolUse\/Stop hook\", \"validate tool use\", \"implement prompt-based hooks\", \"use ${CLAUDE_PLUGIN_ROOT}\", \"set up event-driven automation\", \"block dangerous commands\", or mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API."
}
Hook Development for Claude Code Plugins
Overview
Hooks are event-driven automation scripts that execute in response to Claude Code events. Use hooks to validate operations, enforce policies, add context, and integrate external tools into workflows.
Key capabilities:
- Validate tool calls before execution (PreToolUse)
- React to tool results (PostToolUse)
- Enforce completion standards (Stop, SubagentStop)
- Load project context (SessionStart)
- Automate workflows across the development lifecycle
Hook Types
Prompt-Based Hooks (Recommended)
Use LLM-driven decision making for context-aware validation:
{
"type": "prompt",
"prompt": "Evaluate if this tool use is appropriate: $TOOL_INPUT",
"timeout": 30
}
Supported events: Stop, SubagentStop, UserPromptSubmit, PreToolUse
Benefits:
- Context-aware decisions based on natural language reasoning
- Flexible evaluation logic without bash scripting
- Better edge case handling
- Easier to maintain and extend
Command Hooks
Execute bash commands for deterministic checks:
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh",
"timeout": 60
}
Use for:
- Fast deterministic validations
- File system operations
- External tool integrations
- Performance-critical checks
Hook Configuration Formats
Plugin hooks.json Format
For plugin hooks in hooks/hooks.json, use wrapper format:
{
"description": "Brief explanation of hooks (optional)",
"hooks": {
"PreToolUse": [...],
"Stop": [...],
"SessionStart": [...]
}
}
Key points:
descriptionfield is optionalhooksfield is required wrapper containing actual hook events- This is the plugin-specific format
Example:
{
"description": "Validation hooks for code quality",
"hooks": {
"PreToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/validate.sh"
}
]
}
]
}
}
Settings Format (Direct)
For user settings in .claude/settings.json, use direct format:
{
"PreToolUse": [...],
"Stop": [...],
"SessionStart": [...]
}
Key points:
- No wrapper - events directly at top level
- No description field
- This is the settings format
Important: The examples below show the hook event structure that goes inside either format. For plugin hooks.json, wrap these in {"hooks": {...}}.
Hook Events
PreToolUse
Execute before any tool runs. Use to approve, deny, or modify tool calls.
Example (prompt-based):
{
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "prompt",
"prompt": "Validate file write safety. Check: system paths, credentials, path traversal, sensitive content. Return 'approve' or 'deny'."
}
]
}
]
}
Output for PreToolUse:
{
"hookSpecificOutput": {
"permissionDecision": "allow|deny|ask",
"updatedInput": {"field": "modified_value"}
},
"systemMessage": "Explanation for Claude"
}
PostToolUse
Execute after tool completes. Use to react to results, provide feedback, or log.
Example:
{
"PostToolUse": [
{
"matcher": "Edit",
"hooks": [
{
"type": "prompt",
"prompt": "Analyze edit result for potential issues: syntax errors, security vulnerabilities, breaking changes. Provide feedback."
}
]
}
]
}
Output behavior:
- Exit 0: stdout shown in transcript
- Exit 2: stderr fed back to Claude
- systemMessage included in context
Stop
Execute when main agent considers stopping. Use to validate completeness.
Example:
{
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Verify task completion: tests run, build succeeded, questions answered. Return 'approve' to stop or 'block' with reason to continue."
}
]
}
]
}
Decision output:
{
"decision": "approve|block",
"reason": "Explanation",
"systemMessage": "Additional context"
}
SubagentStop
Execute when subagent considers stopping. Use to ensure subagent completed its task.
Similar to Stop hook, but for subagents.
UserPromptSubmit
Execute when user submits a prompt. Use to add context, validate, or block prompts.
Example:
{
"UserPromptSubmit": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Check if prompt requires security guidance. If discussing auth, permissions, or API security, return relevant warnings."
}
]
}
]
}
SessionStart
Execute when Claude Code session begins. Use to load context and set environment.
Example:
{
"SessionStart": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/load-context.sh"
}
]
}
]
}
Special capability: Persist environment variables using $CLAUDE_ENV_FILE:
echo "export PROJECT_TYPE=nodejs" >> "$CLAUDE_ENV_FILE"
See examples/load-context.sh for complete example.
SessionEnd
Execute when session ends. Use for cleanup, logging, and state preservation.
PreCompact
Execute before context compaction. Use to add critical information to preserve.
Notification
Execute when Claude sends notifications. Use to react to user notifications.
Hook Output Format
Standard Output (All Hooks)
{
"continue": true,
"suppressOutput": false,
"systemMessage": "Message for Claude"
}
continue: If false, halt processing (default true)suppressOutput: Hide output from transcript (default false)systemMessage: Message shown to Claude
Exit Codes
0- Success (stdout shown in transcript)2- Blocking error (stderr fed back to Claude)- Other - Non-blocking error
Hook Input Format
All hooks receive JSON via stdin with common fields:
{
"session_id": "abc123",
"transcript_path": "/path/to/transcript.txt",
"cwd": "/current/working/dir",
"permission_mode": "ask|allow",
"hook_event_name": "PreToolUse"
}
Event-specific fields:
- PreToolUse/PostToolUse:
tool_name,tool_input,tool_result - UserPromptSubmit:
user_prompt - Stop/SubagentStop:
reason
Access fields in prompts using $TOOL_INPUT, $TOOL_RESULT, $USER_PROMPT, etc.
Environment Variables
Available in all command hooks:
$CLAUDE_PROJECT_DIR- Project root path$CLAUDE_PLUGIN_ROOT- Plugin directory (use for portable paths)$CLAUDE_ENV_FILE- SessionStart only: persist env vars here$CLAUDE_CODE_REMOTE- Set if running in remote context
Always use ${CLAUDE_PLUGIN_ROOT} in hook commands for portability:
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh"
}
Plugin Hook Configuration
In plugins, define hooks in hooks/hooks.json:
{
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "prompt",
"prompt": "Validate file write safety"
}
]
}
],
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Verify task completion"
}
]
}
],
"SessionStart": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/load-context.sh",
"timeout": 10
}
]
}
]
}
Plugin hooks merge with user's hooks and run in parallel.
Matchers
Tool Name Matching
Exact match:
"matcher": "Write"
Multiple tools:
"matcher": "Read|Write|Edit"
Wildcard (all tools):
"matcher": "*"
Regex patterns:
"matcher": "mcp__.*__delete.*" // All MCP delete tools
Note: Matchers are case-sensitive.
Common Patterns
// All MCP tools
"matcher": "mcp__.*"
// Specific plugin's MCP tools
"matcher": "mcp__plugin_asana_.*"
// All file operations
"matcher": "Read|Write|Edit"
// Bash commands only
"matcher": "Bash"
Security Best Practices
Input Validation
Always validate inputs in command hooks:
#!/bin/bash
set -euo pipefail
input=$(cat)
tool_name=$(echo "$input" | jq -r '.tool_name')
# Validate tool name format
if [[ ! "$tool_name" =~ ^[a-zA-Z0-9_]+$ ]]; then
echo '{"decision": "deny", "reason": "Invalid tool name"}' >&2
exit 2
fi
Path Safety
Check for path traversal and sensitive files:
file_path=$(echo "$input" | jq -r '.tool_input.file_path')
# Deny path traversal
if [[ "$file_path" == *".."* ]]; then
echo '{"decision": "deny", "reason": "Path traversal detected"}' >&2
exit 2
fi
# Deny sensitive files
if [[ "$file_path" == *".env"* ]]; then
echo '{"decision": "deny", "reason": "Sensitive file"}' >&2
exit 2
fi
See examples/validate-write.sh and examples/validate-bash.sh for complete examples.
Quote All Variables
# GOOD: Quoted
echo "$file_path"
cd "$CLAUDE_PROJECT_DIR"
# BAD: Unquoted (injection risk)
echo $file_path
cd $CLAUDE_PROJECT_DIR
Set Appropriate Timeouts
{
"type": "command",
"command": "bash script.sh",
"timeout": 10
}
Defaults: Command hooks (60s), Prompt hooks (30s)
Performance Considerations
Parallel Execution
All matching hooks run in parallel:
{
"PreToolUse": [
{
"matcher": "Write",
"hooks": [
{"type": "command", "command": "check1.sh"}, // Parallel
{"type": "command", "command": "check2.sh"}, // Parallel
{"type": "prompt", "prompt": "Validate..."} // Parallel
]
}
]
}
Design implications:
- Hooks don't see each other's output
- Non-deterministic ordering
- Design for independence
Optimization
- Use command hooks for quick deterministic checks
- Use prompt hooks for complex reasoning
- Cache validation results in temp files
- Minimize I/O in hot paths
Temporarily Active Hooks
Create hooks that activate conditionally by checking for a flag file or configuration:
Pattern: Flag file activation
#!/bin/bash
# Only active when flag file exists
FLAG_FILE="$CLAUDE_PROJECT_DIR/.enable-strict-validation"
if [ ! -f "$FLAG_FILE" ]; then
# Flag not present, skip validation
exit 0
fi
# Flag present, run validation
input=$(cat)
# ... validation logic ...
Pattern: Configuration-based activation
#!/bin/bash
# Check configuration for activation
CONFIG_FILE="$CLAUDE_PROJECT_DIR/.claude/plugin-config.json"
if [ -f "$CONFIG_FILE" ]; then
enabled=$(jq -r '.strictMode // false' "$CONFIG_FILE")
if [ "$enabled" != "true" ]; then
exit 0 # Not enabled, skip
fi
fi
# Enabled, run hook logic
input=$(cat)
# ... hook logic ...
Use cases:
- Enable strict validation only when needed
- Temporary debugging hooks
- Project-specific hook behavior
- Feature flags for hooks
Best practice: Document activation mechanism in plugin README so users know how to enable/disable temporary hooks.
Hook Lifecycle and Limitations
Hooks Load at Session Start
Important: Hooks are loaded when Claude Code session starts. Changes to hook configuration require restarting Claude Code.
Cannot hot-swap hooks:
- Editing
hooks/hooks.jsonwon't affect current session - Adding new hook scripts won't be recognized
- Changing hook commands/prompts won't update
- Must restart Claude Code: exit and run
claudeagain
To test hook changes:
- Edit hook configuration or scripts
- Exit Claude Code session
- Restart:
claudeorcc - New hook configuration loads
- Test hooks with
claude --debug
Hook Validation at Startup
Hooks are validated when Claude Code starts:
- Invalid JSON in hooks.json causes loading failure
- Missing scripts cause warnings
- Syntax errors reported in debug mode
Use /hooks command to review loaded hooks in current session.
Debugging Hooks
Enable Debug Mode
claude --debug
Look for hook registration, execution logs, input/output JSON, and timing information.
Test Hook Scripts
Test command hooks directly:
echo '{"tool_name": "Write", "tool_input": {"file_path": "/test"}}' | \
bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh
echo "Exit code: $?"
Validate JSON Output
Ensure hooks output valid JSON:
output=$(./your-hook.sh < test-input.json)
echo "$output" | jq .
Quick Reference
Hook Events Summary
| Event | When | Use For |
|---|---|---|
| PreToolUse | Before tool | Validation, modification |
| PostToolUse | After tool | Feedback, logging |
| UserPromptSubmit | User input | Context, validation |
| Stop | Agent stopping | Completeness check |
| SubagentStop | Subagent done | Task validation |
| SessionStart | Session begins | Context loading |
| SessionEnd | Session ends | Cleanup, logging |
| PreCompact | Before compact | Preserve context |
| Notification | User notified | Logging, reactions |
Best Practices
DO:
- ✅ Use prompt-based hooks for complex logic
- ✅ Use ${CLAUDE_PLUGIN_ROOT} for portability
- ✅ Validate all inputs in command hooks
- ✅ Quote all bash variables
- ✅ Set appropriate timeouts
- ✅ Return structured JSON output
- ✅ Test hooks thoroughly
DON'T:
- ❌ Use hardcoded paths
- ❌ Trust user input without validation
- ❌ Create long-running hooks
- ❌ Rely on hook execution order
- ❌ Modify global state unpredictably
- ❌ Log sensitive information
Additional Resources
Reference Files
For detailed patterns and advanced techniques, consult:
references/patterns.md- Common hook patterns (8+ proven patterns)references/migration.md- Migrating from basic to advanced hooksreferences/advanced.md- Advanced use cases and techniques
Example Hook Scripts
Working examples in examples/:
validate-write.sh- File write validation examplevalidate-bash.sh- Bash command validation exampleload-context.sh- SessionStart context loading example
Utility Scripts
Development tools in scripts/:
validate-hook-schema.sh- Validate hooks.json structure and syntaxtest-hook.sh- Test hooks with sample input before deploymenthook-linter.sh- Check hook scripts for common issues and best practices
External Resources
- Official Docs: https://docs.claude.com/en/docs/claude-code/hooks
- Examples: See security-guidance plugin in marketplace
- Testing: Use
claude --debugfor detailed logs - Validation: Use
jqto validate hook JSON output
Implementation Workflow
To implement hooks in a plugin:
- Identify events to hook into (PreToolUse, Stop, SessionStart, etc.)
- Decide between prompt-based (flexible) or command (deterministic) hooks
- Write hook configuration in
hooks/hooks.json - For command hooks, create hook scripts
- Use ${CLAUDE_PLUGIN_ROOT} for all file references
- Validate configuration with
scripts/validate-hook-schema.sh hooks/hooks.json - Test hooks with
scripts/test-hook.shbefore deployment - Test in Claude Code with
claude --debug - Document hooks in plugin README
Focus on prompt-based hooks for most use cases. Reserve command hooks for performance-critical or deterministic checks.


