Building Claude Code Plugins: Architecture, Best Practices, and Examples
Learn to build Claude Code plugins from scratch. Covers plugin.json structure, commands, skills, agents, hooks, and MCP integration with step-by-step examples.
Building Claude Code Plugins: Architecture, Best Practices, and Examples
Plugins are the most powerful way to extend Claude Code. They bundle commands, skills, agents, hooks, and MCP integrations into a single distributable package. This guide takes you from understanding plugin architecture to building and distributing your own.
What Is a Claude Code Plugin?
A plugin is a structured collection of Claude Code extensions packaged together. Think of it like an npm package for Claude Code—it can contain:
- Commands: Slash-triggered actions (
/commit,/review) - Skills: Passive context and knowledge
- Agents: Specialized personas for specific domains
- Hooks: Event-driven automation (PreToolUse, PostToolUse, Stop)
- MCP Servers: External tool integrations
Plugins provide a cohesive experience. Instead of installing individual skills, users get a complete toolkit.
Plugin Architecture
Directory Structure
my-plugin/
├── plugin.json # Plugin manifest (required)
├── README.md # Documentation
├── commands/ # Slash commands
│ ├── commit.md
│ ├── review.md
│ └── deploy.md
├── skills/ # Passive context
│ ├── coding-standards.md
│ └── architecture.md
├── agents/ # Specialized personas
│ ├── security-auditor.md
│ └── performance-expert.md
├── hooks/ # Event handlers
│ ├── pre-commit.md
│ └── post-deploy.md
└── mcp/ # MCP configurations
└── .mcp.json
The plugin.json Manifest
The manifest is the heart of your plugin. It declares what's included and how it should be loaded:
{
"name": "fullstack-developer",
"version": "1.0.0",
"description": "Complete toolkit for fullstack development",
"author": "Your Name",
"license": "MIT",
"repository": "https://github.com/you/fullstack-developer",
"commands": [
"commands/*.md"
],
"skills": [
"skills/*.md"
],
"agents": [
"agents/*.md"
],
"hooks": {
"PreToolUse": ["hooks/validate-bash.md"],
"PostToolUse": ["hooks/log-changes.md"],
"Stop": ["hooks/session-summary.md"]
},
"mcp": {
"servers": {
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "${DATABASE_URL}"
}
}
}
},
"config": {
"defaultBranch": "main",
"commitStyle": "conventional"
}
}
Manifest Fields Reference
| Field | Required | Type | Description |
|---|---|---|---|
name | Yes | string | Unique plugin identifier (kebab-case) |
version | Yes | string | Semantic version |
description | Yes | string | Short description |
author | No | string | Creator name |
license | No | string | License identifier |
repository | No | string | Source repository URL |
commands | No | array | Glob patterns for command files |
skills | No | array | Glob patterns for skill files |
agents | No | array | Glob patterns for agent files |
hooks | No | object | Hook event to file mappings |
mcp | No | object | MCP server configurations |
config | No | object | Plugin-specific configuration |
Building Your First Plugin
Let's build a practical plugin: a code review toolkit.
Step 1: Create the Structure
mkdir code-review-toolkit
cd code-review-toolkit
mkdir -p commands skills agents hooks
touch plugin.json README.md
Step 2: Write the Manifest
{
"name": "code-review-toolkit",
"version": "1.0.0",
"description": "Comprehensive code review tools for development teams",
"author": "Your Name",
"license": "MIT",
"commands": ["commands/*.md"],
"skills": ["skills/*.md"],
"agents": ["agents/*.md"],
"hooks": {
"PreToolUse": ["hooks/safety-check.md"]
}
}
Step 3: Create Commands
commands/review.md:
---
name: review
description: Perform a thorough code review on staged changes
---
# /review
Perform a comprehensive code review on the current changes.
## Instructions
1. Run `git diff --staged` to see what's being reviewed
2. If no staged changes, run `git diff` for unstaged changes
3. Analyze the code for:
- Security vulnerabilities
- Performance issues
- Code style violations
- Logic errors
- Missing error handling
- Test coverage gaps
## Output Format
### Summary
Brief overview of the changes and overall quality.
### Issues Found
For each issue:
- **Location**: file:line
- **Severity**: Critical | High | Medium | Low
- **Issue**: Description of the problem
- **Suggestion**: How to fix it
### Positive Notes
Highlight good practices observed.
### Action Items
Prioritized list of recommended changes.
commands/security-scan.md:
---
name: security-scan
description: Scan code for security vulnerabilities
---
# /security-scan
Scan the codebase for security vulnerabilities.
## Instructions
1. Identify files to scan (focus on: auth, api, database, user input)
2. Look for these vulnerability patterns:
- SQL injection
- XSS (Cross-Site Scripting)
- CSRF vulnerabilities
- Insecure authentication
- Hardcoded secrets
- Path traversal
- Command injection
## Output Format
### Vulnerability Report
| Severity | Location | Type | Description |
|----------|----------|------|-------------|
| Critical | file:line | Type | Details |
### Recommendations
Prioritized remediation steps.
### Secure Patterns Found
Acknowledge good security practices.
commands/pr-description.md:
---
name: pr-description
description: Generate a pull request description from branch changes
---
# /pr-description
Generate a comprehensive PR description based on the branch's changes.
## Instructions
1. Get the base branch: `git symbolic-ref refs/remotes/origin/HEAD | sed 's@^refs/remotes/origin/@@'`
2. List commits: `git log <base>..HEAD --oneline`
3. Show diff: `git diff <base>...HEAD --stat`
4. Analyze all changes to understand the purpose
## PR Template
## Summary
One-line description of what this PR accomplishes.
## Motivation
Why this change is needed.
## Changes Made
- Bullet points of specific changes
- Grouped by category
## Testing
How changes were tested.
## Screenshots
(If applicable)
## Breaking Changes
(If any)
## Checklist
- [ ] Tests added/updated
- [ ] Documentation updated
- [ ] No security vulnerabilities introduced
Step 4: Create Skills
skills/review-standards.md:
---
name: review-standards
description: Code review standards and guidelines
---
# Code Review Standards
These standards apply to all code reviews performed by this plugin.
## Severity Definitions
### Critical
- Security vulnerabilities that could be exploited
- Data loss or corruption risks
- Breaking changes without migration
- Production crashes likely
### High
- Significant bugs affecting functionality
- Performance issues causing user impact
- Missing input validation
- Incorrect error handling
### Medium
- Code that works but has clear improvements
- Minor performance optimizations
- Style inconsistencies
- Missing tests for edge cases
### Low
- Stylistic suggestions
- Documentation improvements
- Minor refactoring opportunities
- Naming convention suggestions
## Review Principles
1. **Be Constructive**: Suggest solutions, not just problems
2. **Be Specific**: Point to exact lines and provide examples
3. **Be Respectful**: Assume good intent from the author
4. **Be Thorough**: Check both the obvious and subtle issues
5. **Be Educational**: Explain why something is an issue
## What to Always Check
- [ ] Logic correctness
- [ ] Error handling
- [ ] Input validation
- [ ] Security implications
- [ ] Performance impact
- [ ] Test coverage
- [ ] Documentation updates
- [ ] Breaking changes
Step 5: Create Agents
agents/security-auditor.md:
---
name: security-auditor
description: Security-focused code reviewer
color: "#FF4444"
---
# Security Auditor Agent
You are a security expert performing a thorough security audit. Your primary focus is identifying vulnerabilities, security anti-patterns, and potential attack vectors.
## Expertise Areas
- Web application security (OWASP Top 10)
- Authentication and authorization
- Cryptography best practices
- Input validation and sanitization
- Secure coding patterns
## Behavior
1. **Be Paranoid**: Assume all input is malicious
2. **Think Like an Attacker**: How could this be exploited?
3. **Prioritize**: Critical vulnerabilities first
4. **Educate**: Explain the risk and impact
## Response Format
For each finding:
### [SEVERITY] Vulnerability Title
**Location**: `file:line`
**Description**: What the vulnerability is
**Risk**: What an attacker could do
**Remediation**: How to fix it
**Example**:
```code
// Fixed version
**agents/performance-expert.md:**
```markdown
---
name: performance-expert
description: Performance optimization specialist
color: "#44AA44"
---
# Performance Expert Agent
You are a performance optimization specialist. Your focus is identifying performance bottlenecks, inefficient patterns, and optimization opportunities.
## Expertise Areas
- Algorithm complexity analysis
- Database query optimization
- Caching strategies
- Memory management
- Network optimization
- Frontend performance (Core Web Vitals)
## Analysis Approach
1. **Measure First**: What's the actual impact?
2. **Profile Bottlenecks**: Where is time being spent?
3. **Consider Trade-offs**: Performance vs. maintainability
4. **Prioritize Impact**: Focus on high-impact optimizations
## Common Patterns to Flag
### N+1 Queries
```javascript
// Bad: N+1 queries
users.forEach(async user => {
const posts = await db.query('SELECT * FROM posts WHERE user_id = ?', [user.id]);
});
// Good: Single query with JOIN
const usersWithPosts = await db.query(`
SELECT users.*, posts.*
FROM users
LEFT JOIN posts ON users.id = posts.user_id
`);
Unnecessary Re-renders
// Bad: New object every render
<Component style={{ color: 'red' }} />
// Good: Memoized or static
const style = useMemo(() => ({ color: 'red' }), []);
<Component style={style} />
### Step 6: Create Hooks
**hooks/safety-check.md:**
```markdown
---
name: safety-check
event: PreToolUse
tools: [Bash]
---
# Safety Check Hook
Validate bash commands before execution.
## Rules
1. **Block Destructive Commands**
- `rm -rf /`
- `sudo rm -rf`
- Any command affecting system directories
2. **Warn on Risky Commands**
- `git push --force`
- `DROP TABLE`
- `DELETE FROM` without WHERE
3. **Allow Safe Commands**
- Read-only operations
- Local development commands
- Test execution
## Response
If blocked: Explain why and suggest alternatives.
If warning: Ask for confirmation.
If allowed: Proceed silently.
Step 7: Document Your Plugin
README.md:
# Code Review Toolkit
A comprehensive code review toolkit for Claude Code.
## Installation
```bash
git clone https://github.com/you/code-review-toolkit ~/.claude/plugins/code-review-toolkit
Commands
| Command | Description |
|---|---|
/review | Comprehensive code review |
/security-scan | Security vulnerability scan |
/pr-description | Generate PR description |
Agents
| Agent | Description |
|---|---|
| Security Auditor | Security-focused reviews |
| Performance Expert | Performance optimization analysis |
Configuration
Create .claude/code-review-toolkit.local.md in your project:
---
severity-threshold: medium
ignore-patterns:
- "*.test.ts"
- "*.spec.ts"
---
License
MIT
## Advanced Plugin Features
### Dynamic Configuration
Plugins can read project-specific configuration:
```markdown
---
name: review
description: Configurable code review
---
# /review
## Configuration Loading
1. Check for `.claude/code-review-toolkit.local.md`
2. Parse YAML frontmatter for settings
3. Apply configuration to review process
## Default Configuration
```yaml
severity-threshold: low # Minimum severity to report
include-patterns: # Files to include
- "src/**/*.ts"
- "src/**/*.tsx"
ignore-patterns: # Files to ignore
- "**/*.test.ts"
- "**/*.d.ts"
review-focus: # Areas to emphasize
- security
- performance
- maintainability
### Inter-Command Communication
Commands can call other commands:
```markdown
---
name: full-review
description: Complete review workflow
---
# /full-review
Run a complete review workflow.
## Instructions
1. First, execute `/security-scan`
2. Then, execute `/review`
3. If issues found, suggest `/fix-issues`
4. Generate `/pr-description` with findings included
## Output
Combine outputs from all commands into a comprehensive report.
MCP Integration
Plugins can bundle MCP servers:
{
"mcp": {
"servers": {
"sonarqube": {
"command": "npx",
"args": ["mcp-sonarqube"],
"env": {
"SONAR_URL": "${SONAR_URL}",
"SONAR_TOKEN": "${SONAR_TOKEN}"
}
}
}
}
}
Then reference in commands:
# /sonar-review
Get SonarQube analysis for the current project.
## Instructions
1. Use the `sonarqube.get_issues` MCP tool
2. Filter to current branch
3. Present findings in standard format
Event Hooks
Hooks respond to Claude Code events:
PreToolUse: Before any tool executes
---
event: PreToolUse
tools: [Bash, Write]
---
Validate the operation before execution.
PostToolUse: After tool execution
---
event: PostToolUse
tools: [Edit, Write]
---
Log file changes for audit trail.
Stop: When conversation ends
---
event: Stop
---
Generate session summary.
Distribution and Installation
GitHub Distribution
The most common method:
# Users install with:
git clone https://github.com/you/plugin-name ~/.claude/plugins/plugin-name
npm Distribution
For JavaScript-based plugins:
{
"name": "@you/claude-code-plugin",
"version": "1.0.0",
"files": ["commands", "skills", "agents", "hooks", "plugin.json"]
}
Users install with:
npm install -g @you/claude-code-plugin
Versioning
Follow semantic versioning:
- Major (1.0.0 to 2.0.0): Breaking changes to commands or behavior
- Minor (1.0.0 to 1.1.0): New commands, skills, or features
- Patch (1.0.0 to 1.0.1): Bug fixes, documentation
Update Mechanism
Include update instructions:
cd ~/.claude/plugins/plugin-name
git pull origin main
Best Practices
1. Single Responsibility
Each command should do one thing well:
# Good
/review - Code review
/security-scan - Security focus
/performance - Performance focus
# Bad
/review --security --performance --style --docs
2. Clear Documentation
Every command needs:
- Description in frontmatter
- Step-by-step instructions
- Expected output format
- Examples
3. Sensible Defaults
Work out of the box:
{
"config": {
"defaultBranch": "main",
"severityThreshold": "medium",
"includeTests": false
}
}
4. Graceful Degradation
Handle missing dependencies:
## Instructions
1. Check if `sonarqube` MCP server is available
2. If available, include SonarQube data
3. If not, proceed with local analysis only
5. Respect User Preferences
Read and respect project configuration:
## Configuration
Check for project-level overrides in:
1. `.claude/plugin-name.local.md`
2. `CLAUDE.md` plugin section
3. Fall back to plugin defaults
Testing Your Plugin
Manual Testing
# Install locally
cp -r my-plugin ~/.claude/plugins/
# Restart Claude Code
claude
# Test commands
> /review
> /security-scan
Validation Script
Create a validation script:
#!/bin/bash
# validate-plugin.sh
# Check required files
if [ ! -f "plugin.json" ]; then
echo "Error: plugin.json missing"
exit 1
fi
# Validate JSON
if ! jq empty plugin.json 2>/dev/null; then
echo "Error: Invalid plugin.json"
exit 1
fi
# Check command files exist
for cmd in commands/*.md; do
if [ ! -f "$cmd" ]; then
echo "Warning: Command file missing: $cmd"
fi
done
echo "Plugin validation passed!"
Conclusion
Plugins are the ultimate way to extend Claude Code. They bundle everything—commands, skills, agents, hooks, and MCP servers—into a cohesive, distributable package.
Start simple: create a plugin with one useful command. Then expand as you identify more needs. Before long, you'll have a toolkit that transforms how you work.
The best plugins solve real problems for real workflows. Think about your daily development tasks—what would make them faster? That's your plugin.
Want to add event-driven automation? Check out our Hooks Customization Guide for a deep dive into Claude Code hooks.