22 KiB
Claude Code Plugin Creation Guide for Agents
This guide provides comprehensive instructions for AI agents to create new Claude Code plugins within this multi-plugin marketplace repository.
Table of Contents
- Overview
- Plugin Structure
- Creating a New Plugin
- Component Specifications
- Best Practices
- Testing and Validation
Overview
What is a Claude Code Plugin?
A Claude Code plugin extends Claude's capabilities with:
- Custom slash commands - User-invocable commands (e.g.,
/namespace:command) - Specialized agents - Autonomous task-focused assistants
- Skills - Auto-activating expertise based on context
- Hooks - Event-driven automation
- Scripts - Reusable bash utilities
Multi-Plugin Repository Structure
repository-root/
├── .claude-plugin/
│ └── marketplace.json # Lists all plugins in this marketplace
├── plugins/
│ ├── plugin-name-1/ # First plugin
│ │ └── .claude-plugin/
│ │ └── plugin.json
│ └── plugin-name-2/ # Second plugin
│ └── .claude-plugin/
│ └── plugin.json
├── README.md # Main marketplace documentation
└── PLUGIN_CREATION_GUIDE.md # This guide
Plugin Structure
Required Directory Structure
Each plugin MUST follow this structure:
plugins/{plugin-name}/
├── .claude-plugin/
│ └── plugin.json # REQUIRED: Plugin metadata
├── commands/ # OPTIONAL: Slash commands
│ └── *.md # Command definitions
├── agents/ # OPTIONAL: Custom agents
│ └── *.md # Agent definitions
├── skills/ # OPTIONAL: Auto-activating skills
│ └── {skill-name}/
│ └── SKILL.md # Skill definition (MUST be named SKILL.md)
├── hooks/ # OPTIONAL: Event hooks
│ └── hooks.json # Hook definitions
├── scripts/ # OPTIONAL: Helper scripts
│ └── *.sh # Bash scripts
└── README.md # RECOMMENDED: Plugin documentation
Naming Conventions
- Plugin namespace: Short, lowercase, no spaces (e.g.,
gd,py,web) - Commands: Use
namespace:actionformat (e.g.,/gd:setup,/py:test) - Files: Use kebab-case for markdown files (e.g.,
setup.md,init-game.md) - Scripts: Use kebab-case with
.shextension (e.g.,validate-env.sh) - Directories: Use lowercase with hyphens (e.g.,
game-planner,godot-dev)
Creating a New Plugin
Step 1: Plan Your Plugin
Define:
- Purpose: What does this plugin do?
- Target users: Who will use it?
- Namespace: What 2-4 letter prefix? (e.g.,
gdfor Godot,pyfor Python) - Core features: What commands/agents/skills are needed?
- Dependencies: What external tools or MCP servers are required?
Step 2: Create Plugin Directory
mkdir -p plugins/{namespace}/.claude-plugin
mkdir -p plugins/{namespace}/commands
mkdir -p plugins/{namespace}/agents
mkdir -p plugins/{namespace}/skills
mkdir -p plugins/{namespace}/hooks
mkdir -p plugins/{namespace}/scripts
Step 3: Create plugin.json
Required file: plugins/{namespace}/.claude-plugin/plugin.json
{
"name": "namespace",
"version": "1.0.0",
"description": "Brief description of what this plugin does and its key features",
"author": {
"name": "Author Name",
"email": "author@example.com",
"url": "https://github.com/username"
},
"homepage": "https://github.com/username/repo",
"repository": "https://github.com/username/repo",
"license": "MIT",
"keywords": ["keyword1", "keyword2", "keyword3"]
}
Required fields:
name: Plugin namespace (MUST match directory name)version: Semantic version (e.g., "1.0.0")description: Clear, concise description
Optional but recommended:
author: Object withname,email,urlhomepage: Plugin website or reporepository: GitHub repo URLlicense: License typekeywords: Array of searchable keywords
Step 4: Register in Marketplace
Edit .claude-plugin/marketplace.json to add your plugin:
{
"name": "marketplace-name",
"owner": {
"name": "Owner Name",
"email": "owner@example.com"
},
"plugins": [
{
"name": "existing-plugin",
"source": "./plugins/existing-plugin",
"description": "Existing plugin description",
"category": "development",
"tags": ["tag1", "tag2"]
},
{
"name": "namespace",
"source": "./plugins/namespace",
"description": "Your new plugin description",
"category": "development",
"tags": ["your", "tags"]
}
]
}
Categories: development, productivity, ai, tools, gaming, web, data, other
Step 5: Add Components
Add commands, agents, skills, hooks, and scripts as needed (see Component Specifications below).
Step 6: Create Documentation
Create plugins/{namespace}/README.md with:
- Plugin overview
- Installation instructions
- Usage examples
- Available commands
- Configuration options
- Troubleshooting
Component Specifications
Commands (commands/*.md)
Slash commands are markdown files with YAML frontmatter.
File format: commands/{command-name}.md
Template:
---
description: Brief description of what this command does
allowed-tools:
- Tool1
- Tool2(specific:function)
- Bash(command1:*,command2:*)
---
Prompt that Claude will receive when the command is invoked.
You can:
- Give instructions
- Reference scripts: !bash ${CLAUDE_PLUGIN_ROOT}/scripts/script-name.sh
- Use environment variables: ${CLAUDE_PROJECT_DIR}, ${CLAUDE_PLUGIN_ROOT}
- Provide context and guidance
Frontmatter fields:
description(REQUIRED): Shows up when listing commandsallowed-tools(OPTIONAL): Restrict which tools Claude can use- Use
*for wildcards (e.g.,mcp__godot__*) - Specify exact patterns (e.g.,
Bash(ls:*,which:*,test:*))
- Use
Available environment variables:
${CLAUDE_PROJECT_DIR}: Absolute path to user's project root${CLAUDE_PLUGIN_ROOT}: Absolute path to plugin directory
Command invocation:
- Users type:
/namespace:command-name - Example:
/gd:setuprunscommands/setup.md
Best practices:
- Keep commands focused on one task
- Use descriptive names (verb-noun pattern)
- Delegate complex logic to scripts
- Provide clear success/failure messages
- Remind users to restart Claude Code if needed (e.g., after MCP changes)
Agents (agents/*.md)
Agents are autonomous assistants launched via the Task tool.
File format: agents/{agent-name}.md
Template:
---
description: Brief description of what this agent does and when to use it
allowed-tools:
- AskUserQuestion
- Read
- Write
- Bash(specific:commands)
---
You are a specialized agent for [specific purpose].
## Your Goal
Clearly state what the agent should accomplish.
## Process
1. Step 1: What to do first
2. Step 2: What to do next
3. Step 3: Final steps
## Guidelines
- Specific behavior instructions
- What to ask the user
- What output to produce
- How to handle errors
## Output
Define exactly what the agent should return to the calling command or user.
Frontmatter fields:
description(REQUIRED): When this agent should be usedallowed-tools(OPTIONAL): Restrict available tools
Invocation methods:
-
From commands: Use Task tool in command markdown
!task subagent_type=custom-agent-name -
Programmatically: Commands can invoke agents
Use the Task tool to launch the {agent-name} agent.
Best practices:
- Make agents conversational (use AskUserQuestion)
- Have clear, structured output
- Handle edge cases gracefully
- Return comprehensive results
Skills (skills/{skill-name}/SKILL.md)
Skills auto-activate based on context matching.
File format: skills/{skill-name}/SKILL.md (MUST be named SKILL.md)
Template:
---
name: skill-identifier
description: Detailed description of when this skill should activate. Be specific about topics, keywords, and use cases that should trigger this skill.
allowed-tools:
- mcp__service__*
- Read
- Write
- Edit
---
# Skill Name
You are an expert in [domain/technology].
## Core Knowledge
### Topic 1
- Detailed information
- Key concepts
- Common patterns
### Topic 2
- More expertise
- Best practices
## Available Tools
Document any MCP tools or special capabilities:
- `mcp__service__tool1`: What it does
- `mcp__service__tool2`: What it does
## Common Tasks
### Task 1: Description
Step-by-step approach:
1. Do this
2. Then this
3. Finally this
### Task 2: Description
Another common pattern...
## Code Examples
```language
# Provide relevant code samples
Best Practices
- Practice 1
- Practice 2
When to Use This Skill
Explicitly list scenarios:
- User asks about X
- User wants to do Y
- User mentions keywords like Z
**Frontmatter fields**:
- `name` (REQUIRED): Unique skill identifier
- `description` (REQUIRED): Claude matches this against user messages to auto-activate
- `allowed-tools` (OPTIONAL): Restrict available tools
**Activation**:
- Skills activate automatically when user messages match the description
- Be specific in descriptions to avoid false activations
- Include relevant keywords and phrases users might say
**Best practices**:
- Make descriptions specific and detailed
- Include domain knowledge and patterns
- Document available MCP tools
- Provide code examples
- Use skills for deep expertise areas
- Test activation by asking questions that should trigger it
### Hooks (`hooks/hooks.json`)
Hooks run automatically on events.
**File format**: `hooks/hooks.json`
**Template**:
```json
{
"description": "Brief description of what these hooks do",
"hooks": {
"SessionStart": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/script-name.sh",
"description": "What this hook does"
}
],
"PreToolUse": [
{
"type": "command",
"command": "echo 'Before tool use'",
"description": "Runs before each tool use"
}
]
}
}
Available hook events:
SessionStart: When Claude Code session startsSessionEnd: When session endsPreToolUse: Before any tool is usedPostToolUse: After any tool is usedUserPromptSubmit: When user submits a messageStop: When user stops ClaudeSubagentStop: When subagent is stoppedNotification: On notificationsPreCompact: Before context compaction
Hook structure:
type: Always"command"for nowcommand: Shell command to run (can use${CLAUDE_PLUGIN_ROOT})description: What the hook does
Best practices:
- Make hooks non-blocking (exit code 0 for validation)
- Keep hooks fast (avoid slow operations)
- Use for validation, setup, cleanup
- Provide helpful warnings, not errors
- Test thoroughly (hooks run automatically)
Scripts (scripts/*.sh)
Reusable bash scripts called by commands and hooks.
File format: scripts/{script-name}.sh
Template:
#!/bin/bash
#
# Description: What this script does
# Usage: script-name.sh [args]
# Returns: Exit code 0 on success, 1 on failure
set -e # Exit on error (optional, use for strict mode)
# Available environment variables:
# - CLAUDE_PROJECT_DIR: User's project root
# - CLAUDE_PLUGIN_ROOT: Plugin directory
# Script logic here
echo "Doing something..."
# Exit with appropriate code
exit 0
Best practices:
- Include shebang:
#!/bin/bash - Add header comments
- Use
set -efor strict error handling (optional) - Make scripts executable:
chmod +x script.sh - Use
${CLAUDE_PROJECT_DIR}for user's project - Use
${CLAUDE_PLUGIN_ROOT}for plugin files - Provide clear output messages
- Exit with proper codes (0 = success, 1 = failure)
Common patterns:
- Validation script:
#!/bin/bash
# Validate environment
if [ ! -f "${CLAUDE_PROJECT_DIR}/.config" ]; then
echo "Warning: Configuration not found"
exit 0 # Non-blocking warning
fi
echo "Environment OK"
exit 0
- Setup script:
#!/bin/bash
# Setup environment
echo "Setting up..."
# Detect tools
TOOL_PATH=$(which tool_name 2>/dev/null || echo "")
if [ -z "$TOOL_PATH" ]; then
echo "Error: tool_name not found"
exit 1
fi
# Create config
cat > "${CLAUDE_PROJECT_DIR}/.config" <<EOF
tool_path=$TOOL_PATH
EOF
echo "Setup complete!"
exit 0
Best Practices
General Guidelines
- Namespace everything: Use consistent namespace across all commands
- Document thoroughly: README, command descriptions, inline comments
- Test extensively: Try all commands, agents, skills in real projects
- Keep it simple: Start minimal, add complexity as needed
- Follow conventions: Use established patterns from existing plugins
- Handle errors gracefully: Provide helpful error messages
- Be idempotent: Commands should be safe to run multiple times
- Version properly: Use semantic versioning
Plugin Design Patterns
Pattern 1: Setup Command + SessionStart Hook
Many plugins need environment setup:
- Setup command (
/namespace:setup): Interactive, creates config - SessionStart hook: Validates silently, warns if misconfigured
Example flow:
- User runs
/namespace:setup→ Creates.config.json - Next session → Hook validates → Shows warning if broken
- Hook is non-blocking (exit 0) to avoid interrupting work
Pattern 2: Planning Agent + Init Command
For project initialization:
- Planning agent: Asks questions, creates plan
- Init command: Launches agent, uses plan to scaffold
Example flow:
- User runs
/namespace:init→ Launches planner agent - Agent asks questions → Creates comprehensive plan
- Command receives plan → Creates files/folders
Pattern 3: Expertise Skill + Specialized Commands
For domain expertise:
- Skill: Auto-activates on relevant questions
- Commands: Specific actions in that domain
Example flow:
- User asks "How do I...?" → Skill activates → Provides guidance
- User runs
/namespace:action→ Command performs specific task
Security Considerations
- Validate inputs: Don't trust user input in scripts
- Restrict tools: Use
allowed-toolsto limit access - Avoid secrets: Don't hardcode API keys or passwords
- Use absolute paths: Prefer
${CLAUDE_PROJECT_DIR}over relative paths - Check file operations: Verify paths before writing files
Performance Tips
- Keep hooks fast: Slow hooks delay every session
- Cache when possible: Don't re-detect on every run
- Lazy load: Only load what's needed
- Parallel operations: Use multiple tool calls when possible
- Provide feedback: Show progress for long operations
Testing and Validation
Before Publishing
- Test all commands: Run every command in various scenarios
- Test skills activation: Ask questions that should trigger skills
- Test agents: Invoke agents with different inputs
- Test hooks: Verify hooks run correctly and quickly
- Test scripts: Run scripts with various inputs
- Check documentation: Ensure README is complete and accurate
- Validate JSON: Ensure all JSON files are valid
- Validate YAML: Ensure all frontmatter is valid
- Test installation: Install plugin fresh in clean environment
- Test with real users: Get feedback on UX
Validation Checklist
- [ ] plugin.json exists and is valid
- [ ] All required fields in plugin.json are filled
- [ ] Plugin is registered in marketplace.json
- [ ] All commands have descriptions
- [ ] All agents have clear goals
- [ ] All skills have specific descriptions
- [ ] All scripts are executable (chmod +x)
- [ ] All scripts have proper shebangs
- [ ] hooks.json is valid JSON (if exists)
- [ ] README.md is complete
- [ ] All examples in README work
- [ ] No hardcoded paths (use env vars)
- [ ] Error messages are helpful
- [ ] Success messages are clear
- [ ] Tested in real project
Common Issues and Fixes
| Issue | Solution |
|---|---|
| Commands not appearing | Restart Claude Code, check YAML syntax |
| Skills not activating | Make description more specific and detailed |
| Hooks not running | Check script paths, make executable, validate JSON |
| Scripts failing | Add error handling, check permissions, use absolute paths |
| MCP tools unavailable | User needs to restart Claude Code after config changes |
Quick Reference
File Extensions
.md- Commands, agents, skills, README.json- Plugin metadata, hooks, marketplace listing.sh- Bash scripts
Required Files
plugins/{namespace}/.claude-plugin/plugin.json- Plugin metadata- At least one of: command, agent, skill, hook, or script
Optional but Recommended
plugins/{namespace}/README.md- Plugin documentationplugins/{namespace}/hooks/hooks.json- SessionStart validation hook
Environment Variables
${CLAUDE_PROJECT_DIR}- User's project root${CLAUDE_PLUGIN_ROOT}- Plugin directory
Command Format
---
description: Command description
allowed-tools:
- Tool1
- Tool2
---
Command prompt here.
Agent Format
---
description: Agent description
allowed-tools:
- Tool1
---
Agent instructions here.
Skill Format
---
name: skill-name
description: When to activate (be specific!)
allowed-tools:
- Tool1
---
Skill expertise here.
Example: Creating a Python Plugin
Let's create a Python development plugin step by step.
1. Plan
- Purpose: Python development tools
- Namespace:
py - Features: Virtual env setup, testing, linting
- Dependencies: Python, pytest, ruff
2. Create Structure
mkdir -p plugins/py/.claude-plugin
mkdir -p plugins/py/commands
mkdir -p plugins/py/skills/python-dev
mkdir -p plugins/py/hooks
mkdir -p plugins/py/scripts
3. Create plugin.json
{
"name": "py",
"version": "1.0.0",
"description": "Python development tools with /py:setup, /py:test commands and Python expertise",
"author": {
"name": "Your Name",
"email": "your@email.com"
},
"license": "MIT",
"keywords": ["python", "testing", "development"]
}
4. Add Setup Command
plugins/py/commands/setup.md:
---
description: Set up Python development environment
allowed-tools:
- Bash(python*:*,pip*:*)
- Write
---
Set up a Python virtual environment for this project:
1. Create virtual environment: `python -m venv .venv`
2. Create requirements.txt if it doesn't exist
3. Install dependencies
4. Provide activation instructions
5. Add Test Command
plugins/py/commands/test.md:
---
description: Run Python tests with pytest
allowed-tools:
- Bash(pytest:*,python:*)
---
Run the test suite:
!bash pytest -v
Analyze results and report any failures.
6. Add Python Skill
plugins/py/skills/python-dev/SKILL.md:
---
name: python-development
description: Expert Python developer knowledge including testing, package management, virtual environments, and common frameworks like FastAPI, Django, Flask
allowed-tools:
- Bash(python*:*,pip*:*)
- Read
- Write
- Edit
---
# Python Development Skill
You are an expert Python developer.
## Best Practices
- Use virtual environments
- Type hints for clarity
- Pytest for testing
- Ruff for linting
...
7. Add Validation Hook
plugins/py/hooks/hooks.json:
{
"description": "Python environment validation",
"hooks": {
"SessionStart": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate-python.sh",
"description": "Check Python environment"
}
]
}
}
8. Add Validation Script
plugins/py/scripts/validate-python.sh:
#!/bin/bash
# Validate Python environment
if [ ! -d "${CLAUDE_PROJECT_DIR}/.venv" ]; then
echo "Tip: Run /py:setup to create a virtual environment"
fi
exit 0 # Non-blocking
Make executable:
chmod +x plugins/py/scripts/validate-python.sh
9. Register in Marketplace
Edit .claude-plugin/marketplace.json:
{
"plugins": [
...existing plugins...,
{
"name": "py",
"source": "./plugins/py",
"description": "Python development tools",
"category": "development",
"tags": ["python", "testing"]
}
]
}
10. Create README
plugins/py/README.md:
# Python Development Plugin
Tools for Python development in Claude Code.
## Installation
/plugin install py@python-dev
## Commands
- /py:setup - Create virtual environment
- /py:test - Run pytest
...
11. Test
- Restart Claude Code
- Run
/py:setupin a Python project - Run
/py:test - Ask "How do I write a Python test?" (should activate skill)
Summary
To create a new plugin:
- ✅ Plan your plugin (purpose, namespace, features)
- ✅ Create directory structure in
plugins/{namespace}/ - ✅ Create
plugin.jsonwith metadata - ✅ Register in
marketplace.json - ✅ Add components (commands, agents, skills, hooks, scripts)
- ✅ Create README documentation
- ✅ Test thoroughly
- ✅ Publish to marketplace
Key principles:
- One plugin, one purpose: Keep plugins focused
- Namespace everything: Use consistent prefixes
- Document thoroughly: READMEs, descriptions, examples
- Test extensively: Real projects, real users
- Follow patterns: Learn from existing plugins
Now you're ready to create amazing Claude Code plugins! 🚀