Implementation Patterns for Custom Claude Code Skills
After using Claude Code professionally for about half a year, retyping the same instructions in every prompt becomes tedious. In my case, I was typing out "the seven things I always check before a PR review" again and again until it occurred to me: this should be a skill. The Claude Code skills system packages exactly this kind of recurring workflow into slash commands like /review, /deploy, or /migrate that you can share across a team.
Prerequisites and Setup
You'll need the following to follow along.
Required tools:
- Claude Code CLI (v2.15 or later recommended)
- Node.js 18+ or Python 3.10+
- Git for version control
Recommended knowledge:
- Basic Claude Code commands (
/help,/model, etc.) - YAML frontmatter syntax
- Markdown formatting
Verify your setup with these commands:
# Check Claude Code version
claude --version
# Check for existing skills directory
ls -la .claude/skills/ 2>/dev/null || echo "No skills directory found"If the skills directory doesn't exist, create it at your project root:
mkdir -p .claude/skillsSkills Architecture Deep Dive
The Claude Code skills system evolved from the earlier "custom commands" feature (.claude/commands/*.md). Both directories are now recognized as slash commands, but the skills format supports more powerful features.
Directory Structure
Skills can live in two scopes:
# Project scope (shared with your team)
.claude/skills/
review/
SKILL.md # Skill definition (required)
templates/ # Template files (optional)
examples/ # Sample code (optional)
# User scope (personal use only)
~/.claude/skills/
my-skill/
SKILL.md
Project-scoped skills are version-controlled with Git, giving every team member access to the same workflows. User-scoped skills apply only to your personal environment.
SKILL.md Anatomy
Every skill is defined by a single SKILL.md file combining YAML frontmatter with Markdown instructions.
---
name: review # Slash command name (invoked as /review)
description: "Run code review and flag improvements"
# --- Optional fields below ---
user-invocable: true # Can users call this directly (default: true)
agent: "claude-code" # Agent type for execution
allowed-tools: # Restrict available tools
- Read
- Glob
- Grep
context: # Context injection config
- type: file
path: ".eslintrc.json"
- type: shell
command: "git diff --staged --stat"
---
# Code Review Skill
Follow these rules when reviewing code:
1. Check for security vulnerabilities
2. Flag performance issues
3. Verify coding standard compliance
...Complete Frontmatter Reference
| Field | Type | Default | Purpose |
|---|---|---|---|
| name | string | directory name | Slash command name |
| description | string | — | Skill description (used for auto-trigger matching) |
| user-invocable | boolean | true | Whether users can invoke directly |
| agent | string | "claude-code" | Execution agent type |
| allowed-tools | string[] | all | Whitelist of available tools |
| context | object[] | — | Context injection definitions |
| disable-model-invocation | boolean | false | Disable LLM calls |
Build 1: An Intelligent Code Review Skill
Our first skill analyzes staged Git changes and returns categorized feedback across security, performance, and maintainability.
Step 1: Create the Directory
mkdir -p .claude/skills/smart-reviewStep 2: Write the SKILL.md
---
name: smart-review
description: "Intelligently review staged changes. Analyzes security, performance, and maintainability."
allowed-tools:
- Read
- Glob
- Grep
- Bash
context:
- type: shell
command: "git diff --staged"
- type: shell
command: "git diff --staged --stat"
- type: file
path: ".claude/skills/smart-review/review-rules.md"
---
# Smart Code Review
You are a senior software engineer conducting code review across three dimensions.
## Review Dimensions
### 1. Security (Critical / Warning / Info)
- SQL injection, XSS, CSRF vulnerabilities
- Hardcoded secrets (API keys, passwords)
- Insufficient input validation
- Insecure cryptographic methods
### 2. Performance (Warning / Info)
- Potential N+1 queries
- Unnecessary I/O inside loops
- Memory leak patterns
- Inefficient algorithms (O(n²) or worse)
### 3. Maintainability (Warning / Info)
- Function complexity (cyclomatic complexity > 10)
- Magic numbers and strings
- Insufficient error handling
- Missing test coverage
## Output Format
Report results in this format:
Review Summary
| Category | Critical | Warning | Info | |---------|----------|---------|------| | Security | X | X | X | | Performance | — | X | X | | Maintainability | — | X | X |
🔴 Critical Issues
(File name, line number, and description for each)
🟡 Warnings
(Recommended improvements)
🔵 Info
(Optional suggestions)
📝 Overall Assessment
(Quality evaluation and recommended direction)
Always run all checks even for small diffs (under 10 lines).
Explicitly state "No issues found" when a category is clean.
Step 3: Add Supporting Rules
<!-- .claude/skills/smart-review/review-rules.md -->
# Project-Specific Review Rules
## Naming Conventions
- React components: PascalCase
- Functions and variables: camelCase
- Constants: UPPER_SNAKE_CASE
- File names: kebab-case
## Forbidden Patterns
- `any` type usage (TypeScript)
- `console.log` left in production code
- Orphaned `// TODO` comments (must have issue numbers)
## Required Patterns
- JSDoc comments on all public functions
- Explicit `try-catch` error handling
- `async/await` for all asynchronous operationsStep 4: Test It
# Stage some changes
git add -p
# Run the skill
claude /smart-reviewThe key design pattern here is the context field automatically injecting git diff --staged output when the skill runs. Users never need to manually paste diffs.
Build 2: Database Migration Generator
This skill detects schema changes and generates migration files with rollback support.
SKILL.md
---
name: gen-migration
description: "Auto-generate database migration files from schema changes"
allowed-tools:
- Read
- Write
- Glob
- Bash
context:
- type: shell
command: "ls -la migrations/ 2>/dev/null | tail -5"
- type: shell
command: "git diff --name-only HEAD | grep -E '(schema|model|entity)' || echo 'No schema changes'"
---
# Database Migration Generator
## Procedure
1. Identify changed schema files
2. Review existing migration history
3. Generate migration SQL from diffs
4. Always generate a corresponding down migration for rollback
## File Naming Convention
migrations/ YYYYMMDDHHMMSS_[descriptive_name].sql
Example: `20260320100000_add_user_preferences_table.sql`
## Template
```sql
-- Migration: [description]
-- Created: [timestamp]
-- Up Migration
BEGIN;
-- Schema changes here
COMMIT;
-- Down Migration (Rollback)
BEGIN;
-- Rollback logic here
COMMIT;
Rules
- Wrap all operations in transactions
- Use
IF EXISTSwithDROP TABLE - Set default values when adding columns (zero-downtime deploys)
- Use
CONCURRENTLYfor index creation (PostgreSQL) - Split destructive changes into two releases:
- First make the column nullable
- Drop it in the next release
### Usage
```bash
# After editing schema files
claude /gen-migration
# Expected output:
# Created migrations/20260320100000_add_user_preferences_table.sql
# Rollback SQL included
Build 3: Architecture Documentation with Explore Agent
This advanced skill uses context: fork with the Explore agent to automatically survey a codebase and generate architecture documentation.
SKILL.md
---
name: arch-doc
description: "Analyze the codebase and auto-generate architecture documentation"
agent: "explore"
context: fork
allowed-tools:
- Read
- Glob
- Grep
---
# Architecture Documentation Generator
This skill runs as an Explore agent. Analyze the codebase in read-only mode and collect the following.
## Information to Collect
### 1. Project Structure
- Directory layout and purpose of each folder
- Main entry points
- Build system configuration
### 2. Dependency Map
- External packages and their purposes
- Internal module dependencies
- Circular dependency detection
### 3. API Endpoints
- Routing definition locations
- HTTP methods and paths for each endpoint
- Authentication and authorization requirements
### 4. Data Models
- Database schemas or type definitions
- Relationships between models
- Validation rules
## Output Format
Produce a Markdown document with this structure:
```markdown
# [Project Name] Architecture Document
## Overview
(Project purpose and tech stack summary)
## Directory Structure
(Tree format with explanations of key directories)
## Core Components
(Responsibilities and relationships between components)
## API Endpoints
(Table format listing)
## Data Models
(ER-style descriptions or table format)
## Dependencies
(Key external libraries and their purposes)For large codebases, focus on the most critical modules and analyze them deeply.
### How `context: fork` Works
Setting `context: fork` routes the skill content as a task to the Explore agent. This agent is optimized for read-only tools (`Read`, `Glob`, `Grep`) and is purpose-built for codebase investigation.
| Characteristic | Standard Skill | Fork Skill |
|---|---|---|
| Execution context | Main session | Independent subagent |
| File writing | Allowed | Read-only |
| Speed | Standard | Faster (lightweight agent) |
| Best for | File generation and editing | Investigation and reporting |
## Advanced Context Injection Techniques
Context injection is one of the most powerful features in the skills system. It automatically pulls external data into the skill at invocation time, eliminating manual input.
### Dynamic Context via Shell Commands
```yaml
context:
# Current branch info
- type: shell
command: "git branch --show-current"
# Recent commit log
- type: shell
command: "git log --oneline -5"
# Test result summary
- type: shell
command: "npm test -- --reporter=dot 2>&1 | tail -5"
# Environment info (never include secrets)
- type: shell
command: "echo NODE_ENV=$NODE_ENV"
Static Context via Files
context:
# Project coding standards
- type: file
path: "docs/coding-standards.md"
# API specification
- type: file
path: "openapi.yaml"
# Team review criteria
- type: file
path: ".claude/skills/review/criteria.md"Important Caveats
Shell-based context injection comes with key constraints:
- Execution time: Commands run synchronously at skill startup. Heavy operations delay invocation
- Security: Never include commands that output secrets or credentials
- Idempotency: Commands should be read-only with no side effects
- Error handling: Failed commands inject an empty string
Testing and Debugging Skills
Manual Testing
The simplest approach is invoking the skill directly and checking its output.
# Verify the skill is recognized
claude /help
# Run with verbose output
claude --verbose /smart-reviewCreating Test Cases
For thorough testing, set up a test repository with known issues.
# Create a test directory
mkdir -p /tmp/skill-test && cd /tmp/skill-test
git init
# Create a file with intentional security issues
cat > test.js << 'EOF'
const password = "hardcoded-secret-123";
const query = `SELECT * FROM users WHERE id = ${userId}`;
console.log(password);
EOF
git add test.js
# Run the skill and verify results
claude /smart-review
# Expected: 3 Critical security issues detectedCommon Errors and Fixes
Skill not recognized:
# Verify directory structure
find .claude/skills -name "SKILL-md" -type f
# Check YAML frontmatter syntax
head -20 .claude/skills/my-skill/SKILL.mdMake sure the YAML frontmatter is properly delimited with ---. Tab characters in indentation will break parsing.
Context injection returns empty:
Run the shell command directly in your terminal to verify its output.
# Test the context command
git diff --staged --statIf the command produces no output, the injected context will also be empty.
Tools blocked by allowed-tools:
Tool names are case-sensitive. Use Read not read, Bash not bash.
Performance and Security Considerations
Performance Optimization
Guidelines for improving skill responsiveness:
- Minimize context: Only inject what the skill actually needs. Large files increase token consumption and slow responses
- Restrict allowed-tools: Excluding unnecessary tools reduces Claude's decision-making overhead
- Use fork agents: Read-only investigation tasks run faster with
context: forkand the Explore agent - Optimize shell commands: Use pipes to extract only relevant data (e.g.,
| head -20,| grep -m 5)
Security Best Practices
- Exclude secrets: Never inject
.envfiles or API keys into context - Limit permissions: For skills that perform destructive operations, use
allowed-toolsto whitelist only necessary tools - Validate input: Escape user input before passing it to shell commands
- Version control: Always track project-scoped skills in Git for change auditing
Distributing and Sharing Skills
Team Sharing
Project-scoped skills in .claude/skills/ are automatically available to anyone who clones the repository.
# Make sure skills aren't gitignored
grep -r "\.claude" .gitignore
# Commit your skills
git add .claude/skills/
git commit -m "Add smart-review skill for team code reviews"Publishing to the Skills Marketplace
Claude Code supports a skills marketplace for sharing skills with the broader community.
# Package the skill (create a .skill file)
cd .claude/skills/smart-review
zip -r smart-review.skill SKILL.md review-rules.mdWhen publishing, keep these tips in mind:
- Write a clear
descriptionfield for search discoverability - Include a
README.mdexplaining usage and examples - Document prerequisites (tools, languages, frameworks)
Looking back and Next Steps
This guide covered the full lifecycle of custom Claude Code skill development — from understanding the architecture to building three production-ready skills, testing them, and sharing them with your team or the community.
The key principle: skills are instructions, not conversations. Use imperative language, define explicit output formats, and scope each skill to a single focused workflow.
For more advanced topics, check out these related articles:
- [Automate Your Workflow with Claude Code Hooks]((/articles/claude-code/claude-code-hooks-automation) — Trigger skills automatically on Git commits and file saves
- [Advanced Multi-Agent Patterns in Claude Code]((/articles/claude-code/claude-code-multi-agent-advanced) — Combining agent teams with subagents
- [Claude Code Worktree Complete Guide]((/articles/claude-code/worktree) — Parallel development patterns with skills