
Claude Ecosystem
- 32 installs
- 14 repo stars
- Updated July 28, 2026
- samhvw8/dotfiles
Helps with ai & agent building tasks.
About
claude-ecosystem is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- claude-ecosystem
- AI & Agent Building
- AI-coding skill
Claude Ecosystem by the numbers
- 32 all-time installs (skills.sh)
- +1 installs in the week ending Jul 26, 2026 (Skillselion tracking)
- Ranked #9,000 of 16,556 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Jul 29, 2026 (Skillselion catalog sync)
npx skills add https://github.com/samhvw8/dotfiles --skill claude-ecosystemAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 32 |
|---|---|
| repo stars | ★ 14 |
| Last updated | July 28, 2026 |
| Repository | samhvw8/dotfiles ↗ |
What it does
Helps with ai & agent building tasks.
Files
Claude Ecosystem
Comprehensive guide for Claude Code CLI tool, extensibility (agents/skills/output styles), and CLAUDE.md architecture.
Module Selection
| Need | Module | Reference |
|---|---|---|
| Setup/Configuration | CLI | references/getting-started.md, references/configuration.md |
| Slash Commands | CLI | references/slash-commands.md |
| MCP Servers | CLI | references/mcp-integration.md |
| Hooks & Plugins | CLI | references/hooks-and-plugins.md |
| Create Agents | Extensibility | references/agent-development.md |
| Create/Refine Skills | Extensibility | references/skill-creation-workflow.md, references/skill-writing-guide.md, references/skill-description-guide.md |
| Output Styles | Extensibility | references/skill-development.md |
| Init CLAUDE.md | Architecture | references/initialization-workflow.md |
| Optimize CLAUDE.md | Architecture | references/optimization-patterns.md |
| Enterprise/CI-CD | CLI | references/enterprise-features.md, references/cicd-integration.md |
| Troubleshooting | CLI | references/troubleshooting.md |
---
Quick Reference
Extension Types
| Type | Invocation | Purpose | Location |
|---|---|---|---|
| Agents | Task tool | Specialized sub-processes | .claude/agents/ |
| Skills | Model-invoked | Domain knowledge | .claude/skills/{name}/ |
| Output Styles | /output-style | Modify main agent | .claude/output-styles/ |
Model Selection (Agents)
| Model | Use When | Target Time |
|---|---|---|
haiku | Fast tasks, exploration | < 3s |
sonnet | Balanced, most use cases | < 10s |
opus | Complex reasoning | < 30s |
CLAUDE.md Token Budget
| Complexity | Target Tokens |
|---|---|
| Simple | 100-200 |
| Medium | 200-400 |
| Complex | 400-800 |
| Maximum | 1000 |
---
Extensibility Principles
Core Truths
| Truth | Meaning |
|---|---|
| Expertise Transfer | Make Claude think like expert, not follow steps |
| Flow, Not Friction | Produce output, not intermediate work |
| Voice Matches Domain | Sound like practitioner, not documentation |
| Focused Beats Comprehensive | Constrain ruthlessly |
Decision Heuristics
| Rule | Guidance |
|---|---|
| 3-File Rule | 3+ files → agent. Enhances YOUR work → skill. |
| Delegation Test | Runs independently? Agent. Guides you? Skill. |
| Activation Breadth | Trigger on 80% of relevant requests |
| Tool Constraint | Start with 2-3 essential tools |
Activation Keywords
The description field is your activation gate. Include: 1. Task verbs: create, build, debug, fix, deploy 2. Problem descriptions: slow, broken, failing 3. Artifact types: component, API, database 4. Casual synonyms: "make it faster" → optimize
---
Common Workflows
Create Agent
For the agent's prompt content (soul, tensions, mental models, thinking approaches), invoke Skill("prompt-architect") — it handles expertise transfer and dialectic design. This skill handles structure and frontmatter.
---
name: agent-name
description: "Use when [use case]. PROACTIVELY for [triggers].\n\nExamples:\n<example>\nContext: [situation]\nuser: [request]\nassistant: [response]\n</example>"
tools: Grep, Glob, Read, Bash
model: haiku
---
# Agent Name
Mission statement.
## Strategy
[Approach]
## Does NOT Do
- [boundary] (use X instead)Create Skill
Each skill is a context engineering problem: what information does Claude need, when should it load, and how much freedom should the instructions leave?
For body content (soul, tensions, mental models, anti-patterns), invoke Skill("prompt-architect") — it handles expertise transfer and dialectic design.
Key Principles
1. Claude is smart — only add what Claude doesn't already know 2. Explain WHY — reasoning beats commands; reframe ALWAYS/NEVER as consequences 3. Be pushy in descriptions — Claude undertriggers by default; use directive language ("ALWAYS invoke") 4. Match freedom to fragility — exact scripts for dangerous ops, principles for judgment tasks 5. Generalize from examples — skills run millions of times; don't overfit
Architecture
skill-name/
├── SKILL.md # Required: YAML frontmatter + instructions (<500 lines)
├── scripts/ # Optional: deterministic operations (execute without loading)
├── references/ # Optional: domain docs loaded as needed
└── assets/ # Optional: templates, fonts, icons for outputCreation Workflow
1. Capture Intent — mine conversation for workflow, tools, corrections before asking questions 2. Research Domain — best practices, failure modes, decision heuristics, similar skills 3. Draft SKILL.md — quick orientation → core workflow → patterns → edge cases → reference routing → frontmatter (LAST) 4. Review — token audit, freedom calibration, generalization, trigger check, "Rationalizations to Reject", "When NOT to Use" 5. Test Cases — 2-3 realistic messy prompts as users actually type 6. Iterate — generalize from feedback, keep lean, reframe don't restrict
Detailed workflow: references/skill-creation-workflow.md Writing principles: references/skill-writing-guide.md Description optimization: references/skill-description-guide.md
Deliverables
1. Complete SKILL.md with frontmatter and body 2. Directory structure with any bundled scripts/references/assets 3. 2-3 test prompts — realistic, messy, user-style 4. Description rationale — brief triggering strategy explanation
Initialize CLAUDE.md
1. Analyze codebase (language, framework, structure) 2. Extract code style, commands, patterns 3. Generate with template, customize 4. Validate commands, check token count 5. Target <400 lines, prefer <250
Detailed: references/initialization-workflow.md
Optimize CLAUDE.md
1. Evaluate token efficiency 2. Find redundancy, outdated info 3. Apply token reduction techniques 4. Target 40%+ reduction 5. Verify critical info retained
Detailed: references/optimization-patterns.md
---
Anti-Patterns
| Pattern | Problem | Fix |
|---|---|---|
| Kitchen Sink Agent | 10+ tools, handles "everything" | Constrain to 3-5 tools |
| Echo Skill | Restates docs without insight | Add expert layer |
| Invisible Trigger | Description uses only formal terms | Include user language |
| Procedure Manual | Step 1, 2, 3... | Teach patterns, not steps |
| Over-Documentation | CLAUDE.md > 400 lines | Document project-specific only |
---
Quality Signals
Good Signs
- Frontmatter reads like "when to use" guide
- First 10 lines provide actionable guidance
- Expert would nod "yes, that's how I think"
- Explicit constraints on what it does NOT handle
Warning Signs
- >50% reference tables or field definitions
- No mention of "when NOT to use"
- Generic language for any domain
- Body exceeds 600 lines
---
References
CLI Tool
references/getting-started.md- Installation, setup, authreferences/slash-commands.md- Complete command catalogreferences/mcp-integration.md- MCP server configurationreferences/hooks-and-plugins.md- Hook types, plugin structurereferences/configuration.md- Settings hierarchyreferences/enterprise-features.md- IAM, SSO, sandboxingreferences/cicd-integration.md- GitHub Actions, GitLab CIreferences/ide-integration.md- VS Code, JetBrainsreferences/advanced-features.md- Extended thinking, cachingreferences/troubleshooting.md- Common issuesreferences/api-reference.md- Admin, Messages, Skills APIsreferences/best-practices.md- Project organization, securityreferences/agent-skills.md- Creating skills via CLI
Extensibility
references/agent-development.md- Full YAML structure, system promptsreferences/skill-development.md- Structure, triggers, hooksreferences/skill-creation-workflow.md- End-to-end skill creation processreferences/skill-writing-guide.md- Writing principles and mental modelsreferences/skill-description-guide.md- Description optimization and triggers
CLAUDE.md
references/initialization-workflow.md- Creating new CLAUDE.mdreferences/optimization-patterns.md- Token reduction techniquesreferences/integration-strategies.md- Global config, MCP toolsreferences/output-templates.md- Standard output formats
---
Skill Routing
| Task | Where | What it handles |
|---|---|---|
| Skill/agent prompt content (soul, tensions, mental models, anti-patterns) | Skill("prompt-architect") | Content quality, dialectic design, freedom calibration |
| Skill structure (frontmatter, directory, progressive disclosure, description) | This skill | Architecture, triggering strategy, token budgeting |
| CLAUDE.md creation/optimization | This skill | Initialization workflow, token reduction |
When creating or editing skills/agents: this skill for structure → prompt-architect for body content.
---
Documentation:
- llms.txt: https://context7.com/websites/claude_en_claude-code/llms.txt?tokens=10000
- Main docs: https://docs.claude.com/en/docs/claude-code/
- GitHub: https://github.com/anthropics/claude-code
Advanced Features
Extended thinking, prompt caching, checkpointing, and memory management in Claude Code.
Extended Thinking
Deep reasoning for complex problems.
Enable Extended Thinking
Global configuration:
claude config set thinking.enabled true
claude config set thinking.budget 15000Project settings (.claude/settings.json):
{
"thinking": {
"enabled": true,
"budget": 10000,
"mode": "auto"
}
}Command-line flag:
claude --thinking "architect microservices system"Thinking Modes
auto: Claude decides when to use extended thinking manual: User explicitly requests thinking disabled: No extended thinking
{
"thinking": {
"mode": "auto",
"budget": 10000,
"minComplexity": 0.7
}
}Budget Control
Set token budget for thinking:
{
"thinking": {
"budget": 10000, // Max tokens for thinking
"budgetPerRequest": 5000, // Per-request limit
"adaptive": true // Adjust based on task complexity
}
}Best Use Cases
- Architecture design
- Complex algorithm development
- System refactoring
- Performance optimization
- Security analysis
- Bug investigation
Example
claude --thinking "Design a distributed caching system with:
- High availability
- Consistency guarantees
- Horizontal scalability
- Fault tolerance"Prompt Caching
Reduce costs by caching repeated context.
Enable Caching
API usage:
const response = await client.messages.create({
model: 'claude-sonnet-4-5-20250929',
system: [
{
type: 'text',
text: 'You are a coding assistant...',
cache_control: { type: 'ephemeral' }
}
],
messages: [...]
});CLI configuration:
{
"caching": {
"enabled": true,
"ttl": 300,
"maxSize": "100MB"
}
}Cache Strategy
What to cache:
- Large codebases
- Documentation
- API specifications
- System prompts
- Project context
What not to cache:
- User queries
- Dynamic content
- Temporary data
- Session-specific info
Cache Control
// Cache large context
{
type: 'text',
text: largeCodebase,
cache_control: { type: 'ephemeral' }
}
// Update without invalidating cache
{
type: 'text',
text: newUserQuery
// No cache_control = not cached
}Cost Savings
With caching:
- First request: Full cost
- Subsequent requests: ~90% discount on cached tokens
- Cache TTL: 5 minutes
Example:
Without caching:
Request 1: 10,000 tokens @ $3/M = $0.03
Request 2: 10,000 tokens @ $3/M = $0.03
Total: $0.06
With caching (8,000 tokens cached):
Request 1: 10,000 tokens @ $3/M = $0.03
Request 2: 2,000 new + 8,000 cached @ $0.30/M = $0.0024
Total: $0.0324 (46% savings)Checkpointing
Automatically track and rewind changes.
Enable Checkpointing
claude config set checkpointing.enabled trueSettings:
{
"checkpointing": {
"enabled": true,
"autoSave": true,
"interval": 300,
"maxCheckpoints": 50
}
}View Checkpoints
# List checkpoints
claude checkpoint list
# View checkpoint details
claude checkpoint show checkpoint-123Restore Checkpoint
# Restore to checkpoint
claude checkpoint restore checkpoint-123
# Restore to time
claude checkpoint restore --time "2025-11-06T10:00:00Z"
# Restore specific files
claude checkpoint restore checkpoint-123 --files src/main.jsCreate Manual Checkpoint
# Create checkpoint with message
claude checkpoint create "before refactoring auth module"
# Create at important moments
claude checkpoint create "working state before experiment"Checkpoint Strategies
Auto-save checkpoints:
- Before major changes
- After successful tests
- Every N minutes
- Before destructive operations
Manual checkpoints:
- Before risky refactors
- At working states
- Before experiments
- After milestones
Example Workflow
# Create checkpoint before risky change
claude checkpoint create "before performance optimization"
# Make changes
claude "optimize database queries for 10x performance"
# If something breaks
claude checkpoint restore "before performance optimization"
# Or continue with improvements
claude checkpoint create "performance optimization complete"Memory Management
Control how Claude remembers context across sessions.
Memory Locations
global: Share memory across all projects project: Project-specific memory none: Disable memory
# Set memory location
claude config set memory.location project
# Enable memory
claude config set memory.enabled trueConfiguration
{
"memory": {
"enabled": true,
"location": "project",
"ttl": 86400,
"maxSize": "10MB",
"autoSummarize": true
}
}Memory Operations
# View stored memories
claude memory list
# View specific memory
claude memory show memory-123
# Clear all memories
claude memory clear
# Clear old memories
claude memory clear --older-than 7d
# Clear project memories
claude memory clear --projectWhat Gets Remembered
Automatically:
- Project structure
- Coding patterns
- Preferences
- Common commands
- File locations
Explicitly stored:
- Important context
- Design decisions
- Architecture notes
- Team conventions
Memory Best Practices
Project memory:
- Good for project-specific context
- Shares across team members
- Persists in
.claude/memory/ - Commit to version control (optional)
Global memory:
- Personal preferences
- General knowledge
- Common patterns
- Cross-project learnings
Disable memory when:
- Working with sensitive data
- One-off tasks
- Testing/experimentation
- Troubleshooting
Example
# Remember project architecture
claude "Remember: This project uses Clean Architecture with:
- Domain layer (core business logic)
- Application layer (use cases)
- Infrastructure layer (external dependencies)
- Presentation layer (API/UI)"
# Claude will recall this in future sessions
claude "Add a new user registration feature"
# Claude: "I'll implement this following the Clean Architecture..."Context Windows
Manage large context effectively.
Maximum Context
Model context limits:
- Claude Sonnet: 200k tokens
- Claude Opus: 200k tokens
- Claude Haiku: 200k tokens
Context Management
{
"context": {
"maxTokens": 200000,
"autoTruncate": true,
"prioritize": ["recent", "relevant"],
"summarizeLong": true
}
}Strategies
Summarization:
- Auto-summarize old context
- Keep summaries of large files
- Compress conversation history
Prioritization:
- Recent messages first
- Most relevant files
- Explicit user priorities
Chunking:
- Process large codebases in chunks
- Incremental analysis
- Parallel processing
See Also
- Pricing: https://docs.claude.com/about-claude/pricing
- Token counting: https://docs.claude.com/build-with-claude/token-counting
- Best practices:
references/best-practices.md - Configuration:
references/configuration.md
Agent Development Guide
Table of Contents
1. YAML Frontmatter Structure 2. Configuration Fields 3. Model Selection Guide 4. Tool Selection Strategy 5. System Prompt Design 6. Built-in Subagents 7. Advanced Features 8. Agent Patterns 9. Optimization Checklist
YAML Frontmatter Structure
---
name: your-sub-agent-name
description: Description of when this subagent should be invoked. Use PROACTIVELY for [triggers].\n\nExamples:\n<example>\nContext: [situation]\nuser: [request]\nassistant: [response]\n<commentary>[reasoning]</commentary>\n</example>
tools: tool1, tool2, tool3
model: sonnet
permissionMode: default
skills: skill1, skill2
---
Your subagent's system prompt goes here. This can be multiple paragraphs
and should clearly define the subagent's role, capabilities, and approach.Configuration Fields
| Field | Required | Description |
|---|---|---|
name | Yes | Unique identifier using lowercase letters and hyphens |
description | Yes | Natural language description; single line with \n for newlines |
tools | No | Comma-separated list; inherits all tools if omitted |
model | No | Model alias (sonnet, opus, haiku) or inherit |
permissionMode | No | Permission handling mode |
skills | No | Comma-separated list of skill names to auto-load |
name
- Lowercase with hyphens only
- Descriptive and unique
- Examples:
codebase-explorer,code-reviewer,debugger
description
- MUST be a single line - use
\nfor newlines (no quotes needed in YAML) - Start with "Use this agent when..." followed by use cases
- Include "Use PROACTIVELY" for automatic delegation
- Include 2-3 inline
<example>blocks - Format:
<example>\nContext: ...\nuser: ...\nassistant: ...\n<commentary>...</commentary>\n</example> - Max ~300 words (examples add value)
- Do NOT use YAML multiline syntax (
>-,|,>)
tools
- Comma-separated list of allowed tools
- Omit to inherit all tools from main agent
- Common:
Grep, Glob, Read, Bash, Write, Edit - Principle of least privilege: Only grant necessary tools
model
haiku: Fast, cost-efficient (exploration, search)sonnet: Balanced (most use cases, default)opus: Complex reasoning (architecture, analysis)inherit: Match main conversation model
permissionMode
| Mode | Behavior |
|---|---|
default | Standard permission handling |
acceptEdits | Auto-accept file edits |
bypassPermissions | Skip all permission checks |
plan | Research-only, read-only mode |
ignore | Ignore permission mode entirely |
skills
- Comma-separated skill names to auto-load
- Skills activated when agent starts
- Example:
skills: pdf-processing, data-analysis
Model Selection Guide
Choose Haiku when:
- Fast response required (< 3 seconds target)
- Simple, well-defined tasks
- Search and discovery operations
- Cost sensitivity critical
Choose Sonnet when:
- Balanced performance needed
- Moderate complexity
- Most general-purpose tasks
- Default choice
Choose Opus when:
- Complex reasoning required
- Architectural decisions
- Multi-step analysis
- Security audits
Choose Inherit when:
- Agent should match main conversation capabilities
- Consistency with user's model choice
Tool Selection Strategy
Read-only Exploration
Grep, Glob, Read, BashUse for: Codebase analysis, file discovery, pattern matching
Analysis without Search
Read, BashUse for: Code review, metrics collection, static analysis
Code Modifications
Write, Edit, BashUse for: Feature implementation, refactoring, file creation
Comprehensive
(omit tools field to inherit all)Use for: Complex workflows, multi-phase operations
Principle: Start minimal, expand if needed.
System Prompt Design
Voice Guidelines
✅ Use: Imperative, infinitive, active voice ✅ Examples: "Find files...", "Analyze code...", "Execute searches..."
❌ Avoid: Second person, passive voice, filler words ❌ Examples: "You should find...", "Files can be found...", "Simply search..."
XML Tag Usage
Use XML tags for:
<principles>- Core design philosophy<exploration_patterns>- Grouped techniques<format>- Output structure<error_handling>- Recovery strategies<constraints>- Limitations and targets
Keep in natural language:
- Main mission statement
- High-level strategy
- Phase/step descriptions
Prompt Optimization
Progressive Disclosure:
- Main agent file (<500 lines): Core strategy and common patterns
- Reference files: Comprehensive examples, language-specific patterns
Compression Strategies:
- Use code blocks instead of prose
- Consolidate repetitive examples
- Abbreviate patterns
Built-in Subagents
General-Purpose Subagent
- Model: Sonnet
- Tools: All tools
- Purpose: Complex research tasks, multi-step operations, code modifications
- Use when: Task requires both exploration and modification
Plan Subagent
- Model: Sonnet
- Tools: Read, Glob, Grep, Bash
- Purpose: Research and gather information in plan mode
- Automatic use: When in plan mode and codebase research needed
Explore Subagent
- Model: Haiku (fast, low-latency)
- Mode: Strictly read-only
- Tools: Glob, Grep, Read, Bash (read-only commands only)
- Thoroughness levels:
quick,medium,very thorough - Use when: Need to search/understand codebase without changes
Advanced Features
Resumable Subagents
Continue previous agent conversations with stored context:
- Each execution gets unique
agentId - Transcript stored in
agent-{agentId}.jsonl - Resume with previous
agentIdto continue with full context
Task(
subagent_type="code-reviewer",
description="Continue review",
prompt="Continue from previous context...",
resume="agent-abc123" # Previous agentId
)CLI-Defined Agents
Define agents at runtime via command line:
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer...",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
}
}'Chaining Subagents
> First use the code-analyzer subagent to find performance issues,
then use the optimizer subagent to fix themDynamic Selection
Claude intelligently selects agents based on:
- Task description matching
- Description field specificity
- Context relevance
Agent Patterns
Pattern Format (When Writing Patterns)
Use this structure for expert patterns in agent prompts:
### [Pattern Name]
**When you see:** [Observable trigger - what catches expert attention]
**This indicates:** [Insight - what expert knows when they see this]
**Therefore:** [Action - what expert does]
**Watch out for:** [Pitfall - common mistake when handling this]File Discovery Agent
---
name: file-finder
description: Locate files across codebase using name patterns, code structures, or feature relationships. Use PROACTIVELY when searching for files.
tools: Grep, Glob, Read, Bash
model: haiku
---Code Review Agent
---
name: code-reviewer
description: Expert code review for quality, security, and maintainability. Use PROACTIVELY after writing or modifying code.\n\nExamples:\n<example>\nContext: User finished implementing auth endpoint\nuser: "I've implemented the auth endpoint"\nassistant: "I'll review the implementation for security and quality"\n<commentary>Proactive review after code changes</commentary>\n</example>
tools: Read, Grep, Glob, Bash
model: sonnet
---Architecture Analyst
---
name: architecture-analyst
description: Analyze system architecture, evaluate design patterns, and understand complex codebases. Use for architectural decisions.
tools: Grep, Glob, Read, Bash
model: opus
---Debugger Agent
---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use PROACTIVELY when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
model: sonnet
---Agent Locations
| Location | Scope | Priority |
|---|---|---|
.claude/agents/ | Project | Highest |
~/.claude/agents/ | User (all projects) | Lower |
Plugin agents/ | Plugin-specific | Varies |
--agents CLI flag | Session only | Medium |
Invocation Methods
Automatic Delegation
User: "Find all authentication files"
→ Claude invokes file-finder automatically based on description matchExplicit Invocation
User: "Use the code-reviewer agent to check my changes"
→ Claude invokes code-reviewer explicitlyProgrammatic
Task(
subagent_type="codebase-explorer",
description="Find payment processing files",
prompt="Search for payment, transaction, checkout patterns",
model="haiku"
)Optimization Checklist
- [ ] Reduce to <800 lines (move details to references)
- [ ] Remove second-person voice
- [ ] Add XML tags for structure
- [ ] Consolidate repetitive examples
- [ ] Use code blocks over prose
- [ ] Include "PROACTIVELY" in description
- [ ] Provide executable examples
- [ ] Add clear response format
- [ ] Include error recovery
- [ ] Specify performance targets
- [ ] Test with real scenarios
- [ ] Limit tools to necessary set
Success Criteria
Well-designed agent has: 1. Clear, focused mission (single responsibility) 2. Appropriate model selection (cost/performance balance) 3. Minimal tool set (least privilege) 4. Concise prompt (<800 lines or references) 5. Executable examples (tested and working) 6. Clear response format 7. Error recovery strategies 8. Performance targets specified 9. "PROACTIVELY" trigger in description
Performance Targets
| Model | Response Time | Token Usage |
|---|---|---|
| Haiku | < 3 seconds | < 1000 tokens |
| Sonnet | < 10 seconds | < 5000 tokens |
| Opus | < 30 seconds | < 10000 tokens |
Agent Skills
Create, manage, and share Skills to extend Claude's capabilities in Claude Code.
What Are Agent Skills?
Agent Skills are modular capabilities that extend Claude's functionality. Each Skill packages:
- Instructions and procedural knowledge
- Metadata (name, description)
- Optional resources (scripts, templates, references)
Skills are automatically discovered and used by Claude when relevant to the task using progressive disclosure principle.
Skill Structure
Basic Structure
.claude/skills/
└── my-skill/
└── SKILL.md # Uppercase filename, Metadata, instructions (required)With Resources
.claude/skills/
└── my-skill/
├── SKILL.md # Uppercase filename, Metadata, instructions (required)
├── scripts/ # Executable code
├── references/ # Documentation
└── assets/ # Templates, imagesCreating Skills
SKILL.md
Metadata and configuration:
Metadata's fields:
name: Unique identifier (kebab-case)description: When Claude should activate this skillversion: Semantic versionauthor: Creator name or org
Main instructions for Claude:
---
name: my-skill
description: Brief description of when to use this skill
version: 1.0.0
---
# Skill Name
Description of what this skill does.
## When to Use This Skill
Specific scenarios when Claude should activate this skill.
## Instructions
Step-by-step instructions for Claude to follow.
## Examples
Concrete examples of skill usage.Best Practices
Clear Activation Criteria
Define exactly when the skill should be used:
Good:
Use when creating React components with TypeScript and Tailwind CSS.Bad:
Use for frontend development.Concise Instructions
Focus on essential information, avoid duplication:
Good:
1. Create component file in src/components/
2. Use TypeScript interfaces for props
3. Apply Tailwind classes for stylingBad:
First you need to think about creating a component,
then maybe you should consider...Actionable Guidance
Provide clear steps Claude can follow:
Good:
Run `npm test` to validate implementation.Bad:
You might want to test things.Include Examples
Show concrete input/output examples:
## Examples
Input: "Create button component"
Output: Creates src/components/Button.tsx with props interfaceScope Limitation
Keep skills focused on specific domains:
Good:
api-testing- Testing REST APIsdb-migrations- Database schema changes
Bad:
general-development- Everything
Resource Types
Scripts (scripts/)
Executable code for deterministic tasks:
scripts/
├── format-code.py
├── generate-types.js
└── run-tests.shWhen to use:
- Repeated code generation
- Deterministic transformations
- External tool integrations
References (references/)
Documentation loaded into context as needed:
references/
├── api-docs.md
├── schemas.md
└── workflows.mdWhen to use:
- API documentation
- Database schemas
- Domain knowledge
- Detailed workflows
Assets (assets/)
Files used in output:
assets/
├── templates/
│ └── component-template.tsx
├── icons/
└── configs/When to use:
- Templates
- Boilerplate code
- Images, icons
- Configuration files
Using Skills via API
TypeScript Example
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY
});
const response = await client.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 4096,
skills: [
{
type: 'custom',
custom: {
name: 'document-creator',
description: 'Creates professional documents',
instructions: 'Follow corporate style guide...'
}
}
],
messages: [{
role: 'user',
content: 'Create a project proposal'
}]
});Python Example
from anthropic import Anthropic
client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
response = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
skills=[
{
"type": "custom",
"custom": {
"name": "code-reviewer",
"description": "Reviews code for quality and security",
"instructions": "Check for common issues..."
}
}
],
messages=[{
"role": "user",
"content": "Review this code"
}]
)Skill Discovery
Claude automatically discovers skills:
1. Global skills: ~/.claude/skills/ 2. Project skills: .claude/skills/ 3. Plugin skills: From installed plugins
Skills are activated when:
- Task matches skill description
- User explicitly invokes skill
- Context suggests skill is relevant
Managing Skills
List Skills
claude skills listTest Skill
claude --skill my-skill "test task"Share Skill
# Package skill
cd .claude/skills/my-skill
tar -czf my-skill.tar.gz .
# Or create plugin
# See references/hooks-and-plugins.mdInstall Skill
# Manual installation
cd .claude/skills/
tar -xzf my-skill.tar.gzExample Skills
API Testing Skill
SKILL.md:
---
name: api-testing
description: Test REST APIs with automated requests
version: 1.0.0
---
# API Testing
Test REST APIs with comprehensive validation.
## When to Use
Use when testing API endpoints, validating responses, or
creating API test suites.
## Instructions
1. Read API documentation from references/api-docs.md
2. Use scripts/test-api.py for making requests
3. Validate response status, headers, body
4. Generate test report
## Examples
Request: "Test the /users endpoint"
Actions:
- Read references/api-docs.md for endpoint spec
- Run scripts/test-api.py --endpoint /users
- Validate response matches schema
- Report resultsDatabase Migration Skill
SKILL.md:
---
name: db-migrations
description: Create and manage database migrations
version: 1.0.0
---
# Database Migrations
Create safe, reversible database schema changes.
## When to Use
Use when modifying database schema, adding tables,
or changing column definitions.
## Instructions
1. Review current schema in references/schema.md
2. Create migration file in migrations/
3. Include both up and down migrations
4. Test migration on development database
5. Update references/schema.md
## Migration Template
See assets/migration-template.sql for standard format.Progressive Disclosure
Keep SKILL.md concise (<100 lines) by:
1. Core instructions in SKILL.md 2. Detailed docs in references/ 3. Executable code in scripts/ 4. Templates in assets/
Example structure:
# My Skill
Brief overview.
## When to Use
Clear activation criteria.
## Instructions
High-level steps that reference:
- references/detailed-workflow.md
- scripts/automation.py
- assets/template.tsxTroubleshooting
Skill Not Activating
- Check description specificity
- Ensure
SKILL.mdhas clear activation criteria
Resource Not Found
- Verify file paths in
SKILL.md - Check directory structure
- Use relative paths from skill root
Conflicting Skills
- Make descriptions more specific
- Use unique names
- Scope skills narrowly
See Also
- Skill creation guide: https://docs.claude.com/claude-code/skills
- Best practices: https://docs.claude.com/agents-and-tools/agent-skills/best-practices
- API usage:
references/api-reference.md - Plugin system:
references/hooks-and-plugins.md
API Reference
API endpoints and programmatic access to Claude Code functionality.
Admin API
Usage Reports
Get Claude Code Usage Report:
GET /v1/admin/claude-code/usageQuery parameters:
start_date: Start date (YYYY-MM-DD)end_date: End date (YYYY-MM-DD)user_id: Filter by userworkspace_id: Filter by workspace
Response:
{
"usage": [
{
"date": "2025-11-06",
"user_id": "user-123",
"requests": 150,
"tokens": 45000,
"cost": 12.50
}
]
}Example:
curl https://api.anthropic.com/v1/admin/claude-code/usage \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d start_date=2025-11-01 \
-d end_date=2025-11-06Cost Reports
Get Cost Report:
GET /v1/admin/usage/costQuery parameters:
start_date: Start dateend_date: End dategroup_by:user|project|model
Response:
{
"costs": [
{
"group": "user-123",
"input_tokens": 100000,
"output_tokens": 50000,
"cost": 25.00
}
],
"total": 250.00
}User Management
List Users:
GET /v1/admin/usersGet User:
GET /v1/admin/users/{user_id}Update User:
PATCH /v1/admin/users/{user_id}Remove User:
DELETE /v1/admin/users/{user_id}Messages API
Create Message
Endpoint:
POST /v1/messagesRequest:
{
"model": "claude-sonnet-4-5-20250929",
"max_tokens": 4096,
"messages": [
{
"role": "user",
"content": "Explain this code"
}
]
}With Skills:
{
"model": "claude-sonnet-4-5-20250929",
"max_tokens": 4096,
"skills": [
{
"type": "custom",
"custom": {
"name": "code-reviewer",
"description": "Reviews code quality",
"instructions": "Check for bugs, security issues..."
}
}
],
"messages": [...]
}Response:
{
"id": "msg_123",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "This code implements..."
}
],
"usage": {
"input_tokens": 100,
"output_tokens": 200
}
}Stream Messages
Streaming response:
{
"model": "claude-sonnet-4-5-20250929",
"max_tokens": 4096,
"stream": true,
"messages": [...]
}Server-sent events:
event: message_start
data: {"type":"message_start","message":{...}}
event: content_block_delta
data: {"type":"content_block_delta","delta":{"text":"Hello"}}
event: message_stop
data: {"type":"message_stop"}Count Tokens
Endpoint:
POST /v1/messages/count_tokensRequest:
{
"model": "claude-sonnet-4-5-20250929",
"messages": [
{
"role": "user",
"content": "Count these tokens"
}
]
}Response:
{
"input_tokens": 15
}Files API
Upload File
Endpoint:
POST /v1/filesRequest (multipart/form-data):
curl https://api.anthropic.com/v1/files \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-F file=@document.pdf \
-F purpose=user_uploadResponse:
{
"id": "file-123",
"object": "file",
"bytes": 12345,
"created_at": 1699564800,
"filename": "document.pdf",
"purpose": "user_upload"
}List Files
Endpoint:
GET /v1/filesResponse:
{
"data": [
{
"id": "file-123",
"filename": "document.pdf",
"bytes": 12345
}
]
}Download File
Endpoint:
GET /v1/files/{file_id}/contentDelete File
Endpoint:
DELETE /v1/files/{file_id}Models API
List Models
Endpoint:
GET /v1/modelsResponse:
{
"data": [
{
"id": "claude-sonnet-4-5-20250929",
"type": "model",
"display_name": "Claude Sonnet 4.5"
}
]
}Get Model
Endpoint:
GET /v1/models/{model_id}Response:
{
"id": "claude-sonnet-4-5-20250929",
"type": "model",
"display_name": "Claude Sonnet 4.5",
"created_at": 1699564800
}Skills API
Create Skill
Endpoint:
POST /v1/skillsRequest:
{
"name": "my-skill",
"description": "Skill description",
"instructions": "Detailed instructions...",
"version": "1.0.0"
}List Skills
Endpoint:
GET /v1/skillsResponse:
{
"data": [
{
"id": "skill-123",
"name": "my-skill",
"description": "Skill description"
}
]
}Update Skill
Endpoint:
PATCH /v1/skills/{skill_id}Request:
{
"description": "Updated description",
"instructions": "Updated instructions..."
}Delete Skill
Endpoint:
DELETE /v1/skills/{skill_id}Client SDKs
TypeScript/JavaScript
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY
});
const message = await client.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [
{ role: 'user', content: 'Hello, Claude!' }
]
});
console.log(message.content);Python
import anthropic
client = anthropic.Anthropic(
api_key=os.environ.get("ANTHROPIC_API_KEY")
)
message = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude!"}
]
)
print(message.content)Error Handling
Error Response Format
{
"type": "error",
"error": {
"type": "invalid_request_error",
"message": "Invalid API key"
}
}Error Types
invalid_request_error: Invalid request parameters authentication_error: Invalid API key permission_error: Insufficient permissions not_found_error: Resource not found rate_limit_error: Rate limit exceeded api_error: Internal API error overloaded_error: Server overloaded
Retry Logic
async function withRetry(fn: () => Promise<any>, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (error.status === 529 && i < maxRetries - 1) {
await new Promise(r => setTimeout(r, 1000 * (i + 1)));
continue;
}
throw error;
}
}
}Rate Limits
Headers
Response headers include rate limit info:
anthropic-ratelimit-requests-limit: 1000
anthropic-ratelimit-requests-remaining: 999
anthropic-ratelimit-requests-reset: 2025-11-06T12:00:00Z
anthropic-ratelimit-tokens-limit: 100000
anthropic-ratelimit-tokens-remaining: 99500
anthropic-ratelimit-tokens-reset: 2025-11-06T12:00:00ZBest Practices
- Monitor rate limit headers
- Implement exponential backoff
- Batch requests when possible
- Use caching to reduce requests
Authentication
API Key
Include API key in requests:
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01"Workspace Keys
For organization workspaces:
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $WORKSPACE_API_KEY" \
-H "anthropic-version: 2023-06-01"See Also
- API documentation: https://docs.anthropic.com/api
- Client SDKs: https://docs.anthropic.com/api/client-sdks
- Rate limits: https://docs.anthropic.com/api/rate-limits
- Error handling: https://docs.anthropic.com/api/errors
Best Practices
Guidelines for project organization, security, performance, collaboration, and cost management.
Project Organization
Directory Structure
Keep .claude/ directory in version control:
project/
├── .claude/
│ ├── settings.json # Project settings
│ ├── commands/ # Custom slash commands
│ │ ├── test-all.md
│ │ └── deploy.md
│ ├── skills/ # Project-specific skills
│ │ └── api-testing/
│ ├── hooks.json # Hooks configuration
│ ├── mcp.json # MCP servers (no secrets!)
│ └── .env.example # Environment template
├── .gitignore # Ignore .claude/.env
└── README.mdDocumentation
Document custom extensions:
README.md:
## Claude Code Setup
### Custom Commands
- `/test-all`: Run full test suite
- `/deploy`: Deploy to staging
### Skills
- `api-testing`: REST API testing utilities
### MCP Servers
- `postgres`: Database access
- `github`: Repository integration
### Environment Variables
Copy `.claude/.env.example` to `.claude/.env` and fill in:
- GITHUB_TOKEN
- DATABASE_URLTeam Sharing
What to commit:
.claude/settings.json.claude/commands/.claude/skills/.claude/hooks.json.claude/mcp.json(without secrets).claude/.env.example
What NOT to commit:
.claude/.env(contains secrets).claude/memory/(optional).claude/cache/- API keys or tokens
.gitignore:
.claude/.env
.claude/memory/
.claude/cache/
.claude/logs/Security
API Key Management
Never commit API keys:
# Use environment variables
export ANTHROPIC_API_KEY=sk-ant-xxxxx
# Or .env file (gitignored)
echo 'ANTHROPIC_API_KEY=sk-ant-xxxxx' > .claude/.envRotate keys regularly:
# Generate new key
# Update in all environments
# Revoke old keyUse workspace keys:
# For team projects, use workspace API keys
# Easier to manage and rotate
# Better access controlSandboxing
Enable sandboxing in production:
{
"sandboxing": {
"enabled": true,
"allowedPaths": ["/workspace"],
"networkAccess": "restricted",
"allowedDomains": ["api.company.com"]
}
}Hook Security
Review hook scripts before execution:
# Check hooks.json
cat .claude/hooks.json | jq .
# Review scripts
cat .claude/scripts/hook.sh
# Validate inputs in hooks
#!/bin/bash
if [[ ! "$TOOL_ARGS" =~ ^[a-zA-Z0-9_-]+$ ]]; then
echo "Invalid input"
exit 1
fiPlugin Security
Audit plugins before installation:
# Review plugin source
gh repo view username/plugin
# Check plugin.json
tar -xzf plugin.tar.gz
cat plugin.json
# Install from trusted sources only
claude plugin install gh:anthropics/official-pluginPerformance Optimization
Model Selection
Choose appropriate model for task:
Haiku - Fast, cost-effective:
claude --model haiku "fix typo in README"
claude --model haiku "format code"Sonnet - Balanced (default):
claude "implement user authentication"
claude "review this PR"Opus - Complex tasks:
claude --model opus "architect microservices system"
claude --model opus "optimize algorithm performance"Prompt Caching
Cache repeated context:
// Cache large codebase
const response = await client.messages.create({
model: 'claude-sonnet-4-5-20250929',
system: [
{
type: 'text',
text: largeCodebase,
cache_control: { type: 'ephemeral' }
}
],
messages: [...]
});Benefits:
- 90% cost reduction on cached tokens
- Faster responses
- Better for iterative development
Rate Limiting
Implement rate limiting in hooks:
#!/bin/bash
# .claude/scripts/rate-limit.sh
REQUESTS_FILE=".claude/requests.log"
MAX_REQUESTS=100
WINDOW=3600 # 1 hour
# Count recent requests
RECENT=$(find $REQUESTS_FILE -mmin -60 | wc -l)
if [ $RECENT -ge $MAX_REQUESTS ]; then
echo "Rate limit exceeded"
exit 1
fi
echo $(date) >> $REQUESTS_FILEToken Management
Monitor token usage:
# Check usage
claude usage show
# Set limits
claude config set maxTokens 8192
# Track costs
claude analytics cost --group-by projectTeam Collaboration
Standardize Commands
Create consistent slash commands:
# .claude/commands/test.md
Run test suite with coverage report.
Options:
- {{suite}}: Specific test suite (optional)Usage:
/test
/test unit
/test integrationShare Skills
Create team skills via plugins:
# Create team plugin
cd .claude/plugins/team-plugin
cat > plugin.json <<EOF
{
"name": "team-plugin",
"skills": ["skills/*/"],
"commands": ["commands/*.md"]
}
EOF
# Package and share
tar -czf team-plugin.tar.gz .Consistent Settings
Use project settings for consistency:
.claude/settings.json:
{
"model": "claude-sonnet-4-5-20250929",
"maxTokens": 8192,
"outputStyle": "technical-writer",
"thinking": {
"enabled": true,
"budget": 10000
}
}Memory Settings
Use project memory for shared context:
{
"memory": {
"enabled": true,
"location": "project"
}
}Benefits:
- Shared project knowledge
- Consistent behavior across team
- Reduced onboarding time
Cost Management
Budget Limits
Set budget limits in hooks:
#!/bin/bash
# .claude/scripts/budget-check.sh
MONTHLY_BUDGET=1000
CURRENT_SPEND=$(claude analytics cost --format json | jq '.total')
if (( $(echo "$CURRENT_SPEND > $MONTHLY_BUDGET" | bc -l) )); then
echo "⚠️ Monthly budget exceeded: \$$CURRENT_SPEND / \$$MONTHLY_BUDGET"
exit 1
fiUsage Monitoring
Monitor via analytics API:
# Daily usage report
claude analytics usage --start $(date -d '1 day ago' +%Y-%m-%d)
# Cost by user
claude analytics cost --group-by user
# Export to CSV
claude analytics export --format csv > usage.csvCost Optimization
Use Haiku for simple tasks:
# Expensive (Sonnet)
claude "fix typo in README"
# Cheap (Haiku)
claude --model haiku "fix typo in README"Enable caching:
{
"caching": {
"enabled": true,
"ttl": 300
}
}Batch operations:
# Instead of multiple requests
claude "fix file1.js"
claude "fix file2.js"
claude "fix file3.js"
# Batch them
claude "fix all files: file1.js file2.js file3.js"Track per-project costs:
# Tag projects
claude --project my-project "implement feature"
# View project costs
claude analytics cost --project my-projectDevelopment Workflows
Feature Development
# 1. Plan feature
claude /plan "implement user authentication"
# 2. Create checkpoint
claude checkpoint create "before auth implementation"
# 3. Implement
claude /cook "implement user authentication"
# 4. Test
claude /test
# 5. Review
claude "review authentication implementation"
# 6. Commit
claude /git:cmBug Fixing
# 1. Debug
claude /debug "login button not working"
# 2. Fix
claude /fix:fast "fix login button issue"
# 3. Test
claude /test
# 4. Commit
claude /git:cmCode Review
# Review PR
claude "review PR #123"
# Check security
claude "review for security vulnerabilities"
# Verify tests
claude "check test coverage"See Also
- Security guide: https://docs.claude.com/claude-code/security
- Cost tracking: https://docs.claude.com/claude-code/costs
- Team setup: https://docs.claude.com/claude-code/overview
- API usage:
references/api-reference.md
CI/CD Integration
Integrate Claude Code into development workflows with GitHub Actions and GitLab CI/CD.
GitHub Actions
Basic Workflow
.github/workflows/claude.yml:
name: Claude Code CI
on: [push, pull_request]
jobs:
claude-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: anthropic/claude-code-action@v1
with:
command: '/fix:types && /test'
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}Code Review Workflow
name: Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Review with Claude
uses: anthropic/claude-code-action@v1
with:
command: |
Review the changes in this PR:
- Check for bugs and edge cases
- Verify test coverage
- Assess performance implications
- Review security concerns
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
- name: Post Review Comment
uses: actions/github-script@v6
with:
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: process.env.CLAUDE_OUTPUT
})Test & Fix Workflow
name: Test and Fix
on: [push]
jobs:
test-fix:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run Tests
id: test
continue-on-error: true
run: npm test
- name: Fix Failures
if: steps.test.outcome == 'failure'
uses: anthropic/claude-code-action@v1
with:
command: '/fix:test check test output and fix failures'
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
- name: Commit Fixes
if: steps.test.outcome == 'failure'
run: |
git config user.name "Claude Bot"
git config user.email "claude@anthropic.com"
git add .
git commit -m "fix: auto-fix test failures"
git pushDocumentation Update
name: Update Docs
on:
push:
branches: [main]
jobs:
docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Update Documentation
uses: anthropic/claude-code-action@v1
with:
command: '/docs:update'
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
- name: Commit Docs
run: |
git config user.name "Claude Bot"
git config user.email "claude@anthropic.com"
git add docs/
git commit -m "docs: auto-update documentation" || echo "No changes"
git pushGitLab CI/CD
Basic Pipeline
.gitlab-ci.yml:
stages:
- review
- test
- deploy
claude-review:
stage: review
image: node:18
script:
- npm install -g @anthropic-ai/claude-code
- claude login --api-key $ANTHROPIC_API_KEY
- claude '/fix:types && /test'
only:
- merge_requestsAdvanced Pipeline
variables:
CLAUDE_MODEL: "claude-sonnet-4-5-20250929"
stages:
- lint
- test
- review
- deploy
before_script:
- npm install -g @anthropic-ai/claude-code
- claude login --api-key $ANTHROPIC_API_KEY
lint:
stage: lint
script:
- claude '/fix:types'
artifacts:
paths:
- src/
expire_in: 1 hour
test:
stage: test
script:
- npm test || claude '/fix:test analyze failures and fix'
coverage: '/Coverage: \d+\.\d+%/'
review:
stage: review
script:
- |
claude "Review this merge request:
- Check code quality
- Verify tests
- Review security
- Assess performance" > review.md
artifacts:
reports:
codequality: review.md
only:
- merge_requests
deploy:
stage: deploy
script:
- claude '/deploy-check'
- ./deploy.sh
only:
- mainAutomated Fixes
fix-on-failure:
stage: test
script:
- npm test
retry:
max: 2
when:
- script_failure
after_script:
- |
if [ $CI_JOB_STATUS == 'failed' ]; then
claude '/fix:test analyze CI logs and fix issues'
git add .
git commit -m "fix: auto-fix from CI"
git push origin HEAD:$CI_COMMIT_REF_NAME
fiCommon Patterns
PR Comment Bot
Post Claude reviews as PR comments:
# GitHub Actions
- name: Comment PR
uses: actions/github-script@v6
with:
script: |
const review = process.env.CLAUDE_REVIEW
github.rest.pulls.createReview({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number,
body: review,
event: 'COMMENT'
})Conditional Execution
Run Claude only on certain conditions:
# Run on large PRs only
- name: Review Large PRs
if: ${{ github.event.pull_request.changed_files > 10 }}
uses: anthropic/claude-code-action@v1
with:
command: '/review:codebase analyze changes'Cost Control
Limit CI usage to control costs:
# Skip for draft PRs
- name: Claude Review
if: ${{ !github.event.pull_request.draft }}
uses: anthropic/claude-code-action@v1
# Run only on specific branches
- name: Claude Check
if: startsWith(github.ref, 'refs/heads/release/')
uses: anthropic/claude-code-action@v1Security Best Practices
API Key Management
GitHub:
Settings → Secrets and variables → Actions
Add: ANTHROPIC_API_KEYGitLab:
Settings → CI/CD → Variables
Add: ANTHROPIC_API_KEY (Protected, Masked)Restricted Permissions
GitHub Actions:
permissions:
contents: read
pull-requests: write
issues: writeGitLab CI:
variables:
GIT_STRATEGY: clone
GIT_DEPTH: 1Secrets Scanning
Prevent API key exposure:
- name: Scan for Secrets
run: |
if git diff | grep -i "ANTHROPIC_API_KEY"; then
echo "API key detected in diff!"
exit 1
fiMonitoring & Debugging
Workflow Logs
GitHub Actions:
- name: Debug Info
run: |
echo "Workflow: ${{ github.workflow }}"
echo "Event: ${{ github.event_name }}"
echo "Ref: ${{ github.ref }}"GitLab CI:
debug:
script:
- echo "Pipeline ID: $CI_PIPELINE_ID"
- echo "Job ID: $CI_JOB_ID"
- echo "Branch: $CI_COMMIT_BRANCH"Artifacts
Save Claude outputs:
# GitHub
- name: Save Claude Output
uses: actions/upload-artifact@v3
with:
name: claude-results
path: claude-output.md
# GitLab
artifacts:
paths:
- claude-output.md
expire_in: 1 weekError Handling
- name: Claude Task
continue-on-error: true
id: claude
uses: anthropic/claude-code-action@v1
- name: Handle Failure
if: steps.claude.outcome == 'failure'
run: |
echo "Claude task failed, continuing anyway"Performance Optimization
Caching
GitHub Actions:
- uses: actions/cache@v3
with:
path: ~/.claude/cache
key: claude-cache-${{ hashFiles('package-lock.json') }}GitLab CI:
cache:
key: claude-cache
paths:
- .claude/cacheParallel Execution
# GitHub - Matrix builds
strategy:
matrix:
task: [lint, test, review]
steps:
- run: claude "/${{ matrix.task }}"
# GitLab - Parallel jobs
test:
parallel: 3
script:
- claude "/test --shard $CI_NODE_INDEX/$CI_NODE_TOTAL"See Also
- GitHub Actions docs: https://docs.github.com/actions
- GitLab CI/CD docs: https://docs.gitlab.com/ee/ci/
- Claude Code Actions: https://github.com/anthropics/claude-code-action
- Best practices:
references/best-practices.md
Configuration and Settings
Configure Claude Code behavior with settings hierarchy, model selection, and output styles.
Settings Hierarchy
Settings are applied in order of precedence:
1. Command-line flags (highest priority) 2. Environment variables 3. Project settings (.claude/settings.json) 4. Global settings (~/.claude/settings.json)
Settings File Format
Global Settings
~/.claude/settings.json:
{
"model": "claude-sonnet-4-5-20250929",
"maxTokens": 8192,
"temperature": 1.0,
"thinking": {
"enabled": true,
"budget": 10000
},
"outputStyle": "default",
"memory": {
"enabled": true,
"location": "global"
}
}Project Settings
.claude/settings.json:
{
"model": "claude-sonnet-4-5-20250929",
"maxTokens": 4096,
"sandboxing": {
"enabled": true,
"allowedPaths": ["/workspace"]
},
"memory": {
"enabled": true,
"location": "project"
}
}Key Settings
Model Configuration
model: Claude model to use
claude-sonnet-4-5-20250929(default, latest Sonnet)claude-opus-4-20250514(Opus for complex tasks)claude-haiku-4-20250408(Haiku for speed)
Model aliases:
sonnet: Latest Claude Sonnetopus: Latest Claude Opushaiku: Latest Claude Haikuopusplan: Opus with extended thinking for planning
{
"model": "sonnet"
}Token Settings
maxTokens: Maximum tokens in response
- Default: 8192
- Range: 1-200000
{
"maxTokens": 16384
}temperature: Randomness in responses
- Default: 1.0
- Range: 0.0-1.0
- Lower = more focused, higher = more creative
{
"temperature": 0.7
}Thinking Configuration
Extended thinking for complex reasoning:
{
"thinking": {
"enabled": true,
"budget": 10000,
"mode": "auto"
}
}Options:
enabled: Enable extended thinkingbudget: Token budget for thinking (default: 10000)mode:auto|manual|disabled
Sandboxing
Filesystem and network isolation:
{
"sandboxing": {
"enabled": true,
"allowedPaths": [
"/workspace",
"/home/user/projects"
],
"networkAccess": "restricted",
"allowedDomains": [
"api.example.com",
"*.trusted.com"
]
}
}Options:
enabled: Enable sandboxingallowedPaths: Filesystem access pathsnetworkAccess:full|restricted|noneallowedDomains: Whitelisted domains
Memory Management
Control how Claude remembers context:
{
"memory": {
"enabled": true,
"location": "project",
"ttl": 86400
}
}location options:
global: Share memory across all projectsproject: Project-specific memorynone: Disable memory
ttl: Time to live in seconds (default: 86400 = 24 hours)
Output Styles
Customize Claude's behavior:
{
"outputStyle": "technical-writer"
}Built-in styles:
default: Standard coding assistanttechnical-writer: Documentation focuscode-reviewer: Review-focusedminimal: Concise responses
Logging
Configure logging behavior:
{
"logging": {
"level": "info",
"file": ".claude/logs/session.log",
"console": true
}
}Levels: debug, info, warn, error
Model Configuration
Using Model Aliases
# Use Sonnet (default)
claude
# Use Opus for complex task
claude --model opus "architect a microservices system"
# Use Haiku for speed
claude --model haiku "fix typo in README"
# Use opusplan for planning
claude --model opusplan "plan authentication system"In Settings File
{
"model": "opus",
"thinking": {
"enabled": true,
"budget": 20000
}
}Model Selection Guide
Sonnet (claude-sonnet-4-5-20250929):
- Balanced performance and cost
- Default choice for most tasks
- Good for general development
Opus (claude-opus-4-20250514):
- Highest capability
- Complex reasoning and planning
- Use for architecture, design, complex debugging
Haiku (claude-haiku-4-20250408):
- Fastest, most cost-effective
- Simple tasks (typos, formatting)
- High-volume operations
opusplan:
- Opus + extended thinking
- Deep planning and analysis
- Architecture decisions
Output Styles
Creating Custom Output Style
Create ~/.claude/output-styles/my-style.md:
You are a senior software architect focused on scalability.
Guidelines:
- Prioritize performance and scalability
- Consider distributed systems patterns
- Include monitoring and observability
- Think about failure modes
- Document trade-offsUsing Custom Output Style
claude --output-style my-styleOr in settings:
{
"outputStyle": "my-style"
}Example Output Styles
technical-writer.md:
You are a technical writer creating clear documentation.
Guidelines:
- Use simple, clear language
- Provide examples
- Structure with headings
- Include diagrams when helpful
- Focus on user understandingcode-reviewer.md:
You are a senior code reviewer.
Guidelines:
- Check for bugs and edge cases
- Review security vulnerabilities
- Assess performance implications
- Verify test coverage
- Suggest improvementsEnvironment Variables
API Configuration
export ANTHROPIC_API_KEY=sk-ant-xxxxx
export ANTHROPIC_BASE_URL=https://api.anthropic.comProxy Configuration
export HTTP_PROXY=http://proxy.company.com:8080
export HTTPS_PROXY=http://proxy.company.com:8080
export NO_PROXY=localhost,127.0.0.1Custom CA Certificates
export NODE_EXTRA_CA_CERTS=/path/to/ca-bundle.crtDebug Mode
export CLAUDE_DEBUG=1
export CLAUDE_LOG_LEVEL=debugCommand-Line Flags
Common Flags
# Set model
claude --model opus
# Set max tokens
claude --max-tokens 16384
# Set temperature
claude --temperature 0.8
# Enable debug mode
claude --debug
# Use specific output style
claude --output-style technical-writer
# Disable memory
claude --no-memory
# Set project directory
claude --project /path/to/projectConfiguration Commands
# View current settings
claude config list
# Set global setting
claude config set model opus
# Set project setting
claude config set --project maxTokens 4096
# Get specific setting
claude config get model
# Reset to defaults
claude config resetAdvanced Configuration
Custom Tools
Register custom tools:
{
"tools": [
{
"name": "custom-tool",
"description": "Custom tool",
"command": "./scripts/custom-tool.sh",
"parameters": {
"arg1": "string"
}
}
]
}Rate Limiting
Configure rate limits:
{
"rateLimits": {
"requestsPerMinute": 100,
"tokensPerMinute": 100000,
"retryStrategy": "exponential"
}
}Caching
Prompt caching configuration:
{
"caching": {
"enabled": true,
"ttl": 3600,
"maxSize": "100MB"
}
}Best Practices
Project Settings
- Keep project-specific in
.claude/settings.json - Commit to version control
- Document custom settings
- Share with team
Global Settings
- Personal preferences only
- Don't override project settings unnecessarily
- Use for API keys and auth
Security
- Never commit API keys
- Use environment variables for secrets
- Enable sandboxing in production
- Restrict network access
Performance
- Use appropriate model for task
- Set reasonable token limits
- Enable caching
- Configure rate limits
Troubleshooting
Settings Not Applied
# Check settings hierarchy
claude config list --all
# Verify settings file syntax
cat .claude/settings.json | jq .
# Reset to defaults
claude config resetEnvironment Variables Not Recognized
# Verify export
echo $ANTHROPIC_API_KEY
# Check shell profile
cat ~/.bashrc | grep ANTHROPIC
# Reload shell
source ~/.bashrcSee Also
- Model selection: https://docs.claude.com/about-claude/models
- Output styles:
references/best-practices.md - Security:
references/enterprise-features.md - Troubleshooting:
references/troubleshooting.md
Enterprise Features
Enterprise deployment, security, compliance, and monitoring for Claude Code.
Identity & Access Management
SSO Integration
Support for SAML 2.0 and OAuth 2.0:
{
"auth": {
"type": "saml",
"provider": "okta",
"entityId": "claude-code",
"ssoUrl": "https://company.okta.com/app/saml",
"certificate": "/path/to/cert.pem"
}
}Supported providers:
- Okta
- Azure AD
- Google Workspace
- OneLogin
- Auth0
Role-Based Access Control (RBAC)
Define user roles and permissions:
{
"rbac": {
"roles": {
"developer": {
"permissions": ["code:read", "code:write", "tools:use"]
},
"reviewer": {
"permissions": ["code:read", "code:review"]
},
"admin": {
"permissions": ["*"]
}
}
}
}User Management
Centralized user provisioning:
# Add user
claude admin user add user@company.com --role developer
# Remove user
claude admin user remove user@company.com
# List users
claude admin user list
# Update user role
claude admin user update user@company.com --role adminSecurity & Compliance
Sandboxing
Filesystem and network isolation:
{
"sandboxing": {
"enabled": true,
"mode": "strict",
"filesystem": {
"allowedPaths": ["/workspace"],
"readOnlyPaths": ["/usr/lib", "/etc"],
"deniedPaths": ["/etc/passwd", "/etc/shadow"]
},
"network": {
"enabled": false,
"allowedDomains": ["api.anthropic.com"]
}
}
}Audit Logging
Comprehensive activity logs:
{
"auditLog": {
"enabled": true,
"destination": "syslog",
"syslogHost": "logs.company.com:514",
"includeToolCalls": true,
"includePrompts": false,
"retention": "90d"
}
}Log format:
{
"timestamp": "2025-11-06T10:30:00Z",
"user": "user@company.com",
"action": "tool_call",
"tool": "bash",
"args": {"command": "git status"},
"result": "success"
}Data Residency
Region-specific deployment:
{
"region": "us-east-1",
"dataResidency": {
"enabled": true,
"allowedRegions": ["us-east-1", "us-west-2"]
}
}Compliance Certifications
- SOC 2 Type II: Security controls
- HIPAA: Healthcare data protection
- GDPR: EU data protection
- ISO 27001: Information security
Deployment Options
Amazon Bedrock
Deploy via AWS Bedrock:
{
"provider": "bedrock",
"region": "us-east-1",
"model": "anthropic.claude-sonnet-4-5",
"credentials": {
"accessKeyId": "${AWS_ACCESS_KEY_ID}",
"secretAccessKey": "${AWS_SECRET_ACCESS_KEY}"
}
}Google Vertex AI
Deploy via GCP Vertex AI:
{
"provider": "vertex",
"project": "company-project",
"location": "us-central1",
"model": "claude-sonnet-4-5",
"credentials": "/path/to/service-account.json"
}Self-Hosted
On-premises deployment:
Docker:
docker run -d \
-v /workspace:/workspace \
-e ANTHROPIC_API_KEY=$API_KEY \
anthropic/claude-code:latestKubernetes:
apiVersion: apps/v1
kind: Deployment
metadata:
name: claude-code
spec:
replicas: 3
template:
spec:
containers:
- name: claude-code
image: anthropic/claude-code:latest
env:
- name: ANTHROPIC_API_KEY
valueFrom:
secretKeyRef:
name: claude-secrets
key: api-keyLLM Gateway
Integration with LiteLLM:
{
"gateway": {
"enabled": true,
"url": "http://litellm-proxy:4000",
"apiKey": "${GATEWAY_API_KEY}"
}
}Monitoring & Analytics
OpenTelemetry
Built-in telemetry support:
{
"telemetry": {
"enabled": true,
"exporter": "otlp",
"endpoint": "http://otel-collector:4317",
"metrics": true,
"traces": true,
"logs": true
}
}Usage Analytics
Track team productivity metrics:
# Get usage report
claude analytics usage --start 2025-11-01 --end 2025-11-06
# Get cost report
claude analytics cost --group-by user
# Export metrics
claude analytics export --format csv > metrics.csvMetrics tracked:
- Requests per user/project
- Token usage
- Tool invocations
- Session duration
- Error rates
- Cost per user/project
Custom Dashboards
Build org-specific dashboards:
from claude_code import Analytics
analytics = Analytics(api_key=API_KEY)
# Get metrics
metrics = analytics.get_metrics(
start="2025-11-01",
end="2025-11-06",
group_by="user"
)
# Create visualization
dashboard = analytics.create_dashboard(
metrics=metrics,
charts=["usage", "cost", "errors"]
)Cost Management
Monitor and control API costs:
{
"costControl": {
"enabled": true,
"budgets": {
"monthly": 10000,
"perUser": 500
},
"alerts": {
"threshold": 0.8,
"recipients": ["admin@company.com"]
}
}
}Network Configuration
Proxy Support
HTTP/HTTPS proxy configuration:
export HTTP_PROXY=http://proxy.company.com:8080
export HTTPS_PROXY=http://proxy.company.com:8080
export NO_PROXY=localhost,127.0.0.1,company.internalCustom CA
Trust custom certificate authorities:
export NODE_EXTRA_CA_CERTS=/etc/ssl/certs/company-ca.crtMutual TLS (mTLS)
Client certificate authentication:
{
"mtls": {
"enabled": true,
"clientCert": "/path/to/client-cert.pem",
"clientKey": "/path/to/client-key.pem",
"caCert": "/path/to/ca-cert.pem"
}
}IP Allowlisting
Restrict access by IP:
{
"ipAllowlist": {
"enabled": true,
"addresses": [
"10.0.0.0/8",
"192.168.1.0/24",
"203.0.113.42"
]
}
}Data Governance
Data Retention
Configure data retention policies:
{
"dataRetention": {
"conversations": "30d",
"logs": "90d",
"metrics": "1y",
"backups": "7d"
}
}Data Encryption
Encryption at rest and in transit:
{
"encryption": {
"atRest": {
"enabled": true,
"algorithm": "AES-256-GCM",
"keyManagement": "aws-kms"
},
"inTransit": {
"tlsVersion": "1.3",
"cipherSuites": ["TLS_AES_256_GCM_SHA384"]
}
}
}PII Protection
Detect and redact PII:
{
"piiProtection": {
"enabled": true,
"detectPatterns": ["email", "ssn", "credit_card"],
"action": "redact",
"auditLog": true
}
}High Availability
Load Balancing
Distribute requests across instances:
# HAProxy configuration
frontend claude_front
bind *:443 ssl crt /etc/ssl/certs/claude.pem
default_backend claude_back
backend claude_back
balance roundrobin
server claude1 10.0.1.10:8080 check
server claude2 10.0.1.11:8080 check
server claude3 10.0.1.12:8080 checkFailover
Automatic failover configuration:
{
"highAvailability": {
"enabled": true,
"primaryRegion": "us-east-1",
"failoverRegions": ["us-west-2", "eu-west-1"],
"healthCheck": {
"interval": "30s",
"timeout": "5s"
}
}
}Backup & Recovery
Automated backup strategies:
# Configure backups
claude admin backup configure \
--schedule "0 2 * * *" \
--retention 30d \
--destination s3://backups/claude-code
# Manual backup
claude admin backup create
# Restore from backup
claude admin backup restore backup-20251106See Also
- Network configuration: https://docs.claude.com/claude-code/network-config
- Security best practices:
references/best-practices.md - Monitoring setup: https://docs.claude.com/claude-code/monitoring
- Compliance: https://docs.claude.com/claude-code/legal-and-compliance
Getting Started with Claude Code
Installation, authentication, and setup guide for Claude Code.
What is Claude Code?
Claude Code is Anthropic's agentic coding tool that lives in the terminal and helps turn ideas into code faster. Key features:
- Agentic Capabilities: Autonomous planning, execution, and validation
- Terminal Integration: Works directly in command line
- IDE Support: Extensions for VS Code and JetBrains IDEs
- Extensibility: Plugins, skills, slash commands, and MCP servers
- Enterprise Ready: SSO, sandboxing, monitoring, and compliance features
Prerequisites
System Requirements
- Operating Systems: macOS, Linux, or Windows (WSL2)
- Runtime: Node.js 18+ or Python 3.10+
- API Key: From Anthropic Console (console.anthropic.com)
Getting API Key
1. Go to console.anthropic.com 2. Sign in or create account 3. Navigate to API Keys section 4. Generate new API key 5. Save key securely (cannot be viewed again)
Installation
Install via npm (Recommended)
npm install -g @anthropic-ai/claude-codeInstall via pip
pip install claude-codeVerify Installation
claude --versionAuthentication
Method 1: Interactive Login
claude login
# Follow prompts to enter API keyMethod 2: Environment Variable
# Add to ~/.bashrc or ~/.zshrc
export ANTHROPIC_API_KEY=your_api_key_here
# Or set for single session
export ANTHROPIC_API_KEY=your_api_key_here
claudeMethod 3: Configuration File
Create ~/.claude/config.json:
{
"apiKey": "your_api_key_here"
}Verify Authentication
claude "hello"
# Should respond without authentication errorsFirst Run
Start Interactive Session
# In any directory
claude
# In specific project
cd /path/to/project
claudeRun with Specific Task
claude "implement user authentication"Run with File Context
claude "explain this code" --file app.jsBasic Usage
Interactive Mode
$ claude
Claude Code> help me create a React component
# Claude will plan and executeOne-Shot Mode
claude "add error handling to main.py"With Additional Context
claude "refactor this function" --file utils.js --context "make it async"Understanding the Interface
Session Start
Claude Code v1.x.x
Working directory: /path/to/project
Model: claude-sonnet-4-5-20250929
Claude Code>Tool Execution
Claude will show:
- Tool being used (Read, Write, Bash, etc.)
- Tool parameters
- Results or outputs
- Thinking/planning process (if enabled)
Session End
# Type Ctrl+C or Ctrl+D
# Or type 'exit' or 'quit'Common First Commands
Explore Codebase
claude "explain the project structure"Run Tests
claude "run the test suite"Fix Issues
claude "fix all TypeScript errors"Add Feature
claude "add input validation to the login form"Directory Structure
Claude Code creates .claude/ in your project:
project/
├── .claude/
│ ├── settings.json # Project-specific settings
│ ├── commands/ # Custom slash commands
│ ├── skills/ # Custom skills
│ ├── hooks.json # Hook configurations
│ └── mcp.json # MCP server configurations
└── ...Next Steps
Learn Slash Commands
# See available commands
/help
# Try common workflows
/cook implement feature X
/fix:fast bug in Y
/testCreate Custom Skills
See references/agent-skills.md for creating project-specific skills.
Configure MCP Servers
See references/mcp-integration.md for connecting external tools.
Set Up Hooks
See references/hooks-and-plugins.md for automation.
Configure Settings
See references/configuration.md for customization options.
Quick Troubleshooting
Authentication Issues
# Re-login
claude logout
claude login
# Verify API key is set
echo $ANTHROPIC_API_KEYPermission Errors
# Check file permissions
ls -la ~/.claude
# Fix ownership
sudo chown -R $USER ~/.claudeInstallation Issues
# Clear npm cache
npm cache clean --force
# Reinstall
npm uninstall -g @anthropic-ai/claude-code
npm install -g @anthropic-ai/claude-codeWSL2 Issues (Windows)
# Ensure WSL2 is updated
wsl --update
# Check Node.js version in WSL
node --version # Should be 18+Getting Help
- Documentation: https://docs.claude.com/claude-code
- GitHub Issues: https://github.com/anthropics/claude-code/issues
- Support: support.claude.com
- Community: discord.gg/anthropic
For detailed troubleshooting, see references/troubleshooting.md.
Hooks and Plugins
Customize and extend Claude Code behavior with hooks and plugins.
Hooks System
Hooks are shell commands that execute in response to events.
Hook Types
Pre-tool hooks: Execute before tool calls Post-tool hooks: Execute after tool calls User prompt submit hooks: Execute when user submits prompts
Configuration
Hooks are configured in .claude/hooks.json:
{
"hooks": {
"pre-tool": {
"bash": "echo 'Running: $TOOL_ARGS'",
"write": "./scripts/validate-write.sh"
},
"post-tool": {
"write": "./scripts/format-code.sh",
"edit": "prettier --write $FILE_PATH"
},
"user-prompt-submit": "./scripts/validate-request.sh"
}
}Environment Variables
Available in hook scripts:
All hooks:
$TOOL_NAME: Name of the tool being called$TOOL_ARGS: JSON string of tool arguments
Post-tool only:
$TOOL_RESULT: Tool execution result
User-prompt-submit only:
$USER_PROMPT: User's prompt text
Hook Examples
Pre-tool: Security Validation
#!/bin/bash
# .claude/scripts/validate-bash.sh
# Block dangerous commands
if echo "$TOOL_ARGS" | grep -E "rm -rf /|format|mkfs"; then
echo "❌ Dangerous command blocked"
exit 1
fi
echo "✓ Command validated"Configuration:
{
"hooks": {
"pre-tool": {
"bash": "./.claude/scripts/validate-bash.sh"
}
}
}Post-tool: Auto-format
#!/bin/bash
# .claude/scripts/format-code.sh
# Extract file path from tool args
FILE_PATH=$(echo "$TOOL_ARGS" | jq -r '.file_path')
# Format based on file type
case "$FILE_PATH" in
*.js|*.ts|*.jsx|*.tsx)
prettier --write "$FILE_PATH"
;;
*.py)
black "$FILE_PATH"
;;
*.go)
gofmt -w "$FILE_PATH"
;;
esacConfiguration:
{
"hooks": {
"post-tool": {
"write": "./.claude/scripts/format-code.sh",
"edit": "./.claude/scripts/format-code.sh"
}
}
}User-prompt-submit: Cost Tracking
#!/bin/bash
# .claude/scripts/track-usage.sh
# Log prompt
echo "$(date): $USER_PROMPT" >> .claude/usage.log
# Estimate tokens (rough)
TOKEN_COUNT=$(echo "$USER_PROMPT" | wc -w)
echo "Estimated tokens: $TOKEN_COUNT"Configuration:
{
"hooks": {
"user-prompt-submit": "./.claude/scripts/track-usage.sh"
}
}Hook Best Practices
Performance: Keep hooks fast (<100ms) Reliability: Handle errors gracefully Security: Validate all inputs Logging: Log important actions Testing: Test hooks thoroughly
Hook Errors
When a hook fails:
- Pre-tool hook failure blocks tool execution
- Post-tool hook failure is logged but doesn't block
- User can configure strict mode to block on all failures
Plugins System
Plugins are packaged collections of extensions.
Plugin Structure
my-plugin/
├── plugin.json # Plugin metadata
├── commands/ # Slash commands
│ ├── my-command.md
│ └── another-command.md
├── skills/ # Agent skills
│ └── my-skill/
│ └── SKILL.md
├── hooks/ # Hook scripts
│ ├── hooks.json
│ └── scripts/
├── mcp/ # MCP server configurations
│ └── mcp.json
└── README.md # Documentationplugin.json
{
"name": "my-plugin",
"version": "1.0.0",
"description": "Plugin description",
"author": "Your Name",
"homepage": "https://github.com/user/plugin",
"license": "MIT",
"commands": ["commands/*.md"],
"skills": ["skills/*/"],
"hooks": "hooks/hooks.json",
"mcpServers": "mcp/mcp.json",
"dependencies": {
"node": ">=18.0.0"
}
}Installing Plugins
From GitHub
claude plugin install gh:username/repo
claude plugin install gh:username/repo@v1.0.0From npm
claude plugin install npm:package-name
claude plugin install npm:@scope/package-nameFrom Local Path
claude plugin install ./path/to/plugin
claude plugin install ~/plugins/my-pluginFrom URL
claude plugin install https://example.com/plugin.zipManaging Plugins
List Installed Plugins
claude plugin listUpdate Plugin
claude plugin update my-plugin
claude plugin update --allUninstall Plugin
claude plugin uninstall my-pluginEnable/Disable Plugin
claude plugin disable my-plugin
claude plugin enable my-pluginCreating Plugins
Initialize Plugin
mkdir my-plugin
cd my-pluginCreate plugin.json
{
"name": "my-plugin",
"version": "1.0.0",
"description": "My awesome plugin",
"author": "Your Name",
"commands": ["commands/*.md"],
"skills": ["skills/*/"]
}Add Components
# Add slash command
mkdir -p commands
cat > commands/my-command.md <<EOF
# My Command
Do something awesome with {{input}}.
EOF
# Add skill
mkdir -p skills/my-skill
cat > skills/my-skill/skill.json <<EOF
{
"name": "my-skill",
"description": "Does something",
"version": "1.0.0"
}
EOFPackage Plugin
# Create archive
tar -czf my-plugin.tar.gz .
# Or zip
zip -r my-plugin.zip .Publishing Plugins
To GitHub
git init
git add .
git commit -m "Initial commit"
git tag v1.0.0
git push origin main --tagsTo npm
npm init
npm publishPlugin Marketplaces
Organizations can create private plugin marketplaces.
Configure Marketplace
{
"marketplaces": [
{
"name": "company-internal",
"url": "https://plugins.company.com/catalog.json",
"auth": {
"type": "bearer",
"token": "${COMPANY_PLUGIN_TOKEN}"
}
}
]
}Marketplace Catalog Format
{
"plugins": [
{
"name": "company-plugin",
"version": "1.0.0",
"description": "Internal plugin",
"downloadUrl": "https://plugins.company.com/company-plugin-1.0.0.zip",
"checksum": "sha256:abc123..."
}
]
}Install from Marketplace
claude plugin install company-internal:company-pluginExample Plugin: Code Quality
Structure
code-quality-plugin/
├── plugin.json
├── commands/
│ ├── lint.md
│ └── format.md
├── skills/
│ └── code-review/
│ └── SKILL.md
└── hooks/
├── hooks.json
└── scripts/
└── auto-lint.shplugin.json
{
"name": "code-quality",
"version": "1.0.0",
"description": "Code quality tools and automation",
"commands": ["commands/*.md"],
"skills": ["skills/*/"],
"hooks": "hooks/hooks.json"
}commands/lint.md
# Lint
Run linter on {{files}} and fix all issues automatically.hooks/hooks.json
{
"hooks": {
"post-tool": {
"write": "./scripts/auto-lint.sh"
}
}
}Security Considerations
Hook Security
- Validate all inputs
- Use whitelists for allowed commands
- Implement timeouts
- Log all executions
- Review hook scripts regularly
Plugin Security
- Verify plugin sources
- Review code before installation
- Use signed packages when available
- Monitor plugin behavior
- Keep plugins updated
Best Practices
- Install plugins from trusted sources only
- Review plugin permissions
- Use plugin sandboxing when available
- Monitor resource usage
- Regular security audits
Troubleshooting
Hooks Not Running
- Check hooks.json syntax
- Verify script permissions (
chmod +x) - Check script paths
- Review logs in
.claude/logs/
Plugin Installation Failures
- Verify internet connectivity
- Check plugin URL/path
- Review error messages
- Clear cache:
claude plugin cache clear
Plugin Conflicts
- Check for conflicting commands
- Review plugin load order
- Disable conflicting plugins
- Update plugins to compatible versions
See Also
- Creating slash commands:
references/slash-commands.md - Agent skills:
references/agent-skills.md - Configuration:
references/configuration.md - Best practices:
references/best-practices.md
IDE Integration
Use Claude Code with Visual Studio Code and JetBrains IDEs.
Visual Studio Code
Installation
1. Open VS Code 2. Go to Extensions (Ctrl+Shift+X) 3. Search for "Claude Code" 4. Click Install 5. Authenticate with API key
Features
Inline Chat
- Press Ctrl+I (Cmd+I on Mac)
- Ask questions about code
- Get suggestions in context
- Apply changes directly
Code Actions
- Right-click on code
- Select "Ask Claude"
- Get refactoring suggestions
- Fix bugs and issues
Diff View
- See proposed changes
- Accept/reject modifications
- Review before applying
- Staged diff comparison
Terminal Integration
- Built-in Claude terminal
- Run commands via Claude
- Execute tools directly
- View real-time output
Configuration
.vscode/settings.json:
{
"claude.apiKey": "${ANTHROPIC_API_KEY}",
"claude.model": "claude-sonnet-4-5-20250929",
"claude.maxTokens": 8192,
"claude.autoSave": true,
"claude.inlineChat.enabled": true,
"claude.terminalIntegration": true
}Keyboard Shortcuts
Default shortcuts:
Ctrl+I: Inline chatCtrl+Shift+C: Open Claude panelCtrl+Shift+Enter: Submit to ClaudeEscape: Close Claude chat
Custom shortcuts (.vscode/keybindings.json):
[
{
"key": "ctrl+alt+c",
"command": "claude.openChat"
},
{
"key": "ctrl+alt+r",
"command": "claude.refactor"
}
]Workspace Integration
Project-specific Claude settings:
.vscode/claude.json:
{
"skills": [".claude/skills/project-skill"],
"commands": [".claude/commands"],
"mcpServers": ".claude/mcp.json",
"outputStyle": "technical-writer"
}Common Workflows
Explain Code: 1. Select code 2. Right-click → "Ask Claude" 3. Type: "Explain this code"
Refactor: 1. Select function 2. Press Ctrl+I 3. Type: "Refactor for better performance"
Fix Bug: 1. Click on error 2. Press Ctrl+I 3. Type: "Fix this error"
Generate Tests: 1. Select function 2. Right-click → "Ask Claude" 3. Type: "Write tests for this"
JetBrains IDEs
Supported IDEs:
- IntelliJ IDEA
- PyCharm
- WebStorm
- PhpStorm
- GoLand
- RubyMine
- CLion
- Rider
Installation
1. Open Settings (Ctrl+Alt+S) 2. Go to Plugins 3. Search "Claude Code" 4. Click Install 5. Restart IDE 6. Authenticate with API key
Features
AI Assistant Panel
- Dedicated Claude panel
- Context-aware suggestions
- Multi-file awareness
- Project understanding
Inline Suggestions
- As-you-type completions
- Contextual code generation
- Smart refactoring hints
- Error fix suggestions
Code Reviews
- Automated code reviews
- Security vulnerability detection
- Best practice recommendations
- Performance optimization tips
Refactoring Support
- Smart rename
- Extract method
- Inline variable
- Move class
Configuration
Settings → Tools → Claude Code:
API Key: [Your API Key]
Model: claude-sonnet-4-5-20250929
Max Tokens: 8192
Auto-complete: Enabled
Code Review: EnabledProject Settings (.idea/claude.xml):
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ClaudeSettings">
<option name="model" value="claude-sonnet-4-5-20250929" />
<option name="skillsPath" value=".claude/skills" />
<option name="autoReview" value="true" />
</component>
</project>Keyboard Shortcuts
Default shortcuts:
Ctrl+Shift+A: Ask ClaudeAlt+Enter: Quick fixes with ClaudeCtrl+Alt+L: Format with Claude suggestions
Custom shortcuts (Settings → Keymap → Claude Code):
Ask Claude: Ctrl+Shift+C
Refactor with Claude: Ctrl+Alt+R
Generate Tests: Ctrl+Alt+T
Code Review: Ctrl+Alt+VIntegration with IDE Features
Version Control:
- Review commit diffs with Claude
- Generate commit messages
- Suggest PR improvements
- Analyze merge conflicts
Debugger:
- Explain stack traces
- Suggest fixes for errors
- Debug complex issues
- Analyze variable states
Database Tools:
- Generate SQL queries
- Optimize database schema
- Write migration scripts
- Explain query plans
Common Workflows
Generate Boilerplate: 1. Right-click in editor 2. Select "Generate" → "Claude Code" 3. Choose template type
Review Changes: 1. Open Version Control panel 2. Right-click on changeset 3. Select "Review with Claude"
Debug Error: 1. Hit breakpoint 2. Right-click in debugger 3. Select "Ask Claude about this"
CLI Integration
Use Claude Code from IDE terminal:
# In VS Code terminal
claude "explain this project structure"
# In JetBrains terminal
claude "add error handling to current file"Best Practices
VS Code
Workspace Organization:
- Use workspace settings for team consistency
- Share .vscode/claude.json in version control
- Document custom shortcuts
- Configure output styles per project
Performance:
- Limit inline suggestions in large files
- Disable auto-save for better control
- Use specific prompts
- Close unused editor tabs
JetBrains
Project Configuration:
- Enable Claude for specific file types only
- Configure inspection severity
- Set up custom code review templates
- Use project-specific skills
Performance:
- Adjust auto-complete delay
- Limit scope of code analysis
- Disable for binary files
- Configure memory settings
Troubleshooting
VS Code
Extension Not Loading:
# Check extension status
code --list-extensions | grep claude
# Reinstall
code --uninstall-extension anthropic.claude-code
code --install-extension anthropic.claude-codeAuthentication Issues:
- Verify API key in settings
- Check environment variable
- Re-authenticate in extension
- Review proxy settings
JetBrains
Plugin Not Responding:
File → Invalidate Caches / Restart
Settings → Plugins → Claude Code → ReinstallPerformance Issues:
- Increase IDE memory (Help → Edit Custom VM Options)
- Disable unused features
- Clear caches
- Update plugin version
See Also
- VS Code extension: https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code
- JetBrains plugin: https://plugins.jetbrains.com/plugin/claude-code
- Configuration:
references/configuration.md - Troubleshooting:
references/troubleshooting.md
Initialization Workflow
Complete guide for creating new CLAUDE.md files from scratch.
Phase 1: Discovery & Analysis
1. Codebase Exploration
Tasks to complete:
- Identify project type (web app, library, CLI, mobile, etc.)
- Detect languages, frameworks, and key dependencies
- Find existing documentation (README, contributing guides, wiki)
- Locate test infrastructure and conventions
- Identify build/deploy tooling (package.json scripts, Makefile, etc.)
- Map directory structure and architectural patterns
- Check for existing .claude/ directory and settings
2. Context Extraction
Extract from codebase:
- Code style patterns (indentation, naming conventions, file organization)
- Testing approach (unit/integration/e2e frameworks, coverage expectations)
- Common commands (dev server, build, test, deploy)
- Environment setup requirements
- Git workflow conventions
- Performance considerations (if applicable)
- Security requirements (if applicable)
3. Anti-Pattern Detection
Check for problematic patterns that CLAUDE.md should prevent:
- Inconsistent code style across files
- Missing test coverage in critical areas
- Outdated dependencies or insecure practices
- Lack of error handling standards
- Missing documentation for complex logic
Phase 2: Structure Generation
Template Selection Based on Project Type
For Web Applications
# [Project Name] - Development Guide
## Project Context
[2-3 sentences: what it does, primary tech stack, target users]
## Core Principles
- [Key architectural pattern, e.g., "Server-side rendering with Next.js"]
- [Important constraint, e.g., "Mobile-first responsive design"]
- [Critical requirement, e.g., "WCAG 2.1 AA accessibility compliance"]
## Development Workflow
### Common Commandsnpm run dev # Start development server (localhost:3000) npm run build # Production build with type checking npm run test # Run Jest unit tests npm run test:e2e # Playwright E2E tests (requires dev server) npm run lint # ESLint + Prettier check
### Code Style
- TypeScript strict mode enabled
- Functional components with hooks (no class components)
- Tailwind CSS for styling (no CSS-in-JS)
- File naming: `kebab-case.tsx` for components, `camelCase.ts` for utilities
### Testing Requirements
- New features require unit tests (>80% coverage)
- User flows need E2E tests in `tests/e2e/`
- Use Testing Library queries (avoid testids when possible)
### File Organizationsrc/ ├── app/ # Next.js app router pages ├── components/ # Reusable UI components ├── lib/ # Business logic and utilities ├── hooks/ # Custom React hooks └── types/ # TypeScript type definitions
## Before Making Changes
1. **Read relevant files first** - Don't jump straight to coding
2. **Check existing patterns** - Match architectural decisions
3. **Run tests after changes** - Verify nothing broke
4. **Consider mobile views** - Test responsive behavior
## Context Loading
Load these files for context when working on:
- **Authentication**: `@src/lib/auth.ts`, `@src/middleware.ts`
- **API routes**: `@src/app/api/`, `@src/lib/db/`
- **UI components**: `@src/components/`, `@tailwind.config.ts`
## MCP Tools Available
- `context7`: Use for official React/Next.js documentation
- `magic`: Use for generating new UI componentsFor Backend APIs
# [Project Name] - API Development Guide
## Project Context
[Brief description of API purpose, authentication, primary data models]
## Architecture
- RESTful API with Express.js
- PostgreSQL with Prisma ORM
- JWT authentication with refresh tokens
- Redis caching for frequently accessed data
## Development Commandsnpm run dev # Nodemon with hot reload (port 3001) npm run db:migrate # Apply Prisma migrations npm run db:seed # Seed development data npm run test # Jest unit + integration tests npm run test:watch # Test watcher for TDD
## Code Standards
### API Conventions
- RESTful routes: `/api/v1/resource`
- Response format: `{data, error, meta}` structure
- Error codes: Follow RFC 7807 Problem Details
- Versioning: URL-based (v1, v2) for breaking changes
### Database Patterns
- Use Prisma transactions for multi-table operations
- Index foreign keys and frequently queried fields
- Soft deletes for user data (deletedAt field)
- UTC timestamps for all datetime fields
### Security Requirements
- Validate all inputs with Zod schemas
- Rate limiting: 100 req/min per IP on public routes
- SQL injection prevention via Prisma (never raw queries)
- Sensitive data encryption at rest (PII fields)
### Testing Strategy
- Unit tests for business logic (services/)
- Integration tests for API endpoints (controllers/)
- Mock external APIs in tests (use MSW)
- Minimum 85% coverage on critical paths
## Before Implementing Features
1. **Check API design** - RESTful? Idempotent where needed?
2. **Define validation schema** - Zod schema before route handler
3. **Consider caching** - Frequently read, rarely updated?
4. **Plan error handling** - What can fail? User-friendly messages?
## Environment Setupcp .env.example .env.local # Configure DATABASE_URL, JWT_SECRET npm run db:migrate # Apply schema npm run db:seed # Load test data
## Useful Context Files
- **Authentication**: `@src/middleware/auth.ts`, `@src/services/token.service.ts`
- **Database**: `@prisma/schema.prisma`, `@src/lib/db.ts`
- **Validation**: `@src/schemas/`, `@src/middleware/validate.ts`For CLI Tools
# [Project Name] - CLI Development Guide
## Project Context
[Brief: CLI purpose, primary commands, target users]
## Architecture
- Node.js CLI with Commander.js
- TypeScript for type safety
- Chalk for colored output, Inquirer for prompts
## Commandsnpm run build # Compile TypeScript to dist/ npm run dev # Watch mode for development npm run test # Jest tests with coverage npm link # Symlink for local testing (use mycli globally)
## Code Standards
### CLI Conventions
- Commands: Verb-noun pattern (`mycli create project`)
- Flags: Long form `--verbose`, short `-v`
- Output: Use Chalk (green=success, red=error, yellow=warning)
- Errors: Exit code 1 with clear message, never silent failures
### User Experience
- Interactive prompts for missing required args (Inquirer)
- Progress indicators for long operations (Ora spinners)
- Confirmation prompts before destructive actions
- Help text for all commands (`--help` flag)
### File Operations
- Check file existence before reading/writing
- Use fs-extra for cross-platform compatibility
- Respect .gitignore patterns when scanning directories
- Create backups before overwriting user files
## Testing Approach
- Unit tests for core logic (src/lib/)
- Integration tests for command execution (spawn CLI)
- Test stdout/stderr output validation
- Mock file system operations (memfs)
## Before Adding Commands
1. **Check existing commands** - Consistent naming/patterns?
2. **Plan error scenarios** - Network fails, file locked, invalid input?
3. **Design output format** - Human-readable? JSON flag for scripting?
4. **Consider undo/rollback** - How to revert if fails midway?Phase 3: Intelligent Defaults
Context Loading Strategy
## Context Loading Guidelines
### Use @-syntax ONLY for:
- Small, universally relevant files (<100 lines)
- Configuration that affects all changes (tsconfig, .eslintrc)
- Core type definitions used everywhere
### Use On-Demand Loading:
- Specify context conditionally: "When working on X, read @path/to/file"
- Group related files: "For authentication work: @lib/auth.ts, @middleware.ts"
### Avoid:
- Loading entire directories with @src/**
- Adding large files that aren't always needed
- Injecting documentation that duplicates official sourcesWorkflow Routing (if needed for complex projects)
## Task Routing
When user requests involve:
- **New UI components** → Use `/ui` or magic MCP tool
- **Library documentation** → Use context7 MCP (official docs)
- **Browser testing** → Use Playwright MCP for E2E validation
- **Complex refactoring** → Create plan first, then implement incrementally
Use `/plan` mode for:
- Features requiring >3 files to change
- Architectural changes affecting multiple modules
- When approach is unclear or multiple options existPhase 4: Validation & Output
Quality Checklist
Before presenting CLAUDE.md:
- ✓ File is <400 lines (prefer <250)
- ✓ Commands are accurate (verified against package.json/Makefile)
- ✓ Code patterns match actual codebase conventions
- ✓ No redundant information already in README
- ✓ Context loading is selective, not exhaustive
- ✓ Structure uses clear sections with headers
- ✓ Examples are concrete, not generic advice
- ✓ Security/testing requirements reflect actual needs
Output Format
1. Present the generated CLAUDE.md content 2. Explain key decisions and customizations 3. Suggest optional additions based on project maturity 4. Provide next steps (where to save, how to iterate)
Advanced Scenarios
Multi-Language Projects
# Polyglot Project - Development Guide
## Stack Overview
- **Frontend**: React (TypeScript) + Vite
- **Backend**: Python (FastAPI) + PostgreSQL
- **Mobile**: React Native (TypeScript)
## Context Loading by Area
When working on frontend:
@frontend/package.json
@frontend/tsconfig.json
@frontend/src/components/
When working on backend:
@backend/pyproject.toml
@backend/app/main.py
@backend/app/models/
When working on mobile:
@mobile/package.json
@mobile/src/screens/
## Commands by ContextFrontend
cd frontend && npm run dev
Backend
cd backend && poetry run uvicorn app.main:app --reload
Mobile
cd mobile && npx expo start
## Standards Vary by Language
- **TypeScript**: Functional components, Zod validation
- **Python**: Type hints (mypy strict), Pydantic models
- **Shared**: RESTful API conventions, UTC timestampsMonorepo Projects
# Monorepo - Development Guide
## Architectureapps/ ├── web/ # Next.js customer portal ├── admin/ # React admin dashboard └── api/ # Express.js backend
packages/ ├── ui/ # Shared component library ├── config/ # ESLint, TypeScript configs └── types/ # Shared TypeScript types
## Workspace Commandsnpm run dev # All apps concurrently npm run dev --workspace=web # Single app npm run build --workspaces # All apps npm run test --workspace=packages/ui
## When Making Changes
1. **Shared packages**: Affects all consumers, requires version bump
2. **Apps**: Independent, but check for shared package impacts
3. **Config changes**: Test across all workspaces
## Context Loading
When working on specific app:
@apps/[app-name]/
@packages/ui/ (if UI changes)
@packages/types/ (if type changes)Legacy Codebase
# Legacy System - Modernization Guide
## Current State
- Mixed JavaScript/TypeScript (~60% migrated)
- Class components + hooks (transitioning)
- REST API with inconsistent patterns
## Modernization Strategy
<constraints>
- NEVER break existing APIs (versioning required)
- PREFER refactoring over rewriting
- REQUIRE tests before refactoring (characterization tests)
- ADD new features in TypeScript, modern patterns
</constraints>
## Pattern Decision Tree
When adding features:
1. **New files** → TypeScript, functional components, modern patterns
2. **Modifying existing** → Match existing style (unless explicit refactor task)
3. **Refactoring** → Add tests first, incremental changes, verify with stakeholders
## Before Refactoring
<refactoring_checklist>
- [ ] Characterization tests capture current behavior?
- [ ] Change affects <5 files (small, reversible)?
- [ ] Backward compatibility verified?
- [ ] Team approved scope?
</refactoring_checklist>
## File Organizationsrc/ ├── legacy/ # Class components, old patterns (preserve until migrated) ├── modern/ # New TypeScript, functional components └── shared/ # Utilities (being modernized incrementally)
Integration Strategies
Guide for integrating CLAUDE.md with other tools and global configurations.
Integration with Global CLAUDE.md
User has ~/.claude/CLAUDE.md (global)
Contains:
- Universal principles (SOLID, DRY, YAGNI)
- MCP tool documentation
- Preferred communication style
Project CLAUDE.md should
- Focus exclusively on project-specific guidance
- Reference global patterns: "Follow SOLID principles (see global CLAUDE.md)"
- Avoid duplicating MCP tool usage (already documented globally)
- Add project-specific MCP tool applications only
Example Structure
# MyProject - Development Guide
> Note: General software engineering principles are in your global CLAUDE.md.
> This guide focuses on project-specific patterns and requirements.
## Project Context
[Specific to this project only]
## Code Standards
[Only patterns unique to this codebase, not universal practices]Custom Slash Commands Integration
When to suggest
- Project has >3 frequently repeated workflows
- Common task requires >5 manual steps
- Team follows specific process (e.g., PR checklist)
Example suggestion
"Your project would benefit from custom slash commands:
Create .claude/commands/test-feature.md:Run all tests for a feature area: 1. Run unit tests matching the feature name 2. Run related integration tests 3. Check test coverage report 4. If coverage <80%, identify untested code paths
Usage: `/test-feature authentication`
Would you like me to create these commands?"MCP Tool Configuration
Detect opportunities
Check for:
- React/Vue/Angular imports → Suggest context7 for official docs
- UI component requests → Suggest magic MCP for 21st.dev patterns
- E2E test files → Suggest Playwright MCP for browser automation
- API documentation needs → Suggest context7 for OpenAPI/Swagger
Add to CLAUDE.md
## MCP Tools Configuration
### context7 (Official Documentation)
Use for:
- React hooks best practices: `/resolve react → /get-docs`
- Next.js routing patterns: `/resolve next.js → /get-docs`
- Prisma schema syntax: `/resolve prisma → /get-docs`
### magic (UI Component Generation)
Use for:
- New component requests: "create a searchable data table"
- Component refinement: "make this form more accessible"
- Design system patterns: "responsive card grid layout"
### Playwright (E2E Testing)
Use for:
- User flow validation: "test checkout process"
- Visual regression: "screenshot comparison on mobile"
- Accessibility audit: "check WCAG compliance"Maintenance Strategy
Suggest to user after creation
Your CLAUDE.md is ready. Maintenance recommendations:
1. **Immediate (next 1-2 days)**
- Use Claude Code on 3-5 real tasks
- Note any missing context or unclear guidance
- Verify commands work as documented
2. **Short-term (first 2 weeks)**
- Add on-demand context for files frequently needed
- Remove sections that never get referenced
- Update if project patterns evolve
3. **Long-term (monthly)**
- Review after major dependency updates
- Prune outdated information
- Add new conventions if patterns solidify
4. **Signs to update**
- Framework upgrade (React 17→18, Next 12→14)
- Architecture change (REST→GraphQL, monolith→microservices)
- New team conventions adopted
- Claude consistently missing context you expect it to haveSuccess Metrics
Effective CLAUDE.md indicators
- Claude Code requires fewer clarifying questions
- Code changes match project conventions on first try
- Test coverage maintained/improved consistently
- Commands work without "command not found" errors
- User rarely needs to provide missing context manually
Ineffective CLAUDE.md indicators
- Claude frequently asks "what testing framework?"
- Generated code doesn't match existing style
- User repeatedly provides same context files
- CLAUDE.md contains info never referenced in practice
Quality Standards
Mandatory Elements
Every CLAUDE.md must include:
- ✓ Project context (tech stack, purpose)
- ✓ Common commands (dev, build, test)
- ✓ Code style conventions (if project has specific patterns)
- ✓ File organization overview
- ✓ Where to find key files (authentication, config, etc.)
Prohibited Content
Never include:
- ✗ Generic software engineering principles (user has global PRINCIPLES.md)
- ✗ Framework tutorials (use context7 MCP instead)
- ✗ Extensive copy-paste from README
- ✗ Obvious best practices without project-specific application
- ✗ Auto-loading of large directories (>100 files)
Implementation Checklist
Before presenting CLAUDE.md to user:
Discovery Phase
- [ ] Explored project structure (directories, key files)
- [ ] Identified language, framework, testing setup
- [ ] Read package.json/Makefile/docker-compose for commands
- [ ] Checked for existing documentation to avoid duplication
- [ ] Detected code style patterns (naming, organization)
Generation Phase
- [ ] Selected appropriate template (web/API/CLI/library)
- [ ] Customized based on actual codebase patterns
- [ ] Verified commands are accurate
- [ ] Used concise language (removed fluff)
- [ ] Structured with clear sections
Optimization Phase (if improving existing)
- [ ] Identified token waste (generic advice, redundancy)
- [ ] Converted auto-loading to on-demand context
- [ ] Removed outdated or inaccurate information
- [ ] Condensed verbose sections
- [ ] Preserved all critical project-specific guidance
Validation Phase
- [ ] Token count is reasonable for project complexity
- [ ] All commands verified against current codebase
- [ ] No generic content duplicating global CLAUDE.md or README
- [ ] Structure is scannable (clear headers, concise bullets)
- [ ] Context loading strategy is selective
Output Phase
- [ ] Presented full CLAUDE.md content
- [ ] Explained key customizations
- [ ] Quantified improvements (if optimization)
- [ ] Suggested next steps and iteration approach
- [ ] Offered optional additions
MCP Integration
Model Context Protocol (MCP) integration for connecting Claude Code to external tools and services.
What is MCP?
Model Context Protocol enables Claude Code to:
- Connect to external tools and services
- Access resources (files, databases, APIs)
- Use custom tools
- Provide prompts and completions
Configuration
MCP servers are configured in .claude/mcp.json:
Basic Configuration
{
"mcpServers": {
"server-name": {
"command": "command-to-run",
"args": ["arg1", "arg2"],
"env": {
"VAR_NAME": "value"
}
}
}
}Example Configuration
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"],
"env": {}
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
},
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "postgresql://user:pass@localhost:5432/db"
}
}
}
}Common MCP Servers
Filesystem Access
{
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/path/to/allowed/files"
]
}
}Capabilities:
- Read/write files
- List directories
- File search
- Path restrictions for security
GitHub Integration
{
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
}
}Capabilities:
- Repository access
- Issues and PRs
- Code search
- Workflow management
PostgreSQL Database
{
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "${DATABASE_URL}"
}
}
}Capabilities:
- Query execution
- Schema inspection
- Transaction management
- Connection pooling
Brave Search
{
"brave-search": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-brave-search"],
"env": {
"BRAVE_API_KEY": "${BRAVE_API_KEY}"
}
}
}Capabilities:
- Web search
- News search
- Local search
- Result filtering
Puppeteer (Browser Automation)
{
"puppeteer": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-puppeteer"]
}
}Capabilities:
- Browser automation
- Screenshots
- PDF generation
- Web scraping
Remote MCP Servers
Connect to MCP servers over HTTP/SSE:
Basic Remote Server
{
"mcpServers": {
"remote-service": {
"url": "https://api.example.com/mcp"
}
}
}With Authentication
{
"mcpServers": {
"remote-service": {
"url": "https://api.example.com/mcp",
"headers": {
"Authorization": "Bearer ${API_TOKEN}",
"X-Custom-Header": "value"
}
}
}
}With Proxy
{
"mcpServers": {
"remote-service": {
"url": "https://api.example.com/mcp",
"proxy": "http://proxy.company.com:8080"
}
}
}Environment Variables
Use environment variables for sensitive data:
.env File
# .claude/.env
GITHUB_TOKEN=ghp_xxxxx
DATABASE_URL=postgresql://user:pass@localhost/db
BRAVE_API_KEY=BSAxxxxx
API_TOKEN=token_xxxxxReference in mcp.json
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
}
}
}Testing MCP Servers
Inspector Tool
npx @modelcontextprotocol/inspectorOpens web UI for testing MCP servers:
- List available tools
- Test tool invocations
- View resources
- Debug connections
Manual Testing
# Test server command
npx -y @modelcontextprotocol/server-filesystem /tmp
# Check server output
echo '{"jsonrpc":"2.0","method":"initialize","params":{}}' | \
npx -y @modelcontextprotocol/server-filesystem /tmpCreating Custom MCP Servers
Python Server
from mcp.server import Server
from mcp.server.stdio import stdio_server
server = Server("my-server")
@server.tool()
async def my_tool(arg: str) -> str:
"""Tool description"""
return f"Result: {arg}"
if __name__ == "__main__":
stdio_server(server)Configuration
{
"mcpServers": {
"my-server": {
"command": "python",
"args": ["path/to/server.py"]
}
}
}Node.js Server
import { Server } from "@modelcontextprotocol/server-node";
const server = new Server("my-server");
server.tool({
name: "my-tool",
description: "Tool description",
parameters: { arg: "string" }
}, async ({ arg }) => {
return `Result: ${arg}`;
});
server.listen();Security Considerations
Filesystem Access
- Restrict to specific directories
- Use read-only access when possible
- Validate file paths
- Monitor access logs
API Credentials
- Use environment variables
- Never commit credentials
- Rotate keys regularly
- Implement least-privilege access
Network Access
- Whitelist allowed domains
- Use HTTPS only
- Implement timeouts
- Rate limit requests
Remote Servers
- Validate server certificates
- Use authentication
- Implement request signing
- Monitor for anomalies
Troubleshooting
Server Not Starting
# Check server command
npx -y @modelcontextprotocol/server-filesystem /tmp
# Verify environment variables
echo $GITHUB_TOKEN
# Check logs
cat ~/.claude/logs/mcp-*.logConnection Errors
# Test network connectivity
curl https://api.example.com/mcp
# Verify proxy settings
echo $HTTP_PROXY
# Check firewall rulesPermission Errors
# Verify file permissions
ls -la /path/to/allowed/files
# Check user permissions
whoami
groupsTool Not Found
- Verify server is running
- Check server configuration
- Inspect server capabilities
- Review tool registration
Best Practices
Configuration Management
- Use environment variables for secrets
- Document server purposes
- Version control mcp.json (without secrets)
- Test configurations thoroughly
Performance
- Use local servers when possible
- Implement caching
- Set appropriate timeouts
- Monitor resource usage
Maintenance
- Update servers regularly
- Monitor server health
- Review access logs
- Clean up unused servers
See Also
- MCP specification: https://modelcontextprotocol.io
- Creating MCP servers:
references/api-reference.md - Security best practices:
references/best-practices.md - Troubleshooting:
references/troubleshooting.md
Optimization Patterns
Techniques for reducing token usage and improving CLAUDE.md effectiveness.
Analysis Process
1. Read Current CLAUDE.md
Evaluate against best practices:
- Token efficiency: Is content concise or verbose?
- Accuracy: Do commands/patterns match current codebase?
- Relevance: Is information actionable or generic advice?
- Structure: Clear sections or wall of text?
- Scope: Focused on essentials or trying to document everything?
2. Identify Issues
Common anti-patterns to fix:
- Redundant content (repeats README or official docs)
- Outdated commands or deprecated patterns
- Generic advice not specific to this project
- Missing critical context (e.g., testing requirements)
- Over-use of @-syntax (entire directories loaded)
- Verbose explanations where concise instructions suffice
3. Measure Token Usage
Calculate approximate token count:
- Current file size / 4 = rough token estimate
- Identify high token-to-value sections
- Flag content that doesn't guide Claude's actions
Token Reduction Techniques
Example 1: Verbose to Concise
Before (180 tokens):
When you are implementing new features in this codebase, it's very important that you always make sure to write comprehensive tests for all the functionality you add. We use Jest as our testing framework, and we expect all new code to have at least 80% code coverage. You should write unit tests for individual functions and integration tests for API endpoints.After (54 tokens):
### Testing Requirements
- New features require tests (Jest, >80% coverage)
- Unit tests: Individual functions in `src/lib/`
- Integration tests: API endpoints with SupertestSavings: 70% token reduction, same information
Example 2: Context Loading Optimization
Before (200+ tokens per request):
@src/**/*.ts
@src/**/*.tsx
@tests/**/*.test.ts
@package.json
@tsconfig.json
@README.mdAfter (30 tokens):
## Context Loading
Load conditionally based on task:
- **API work**: `@src/routes/`, `@src/services/`
- **UI work**: `@src/components/`, `@tailwind.config.ts`
- **Config always**: `@package.json`, `@tsconfig.json`Savings: 85% reduction in auto-loaded context
Content Prioritization
Keep (High Value)
- Project-specific commands and scripts
- Code style conventions unique to this project
- File organization patterns
- Testing requirements and strategies
- Security constraints
- Performance considerations
Remove (Low Value)
- Generic software engineering advice
- Information already in README
- Obvious best practices (DRY, SOLID, etc.)
- Detailed explanations of frameworks (use context7 instead)
- Step-by-step tutorials (link to docs instead)
Structural Improvements
Apply Clean Architecture
# Project Name
## Quick Reference
[Most frequently needed commands and patterns]
## Project Context
[2-3 sentences: tech stack, purpose, key constraints]
## Development Workflow
[Commands, setup, common tasks]
## Code Standards
[Conventions specific to this project]
## Before Making Changes
[Pre-flight checklist for Claude]
## Context Loading
[Selective file references]
## MCP Tools
[Available tools and when to use them]XML Integration for Complex Projects
<workflow_routing>
When user request matches:
- "add test" → Read test files, match existing patterns
- "implement API" → Load @src/routes/, @src/services/, validate schemas first
- "fix bug" → Reproduce issue, read related files, apply minimal fix
</workflow_routing>
<constraints>
- Never modify database migrations (create new ones)
- Preserve backward compatibility in public APIs
- Require code review for authentication changes
</constraints>Effectiveness Testing
After optimization, verify: 1. Token count reduced by >40% (if bloated originally) 2. All critical project info retained 3. Commands are still accurate 4. Structure is more scannable 5. On-demand context replaces auto-loading
Iterative Refinement
Suggest to user:
"I've optimized your CLAUDE.md from ~X tokens to ~Y tokens (Z% reduction).
Key changes:
- Removed generic advice duplicated in your README
- Converted auto-loading (@src/**) to on-demand context
- Condensed verbose explanations to concise checklists
- Added workflow routing for common tasks
Next steps:
1. Save this version to .claude/CLAUDE.md (or project root)
2. Use Claude Code on your project for 1-2 days
3. Note any missing context or unclear instructions
4. Iterate based on actual usage patterns
Would you like me to:
- Add specific sections (e.g., deployment, debugging)?
- Create custom slash commands for frequent workflows?
- Set up MCP tool integration?"Best Practices from Anthropic Engineering
1. Specificity Trumps Verbosity
❌ Bad: "Make sure to follow best practices when writing tests"
✅ Good: "Test edge cases: null inputs, empty arrays, unauthorized access"2. Iterate on Effectiveness
- Start minimal (core commands + key constraints)
- Add sections as needs become clear
- Remove unused guidance after 1-2 weeks
- Measure: Does this make Claude more effective?
3. Use Visual References
When applicable, include:
- Directory tree structure
- Example command output
- API response format examples
- Error message examples
4. Enable Extended Thinking
For complex projects, add:
"For architectural decisions or complex refactoring, think through:
1. Current implementation analysis
2. Alternative approaches
3. Tradeoff evaluation
4. Selected approach rationale"Advanced Patterns from pincc.ai
1. Core Identity & Mission
Add at top of CLAUDE.md for complex projects:
"You are a [role] for [project type]. Your mission is to [primary goal] while maintaining [key constraint]."
Example:
"You are a backend API developer for a healthcare SaaS platform. Your mission is to implement features that prioritize HIPAA compliance and data security."2. Workflow Routing Engine
For projects with distinct work types:
<workflow_routing>
Priority 10: If user says "/deploy" → Use deployment workflow
Priority 9: If keywords: "bug", "error", "broken" → Debug workflow
Priority 8: If keywords: "test", "coverage" → Testing workflow
Priority 5: If keywords: "feature", "implement", "add" → Feature workflow
Default: Analyze request, ask for clarification if ambiguous
</workflow_routing>3. Ultrathink Protocol
For critical operations:
<ultrathink_triggers>
Engage deep thinking before:
- Database schema changes
- Authentication/authorization modifications
- Breaking API changes
- Deployment configuration updates
- Dependency upgrades (major versions)
Process:
1. Clarify objective with user
2. Analyze implications (data loss risk, backward compat, security)
3. Present options with tradeoffs
4. Get explicit approval
5. Implement with rollback plan
</ultrathink_triggers>4. Security & Safety Constraints
<constraints>
- NEVER commit secrets, API keys, or credentials
- NEVER run destructive operations without confirmation
- NEVER skip migrations (create new ones instead)
- ALWAYS validate user input in API endpoints
- ALWAYS use parameterized queries (no string concatenation)
- REQUIRE explicit approval for: force push, drop table, delete user data
</constraints>5. Context Management Strategy
# Context Loading Strategy
## Always Load (Global Context)
@package.json
@tsconfig.json
@.env.example
## Conditional Loading (On-Demand)
When working on authentication:
@src/lib/auth.ts
@src/middleware/authenticate.ts
@prisma/schema.prisma (User model)
When working on API routes:
@src/schemas/validation.ts
@src/lib/api-response.ts
When working on UI components:
@src/components/
@tailwind.config.ts
@src/styles/globals.css
## Never Load
- node_modules/
- dist/, build/ (generated files)
- .next/, .cache/ (framework internals)Token Budget Guidelines
Target sizes by project complexity:
- Simple (single-purpose tool): 100-200 tokens
- Medium (standard web app): 200-400 tokens
- Complex (multi-service platform): 400-800 tokens
- Maximum (exception only): 1000 tokens
If approaching max, split into:
.claude/CLAUDE.md(essentials).claude/ARCHITECTURE.md(reference, not auto-loaded).claude/commands/*.md(workflows as slash commands)
Error Prevention
Common Mistakes to Avoid
1. Over-Documentation
Problem: Trying to document every possible scenario
Solution: Document project-specific decisions only2. Stale Information
Problem: Commands/patterns no longer match codebase
Solution: Verify against current package.json, actual files3. Redundant Context
Problem: README says "React SPA", CLAUDE.md repeats it extensively
Solution: Link to README, add only project-specific React patterns4. Token Waste
Problem: Auto-loading entire src/ directory
Solution: On-demand context by functional area5. Generic Fluff
Problem: "Make sure code is maintainable and follows best practices"
Solution: "Match existing patterns: functional components, Zod validation, Prisma transactions"