
Claude Code
- 65 installs
- 7 repo stars
- Updated June 18, 2026
- duc01226/easyplatform
Guides Claude Code CLI setup, configuration, troubleshooting, and feature usage.
About
Guides Claude Code CLI setup, configuration, troubleshooting, and feature usage. A developer uses it to configure or debug their Claude Code environment.
- Guides Claude Code CLI setup and configuration
- Covers troubleshooting and feature usage
Claude Code by the numbers
- 65 all-time installs (skills.sh)
- Ranked #280 of 550 CLI & Terminal skills by installs in the Skillselion catalog
- Data as of Jul 29, 2026 (Skillselion catalog sync)
npx skills add https://github.com/duc01226/easyplatform --skill claude-codeAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 65 |
|---|---|
| repo stars | ★ 7 |
| Last updated | June 18, 2026 |
| Repository | duc01226/easyplatform ↗ |
What it does
Guides Claude Code CLI setup, configuration, troubleshooting, and feature usage.
Files
Codex compatibility note:
>
- Invoke repository skills with$skill-namein Codex; this mirrored copy rewrites legacy Claude/skill-namereferences.
- Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
- User-question prompts mean to ask the user directly in Codex.
- Ignore Claude-specific mode-switch instructions when they appear.
- Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
- Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required spawn_agent subagent(s) for that task.- Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
- For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
- If a required step/tool cannot run in this environment, stop and ask the user before adapting.
<!-- CODEX:PROJECT-REFERENCE-LOADING:START -->
Codex Project-Reference Loading (No Hooks)
Codex does not receive Claude hook-based doc injection. When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
Always read:
docs/project-config.json(project-specific paths, commands, modules, and workflow/test settings)docs/project-reference/docs-index-reference.md(routes to the fulldocs/project-reference/*catalog)docs/project-reference/lessons.md(always-on guardrails and anti-patterns)
Missing/stale context route: If docs/project-config.json, the docs index, lessons.md, CLAUDE.md, AGENTS.md, or any task-required reference doc is missing or stale, auto-run $project-init or the narrow setup route ($project-config, $docs-init, $scan-all, $scan --target=<key>, $claude-md-init) before ordinary project-specific work. If Codex mirrors or AGENTS.md are missing/stale, ask the user to run $sync-codex; do not auto-run it.
Situation-based docs:
- Backend/CQRS/API/domain/entity changes:
backend-patterns-reference.md,domain-entities-reference.md,project-structure-reference.md - Frontend/UI/styling/design-system:
frontend-patterns-reference.md,scss-styling-guide.md,design-system/README.md - Spec authoring,
docs/specs/pathing, or TC format:feature-spec-reference.md,spec-system-reference.md,spec-principles.md - Behavior/public-contract changes or spec-test-code sync:
workflow-spec-test-code-cycle-reference.mdplus the spec docs above - Derived spec indexes/ERDs/reimplementation guides:
spec-system-reference.mdand source Feature Specs underdocs/specs/ - Integration test implementation/review:
integration-test-reference.md - E2E test implementation/review:
e2e-test-reference.md - Code review/audit work:
code-review-rules.mdplus domain docs above based on changed files
Do not read all docs blindly. Start from docs-index-reference.md, then open only relevant files for the task.
<!-- CODEX:PROJECT-REFERENCE-LOADING:END -->
Quick Summary
Goal: Help users install, configure, troubleshoot, and extend Claude Code CLI (hooks, MCP, skills, commands).
Workflow:
1. Categorize — Identify problem type (Setup, Hooks, MCP, Context, Extensibility, Config) 2. Diagnose — Follow category-specific diagnostic steps 3. Fix & Verify — Apply solution and confirm it resolves the issue
Key Rules:
- Not for writing application code -- use the feature workflow, fix, or refactoring skills instead
- Obtain explicit user approval before modifying settings; never change them unilaterally
- For hooks: check event type, script executability, and JSON output format
Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).
Claude Code
Purpose
Help users install, configure, troubleshoot, and extend Claude Code CLI -- Anthropic's agentic coding tool with skills, hooks, MCP servers, and slash commands.
When to Use
- Setting up Claude Code for the first time (installation, authentication)
- Troubleshooting hooks that don't fire or produce errors
- Diagnosing MCP server connection failures
- Understanding or resolving context window limits
- Creating or modifying slash commands and agent skills
- Configuring settings (model, allowed tools, output style)
When NOT to Use
- Writing application code -- use the
workflow-featureworkflow,fix, orrefactoringskills - Creating or managing MCP servers -- use MCP documentation and project MCP config directly
- AI prompt engineering -- use general prompt-engineering guidance directly
Prerequisites
- Access to
.claude/directory in the project root - For hooks: read
.claude/hooks/directory structure - For skills: read
.claude/skills/directory structure
Workflow
Step 1: Identify the Problem Category
| User Says | Category | Go To |
|---|---|---|
| "install", "set up", "authenticate" | Setup | Step 2A |
| "hook not firing", "hook error" | Hook Issues | Step 2B |
| "MCP not connecting", "MCP error" | MCP Issues | Step 2C |
| "context too long", "compaction", "token limit" | Context Issues | Step 2D |
| "create skill", "create command" | Extensibility | Step 2E |
| "configure", "settings", "model" | Configuration | Step 2F |
Step 2A: Setup
1. Check prerequisites: Node.js 18+, npm 2. Verify authentication: claude auth status 3. IF auth fails: guide through claude auth login 4. Verify project detection: check for CLAUDE.md in project root
Step 2B: Hook Issues
1. Read the hook file causing issues 2. Check hook event type matches expected trigger (PreToolUse, PostToolUse, SessionStart, Stop, SubagentStop) 3. Verify hook script is executable and has correct shebang 4. Check .claude/settings.json for hook registration 5. Test hook in isolation: run the script directly with mock input 6. Check for syntax errors in hook output (must be valid JSON for PreToolUse/PostToolUse)
Common fixes:
- Hook not firing: wrong event name or tool matcher pattern
- Hook errors: script not finding dependencies (check relative paths)
- Hook blocks unexpectedly: PreToolUse returning
{ "decision": "block" }incorrectly
Step 2C: MCP Issues
1. Check .claude/settings.json for MCP server configuration 2. Verify the MCP server process can start: run the command manually 3. Check environment variables (API keys, tokens) are set 4. Test connectivity: claude mcp list to see registered servers 5. IF timeout: increase timeout in config or check network
Common fixes:
- "Connection refused": MCP server not running or wrong port
- "Authentication failed": expired or missing API token
- "Tool not found": MCP server registered but tool name mismatch
Step 2D: Context Issues
1. Check current context usage (Claude will report when near limit) 2. IF approaching limit: suggest $compact command 3. Review if large files are being read unnecessarily 4. Check for recovery files in /tmp/ck/swap/ after compaction 5. Verify post-compact-recovery hook is configured for session continuity
Step 2E: Extensibility
1. For skills: read references/agent-skills.md for structure 2. For custom slash commands: create skills in .claude/skills/{name}/SKILL.md 3. Verify SKILL.md frontmatter has required fields (name, version, description) 4. Test: invoke the skill/command and verify it loads
Step 2F: Configuration
1. Read references/configuration.md for settings hierarchy 2. Settings locations: .claude/settings.json (project), ~/.claude/settings.json (user) 3. IMPORTANT: Obtain explicit user approval before modifying settings; never change them unilaterally 4. Common settings: model selection, allowed tools, output verbosity
Step 3: Verification
- Confirm the fix resolves the user's issue
- Document any configuration changes made
- Warn if changes affect other team members (project-level settings)
Output Format
## Claude Code: [Issue/Task Summary]
### Problem
[What was wrong or what was requested]
### Solution
[Step-by-step fix or setup instructions]
### Files Changed
[List any config files modified, with before/after]
### Verification
[How to confirm the fix works]Examples
Example 1: Hook Not Firing
User: "My PreToolUse hook for blocking large file reads isn't triggering"
Diagnosis:
1. Read .claude/settings.json -- hook registered under hooks.PreToolUse 2. Check tool matcher: "matcher": "Read" -- correct 3. Run script directly: node .claude/hooks/block-large-reads.cjs -- works 4. Found: Hook command uses %CLAUDE_PROJECT_DIR% but runs from wrong CWD
Fix: Update hook command to use absolute path or verify %CLAUDE_PROJECT_DIR% resolves correctly. Check that the hook entry in settings uses the correct variable syntax for the OS/shell (Windows vs Unix).
Example 2: Setting Up a New Slash Command
User: "I want a /deploy command that runs our staging deployment"
Steps:
1. Create .claude/skills/deploy/SKILL.md:
Deploy to staging environment.
Run the following steps:
1. Verify all tests pass: `npm test`
2. Build the project: `npm run build`
3. Deploy: `npm run deploy:staging`
4. Report deployment status2. Test: type /deploy in Claude Code CLI 3. Verify: command appears in autocomplete and executes the workflow
Reference Files
Load these for detailed guidance on specific topics:
| Topic | File |
|---|---|
| Installation | references/getting-started.md |
| Slash commands | references/slash-commands.md |
| Skills creation | references/agent-skills.md |
| MCP servers | references/mcp-integration.md |
| Hooks system | references/hooks-comprehensive.md |
| Configuration | references/configuration.md |
| Troubleshooting | references/troubleshooting.md |
| Enterprise | references/enterprise-features.md |
Related Skills
skill-creator-- for creating new agent skills with best practices
---
[IMPORTANT] Use task tracking to break ALL work into small tasks BEFORE starting — including tasks for each file read. This prevents context loss from long files. For simple tasks, AI MUST ATTENTION ask user whether to skip.
<!-- SYNC:ai-mistake-prevention -->
AI Mistake Prevention — Failure modes to avoid on every task:
>
Check downstream references before deleting. Deleting components causes documentation and code staleness cascades. Map all referencing files before removal.
Verify AI-generated content against actual code. AI hallucinates APIs, class names, and method signatures. Always grep to confirm existence before documenting or referencing.
Trace full dependency chain after edits. Changing a definition misses downstream variables and consumers derived from it. Always trace the full chain.
Trace ALL code paths when verifying correctness. Confirming code exists is not confirming it executes. Always trace early exits, error branches, and conditional skips — not just happy path.
When debugging, ask "whose responsibility?" before fixing. Trace whether bug is in caller (wrong data) or callee (wrong handling). Fix at responsible layer — never patch symptom site.
Assume existing values are intentional — ask WHY before changing. Before changing any constant, limit, flag, or pattern: read comments, check git blame, examine surrounding code.
Verify ALL affected outputs, not just the first. Changes touching multiple stacks require verifying EVERY output. One green check is not all green checks.
Holistic-first debugging — resist nearest-attention trap. When investigating any failure, list EVERY precondition first (config, env vars, DB names, endpoints, DI registrations, data preconditions), then verify each against evidence before forming any code-layer hypothesis.
Surgical changes — apply the diff test. Bug fix: every changed line must trace directly to the bug. Don't restyle or improve adjacent code. Enhancement task: implement improvements AND announce them explicitly.
Surface ambiguity before coding — don't pick silently. If request has multiple interpretations, present each with effort estimate and ask. Never assume all-records, file-based, or more complex path.
Keep domain concepts out of generic/shared/infrastructure layers. A reusable layer (shared library, framework, infra module) must reference NO consumer-specific domain concept — tenant/customer/product IDs, business entities, feature rules. The leak compiles and runs, so it passes review silently while coupling the "reusable" layer to one consumer. Push domain fields/logic down into the consumer via subclass or composition.
<!-- /SYNC:ai-mistake-prevention -->
<!-- SYNC:critical-thinking-mindset -->
Critical Thinking Mindset — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
Anti-hallucination: Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.
<!-- /SYNC:critical-thinking-mindset -->
<!-- SYNC:critical-thinking-mindset:reminder -->
MUST ATTENTION apply critical thinking — every claim needs traced proof, confidence >80% to act. Anti-hallucination: never present guess as fact.
<!-- /SYNC:critical-thinking-mindset:reminder -->
<!-- SYNC:ai-mistake-prevention:reminder -->
MUST ATTENTION apply AI mistake prevention — holistic-first debugging, fix at responsible layer, surface ambiguity before coding, re-read files after compaction.
<!-- /SYNC:ai-mistake-prevention:reminder -->
Closing Reminders
- MANDATORY IMPORTANT MUST ATTENTION break work into small todo tasks using task tracking BEFORE starting
- MANDATORY IMPORTANT MUST ATTENTION search codebase for 3+ similar patterns before creating new code
- MANDATORY IMPORTANT MUST ATTENTION cite
file:lineevidence for every claim (confidence >80% to act) - MANDATORY IMPORTANT MUST ATTENTION add a final review todo task to verify work quality
[TASK-PLANNING] Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using task tracking.
<!-- CODEX:SYNC-PROMPT-PROTOCOLS:START -->
Hookless Prompt Protocol Mirror (Auto-Synced)
Source: .claude/hooks/lib/prompt-injections.cjs + .claude/.ck.json
[WORKFLOW-EXECUTION-PROTOCOL] [BLOCKING] Workflow Execution Protocol — MANDATORY IMPORTANT MUST CRITICAL. Do not skip for any reason.
Generic portability boundary: Reusable skills and protocol text stay project-neutral; project-specific conventions are discovered from docs/project-config.json and docs/project-reference/. Apply shared AI-SDD from shared/sdd-artifact-contract.md. Read docs/project-config.json and docs/project-reference/docs-index-reference.md, then open the project reference docs named there. For spec, test-case, behavior-change, public-contract, or docs/specs/ work, route through the local spec docs named by the docs index: feature-spec-reference.md, spec-system-reference.md, spec-principles.md, and workflow-spec-test-code-cycle-reference.md when specs/tests/code must stay synchronized. If either file or a required reference doc is missing or stale, auto-run $project-init (or the narrow lower-level route such as $project-config, $docs-init, $scan-all, or $scan --target=<key>) before ordinary project-specific work. Any supported AI tool may execute when this shared context and local docs are available.
1. DETECT: If the prompt starts with an explicit slash skill/workflow command, execute it directly. Otherwise match the prompt against the workflow catalog and skill list. 2. ANALYZE: Choose the best option: execute directly, invoke a skill, activate a standard workflow, or compose a custom step combination. 3. AUTO-SELECT: Pick the best option yourself. Do not ask the user to choose between direct execution, skill, standard workflow, or custom workflow. 4. ACTIVATE: For a selected workflow, call $start-workflow <workflowId>; for a selected skill, invoke that skill; for a custom workflow, sequence custom steps directly; for direct execution, proceed with the task. 5. CREATE TASKS: task tracking for ALL workflow/skill/custom steps before execution when the selected path has multiple steps. 6. EXECUTE: Advance per the Workflow Step Advancement & Parallel Phases rule in your context instructions — model-driven; a sub-agent completion advances a step identically to an inline call; a parallel-phase group is an all-return barrier (advance only after ALL members return, never serialize it) [CRITICAL-THINKING-MINDSET] Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act. Anti-hallucination principle: Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination. AI Attention principle (Primacy-Recency): Put the 3 most critical rules at both top and bottom of long prompts/protocols so instruction adherence survives long context windows. Goal-driven execution: Define success criteria first, loop until verified, and stop only when observable checks pass. Tests verify intent: Tests must protect business rules/invariants and fail when the protected intent breaks, not only mirror current behavior.
[LESSON-LEARNED-REMINDER] [BLOCKING] Task Planning & Continuous Improvement — MANDATORY. Do not skip.
Break work into small tasks (task tracking) before starting. Add final task: "Analyze AI mistakes & lessons learned".
Extract lessons — ROOT CAUSE ONLY, not symptom fixes:
1. Name the FAILURE MODE (reasoning/assumption failure), not symptom — "assumed API existed without reading source" not "used wrong enum value". 2. Generality test: does this failure mode apply to ≥3 contexts/codebases? If not, abstract one level up. 3. Write as a universal rule — strip project-specific names/paths/classes. Useful on any codebase. 4. Consolidate: multiple mistakes sharing one failure mode → ONE lesson. 5. Recurrence gate: "Would this recur in future session WITHOUT this reminder?" — No → skip $learn. 6. Auto-fix gate: "Could $code-review/$code-simplifier/$security-review/$lint catch this?" — Yes → improve review skill instead. 7. BOTH gates pass → ask user to run $learn. [TASK-PLANNING] [MANDATORY] BEFORE executing any workflow or skill step, create/update task tracking for all planned steps, then keep it synchronized as each step starts/completes.
<!-- CODEX:SYNC-PROMPT-PROTOCOLS:END -->
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: 'sonnet',
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 {source-root}/mainCreate 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 repository 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
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 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 `{source-root}/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 `{source-root}/components/Button` 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: 'sonnet',
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="sonnet",
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.5
}
]
}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.0
}
],
"total": 250.0
}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": "sonnet",
"max_tokens": 4096,
"messages": [
{
"role": "user",
"content": "Explain this code"
}
]
}With Skills:
{
"model": "sonnet",
"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": "sonnet",
"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": "sonnet",
"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": "sonnet",
"type": "model",
"display_name": "Claude Sonnet 4.5"
}
]
}Get Model
Endpoint:
GET /v1/models/{model_id}Response:
{
"id": "sonnet",
"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: 'sonnet',
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="sonnet",
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/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:
Sonnet - Balanced (default for all tasks):
claude "fix typo in README"
claude "implement user authentication"
claude "review this PR"Opus - Complex reasoning and architecture:
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: 'sonnet',
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/skills/test/SKILL.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": "sonnet",
"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 Sonnet as the default for all tasks:
# Default (Sonnet)
claude "fix typo in README"
# Complex tasks (Opus)
claude --model opus "architect microservices system"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 $commit --pushBug Fixing
# 1. Debug
claude $debug-investigate "login button not working"
# 2. Fix
claude $fix "fix login button issue"
# 3. Test
claude $test
# 4. Commit
claude $commit --pushCode 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-review
- 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: "sonnet"
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:
- {source-root}/
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
Common Claude Code Workflows
Feature Implementation
Plan first approach:
$plan implement payment integration with Stripe
# Review plan, then proceed with implementation
$cook implement payment integration with StripeDirect implementation:
$cook implement user authentication with JWT
$cook add dark mode toggle to settingsBug Fixing
Quick fixes:
$fix login button not working
$fix --target=types # Fix TypeScript errorsComplex debugging:
$debug-investigate API returns 500 errors intermittently
$fix authentication flow breaks after password resetTest-driven fixes:
$fix --target=test user service tests failing
$test # Run full test suiteCI/CD failures:
$fix --target=ci https://github.com/org/repo/actions/runs/12345Code Review & Testing
# Review recent changes
claude "review my latest commit"
claude "analyze the changes in PR #42"
# Run tests
$test
$fix --target=test payment tests failingDocumentation Management
/docs:init # Create initial docs structure
/docs:update # Update all docs based on codebase
/docs:summarize auth security # Focused documentation updateGit Operations
$commit --push # Stage, commit, and push
/git:cp # Stage, commit, and push
/git:pr feature-branch main # Create pull request from feature-branch to mainDesign & Content
UI/UX design:
$design:fast create landing page for SaaS product
$design:good build immersive dashboard with data viz
$design:screenshot analyze this design and suggest improvementsContent creation:
/content:good write product description for new feature
/content:fast create blog post about our API
/content:cro optimize landing page copy for conversionsProject Initialization
/bootstrap:auto create Next.js app with auth and database
/bootstrap:auto:fast quick React app with TypeScriptAdvanced Workflows
Codebase analysis:
$code-review analyze authentication implementation
$scout --ext find all payment-related filesStrategic planning:
$plan implement real-time collaboration features
$plan compare serverless vs traditional backend approaches
$brainstorm improve onboarding UXPayment integrations:
/payment-integration add Vietnamese payment gatewaySkill management:
/skill:create payment-processing # Create new skill
/skill:optimize frontend-dev # Improve existing skillConfiguration 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": "sonnet",
"maxTokens": 8192,
"temperature": 1.0,
"thinking": {
"enabled": true,
"budget": 10000
},
"outputStyle": "default",
"memory": {
"enabled": true,
"location": "global"
}
}Project Settings
.claude/settings.json:
{
"model": "sonnet",
"maxTokens": 4096,
"sandboxing": {
"enabled": true,
"allowedPaths": ["/workspace"]
},
"memory": {
"enabled": true,
"location": "project"
}
}Key Settings
Model Configuration
model: Claude model to use
sonnet(default, balanced coding)opus(complex reasoning and architecture)
Model aliases (use these instead of version IDs):
sonnet: Latest Claude Sonnet (default for all tasks)opus: Latest Claude Opus (complex tasks)opusplan: 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 opusplan for planning
claude --model opusplan "plan authentication system"In Settings File
{
"model": "opus",
"thinking": {
"enabled": true,
"budget": 20000
}
}Model Selection Guide
Sonnet (default):
- Balanced performance and cost
- Default choice for all tasks
- Good for general development, coding, reviews
Opus (complex tasks):
- Highest capability
- Complex reasoning and planning
- Use for architecture, design, complex debugging
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.sonnet",
"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": "sonnet",
"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: sonnet
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.
Detailed documentation
https://code.claude.com/docs/en/hooks.md
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
Hooks System - Comprehensive Guide
Event-driven automation framework for Claude Code with deterministic shell commands and LLM evaluations.
Quick Reference
Hook Types: Command-based (bash) | Prompt-based (LLM evaluation) Configuration: .claude/settings.json (4-tier hierarchy) Events: 10 lifecycle triggers Matchers: Exact, regex, wildcard patterns Security: User assumes full responsibility
Hook Events (10 Total)
| Event | Trigger Point | Common Use Cases |
|---|---|---|
| PreToolUse | Before tool processing | Validation, blocking operations |
| PermissionRequest | Permission dialog display | Custom permission logic |
| PostToolUse | After tool completion | Post-processing, auto-formatting, logging |
| Notification | Notification sent | Desktop alerts, custom notifications |
| UserPromptSubmit | User prompt submission | Input validation, filtering |
| Stop | Main agent response complete | Session cleanup, logging |
| SubagentStop | Subagent completion | Subagent monitoring |
| PreCompact | Before compaction | Pre-compaction validation |
| SessionStart | Session init/resume | Environment setup |
| SessionEnd | Session termination | Cleanup operations |
Configuration Structure
Settings Hierarchy (Priority Order)
1. Enterprise managed: managed-settings.json (IT-deployed, cannot override) 2. User settings: ~/.claude/settings.json (global defaults) 3. Project settings: .claude/settings.json (team-shared, version controlled) 4. Local settings: .claude/settings.local.json (personal, git-ignored)
Basic Configuration
{
"hooks": {
"EventName": [
{
"matcher": "ToolPattern",
"hooks": [
{
"type": "command",
"command": "bash script command"
}
]
}
]
}
}Tool Matchers
Exact matching:
"matcher": "Bash"Regex patterns:
"matcher": "Edit|Write"Wildcard (all tools):
"matcher": "*"MCP tools:
"matcher": "mcp__servername__toolname"Built-in tools: Write, Edit, Read, Bash, Task, Grep, Glob, WebFetch, WebSearch, NotebookEdit, SlashCommand, Skill
Hook Types
1. Command-Based Hooks
Execute bash scripts with full shell capabilities.
Configuration:
{
"type": "command",
"command": "jq -r '.tool_parameters.command' | tee -a .claude/commands.log"
}Input: JSON via stdin with fields:
session_id: Current session identifiertranscript_path: Path to session transcriptcwd: Current working directorypermission_mode: Current permission settinghook_event_name: Triggering event name- Event-specific fields (varies by hook)
Output Control:
- Exit code 0: Success, continue execution
- Exit code 2: Blocking error, halt execution
- Optional JSON output:
{
"continue": false,
"stopReason": "Reason for blocking",
"decision": {}
}2. Prompt-Based Hooks
Leverage LLM evaluation for context-aware decisions.
Supported Events: Stop, SubagentStop only
Configuration:
{
"type": "prompt",
"prompt": "Analyze the session transcript and determine if...",
"model": "sonnet"
}Output: Structured JSON response based on LLM evaluation
Common Use Cases
Auto-Formatting (PostToolUse)
Automatically format code after edits.
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "FILE=$(echo \"$INPUT\" | jq -r '.tool_parameters.file_path'); case \"$FILE\" in *.ts|*.js) npx prettier --write \"$FILE\" ;; *.go) gofmt -w \"$FILE\" ;; esac"
}
]
}
]
}
}Script version (scripts/format-code.sh):
#!/bin/bash
FILE=$(jq -r '.tool_parameters.file_path')
case "$FILE" in
*.ts|*.tsx|*.js|*.jsx)
npx prettier --write "$FILE"
;;
*.go)
gofmt -w "$FILE"
;;
*.py)
black "$FILE"
;;
esacFile Protection (PreToolUse)
Block modifications to sensitive files.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "FILE=$(echo \"$INPUT\" | jq -r '.tool_parameters.file_path'); case \"$FILE\" in .env|*package-lock.json|.git/*) echo '{\"continue\":false,\"stopReason\":\"Protected file\"}'; exit 2 ;; esac"
}
]
}
]
}
}Desktop Notifications (Notification)
Custom alerts when Claude needs input.
{
"hooks": {
"Notification": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "MESSAGE=$(jq -r '.message'); notify-send 'Claude Code' \"$MESSAGE\""
}
]
}
]
}
}Command Logger (PreToolUse)
Track bash commands for compliance.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_parameters | \"\\(.command) - \\(.description)\"' >> .claude/commands.log"
}
]
}
]
}
}Markdown Enhancement (PostToolUse)
Auto-detect code block languages.
````bash #!/usr/bin/env python3
scripts/enhance-markdown.py
import json, sys, re
data = json.load(sys.stdin) file_path = data['tool_parameters']['file_path']
if not file_path.endswith('.md'): sys.exit(0)
with open(file_path, 'r') as f: content = f.read()
Detect unlabeled code blocks and add language tags
enhanced = re.sub( r'``\n((?:import|function|const|let|var|class)\b.*?)`', r'`javascript\n\1``', content, flags=re.DOTALL )
with open(file_path, 'w') as f: f.write(enhanced) ````
Configuration:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "python3 scripts/enhance-markdown.py"
}
]
}
]
}
}Environment Variables
Available in all hooks:
$CLAUDE_PROJECT_DIR: Project root path${CLAUDE_PLUGIN_ROOT}: Plugin directory path
SessionStart only:
CLAUDE_ENV_FILE: Persist environment variables across session
Hook input via stdin: All data passed as JSON (parse with jq)
Security Framework
Critical Considerations
- Users assume full responsibility for hook commands
- Hooks execute with user's environment credentials
- Malicious hooks can exfiltrate data
Best Practices
Input Validation:
# Validate file paths
FILE=$(jq -r '.tool_parameters.file_path')
if [[ ! "$FILE" =~ ^[a-zA-Z0-9/_.-]+$ ]]; then
echo '{"continue":false,"stopReason":"Invalid path"}' && exit 2
fiProper Quoting:
# Always quote variables
FILE=$(jq -r '.tool_parameters.file_path')
prettier --write "$FILE" # Correct
prettier --write $FILE # Wrong - vulnerable to injectionPath Traversal Prevention:
# Use absolute paths and validate
REALPATH=$(realpath "$FILE")
if [[ ! "$REALPATH" =~ ^"$CLAUDE_PROJECT_DIR" ]]; then
echo '{"continue":false,"stopReason":"Path outside project"}' && exit 2
fiCommand Whitelisting:
# Whitelist allowed commands
COMMAND=$(jq -r '.tool_parameters.command')
case "$COMMAND" in
npm\ install|npm\ test|npm\ run\ *)
# Allowed
;;
*)
echo '{"continue":false,"stopReason":"Command not allowed"}' && exit 2
;;
esacHook Management
Setup via /hooks Command
claude
> /hooksInteractive setup wizard for hook configuration.
Manual Configuration
Edit .claude/settings.json or .claude/settings.local.json:
{
"hooks": {
"PreToolUse": [...],
"PostToolUse": [...]
}
}Testing Hooks
# Enable debug mode
claude --debug
# Test hook with sample input
echo '{"session_id":"test","tool_parameters":{"command":"ls"}}' | bash scripts/test-hook.shDebugging
Check logs:
cat .claude/logs/hooks.logCommon issues:
- Verify script permissions:
chmod +x scripts/*.sh - Check JSON syntax in settings
- Validate script paths (relative to project root)
- Test stdin parsing:
echo '{}' | jq
Plugin Integration
Hooks can be bundled in plugins for distribution.
Plugin structure:
my-plugin/
├── plugin.json
├── hooks/
│ └── settings.json # Hook configurations
└── scripts/
└── hook-script.shplugin.json:
{
"name": "my-plugin",
"version": "1.0.0",
"description": "Plugin with hooks",
"hooks": "hooks/settings.json"
}hooks/settings.json:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/hook-script.sh"
}
]
}
]
}
}Advanced Patterns
Conditional Execution
#!/bin/bash
# Only run in production branch
BRANCH=$(git branch --show-current)
if [[ "$BRANCH" == "main" ]]; then
# Execute hook logic
echo "Running on production"
fiMulti-step Processing
#!/bin/bash
FILE=$(jq -r '.tool_parameters.file_path')
# Step 1: Format
prettier --write "$FILE"
# Step 2: Lint
eslint --fix "$FILE"
# Step 3: Test
npm test -- "$FILE"Notification Integration
#!/bin/bash
# Slack webhook notification
MESSAGE=$(jq -r '.message')
curl -X POST "$SLACK_WEBHOOK_URL" \
-H 'Content-Type: application/json' \
-d "{\"text\":\"$MESSAGE\"}"Error Handling
#!/bin/bash
set -euo pipefail
FILE=$(jq -r '.tool_parameters.file_path')
# Validate file exists
if [[ ! -f "$FILE" ]]; then
echo '{"continue":false,"stopReason":"File not found"}' >&2
exit 2
fi
# Process file
prettier --write "$FILE" || {
echo '{"continue":false,"stopReason":"Format failed"}' >&2
exit 2
}Performance Considerations
Keep hooks fast: <100ms execution time ideal
Async operations:
#!/bin/bash
# Run in background for long operations
{
# Long-running task
npm run build
} &Caching:
#!/bin/bash
CACHE_FILE=".claude/cache/format-cache"
FILE_HASH=$(md5sum "$FILE" | cut -d' ' -f1)
# Check cache
if grep -q "$FILE_HASH" "$CACHE_FILE" 2>/dev/null; then
echo "Using cached result" >&2
exit 0
fi
# Process and cache
prettier --write "$FILE"
echo "$FILE_HASH" >> "$CACHE_FILE"Example: Complete Hook System
File: .claude/settings.json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "bash .claude/scripts/validate-bash.sh"
}
]
},
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "bash .claude/scripts/protect-files.sh"
}
]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "bash .claude/scripts/auto-format.sh"
}
]
}
],
"Notification": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "bash .claude/scripts/desktop-notify.sh"
}
]
}
],
"UserPromptSubmit": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "bash .claude/scripts/log-usage.sh"
}
]
}
],
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Review the session and log key accomplishments.",
"model": "sonnet"
}
]
}
]
}
}Reference Links
- Hooks Guide: https://code.claude.com/docs/en/hooks-guide
- Hooks API Reference: https://code.claude.com/docs/en/hooks
- Settings Configuration: https://code.claude.com/docs/en/settings
- Plugins Reference: https://code.claude.com/docs/en/plugins-reference
- GitHub Examples: https://github.com/anthropics/claude-code/tree/main/examples/hooks
See Also
- Settings:
references/configuration.md - Plugins:
references/hooks-and-plugins.md(plugin-specific) - MCP Integration:
references/mcp-integration.md - Security 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": "sonnet",
"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/skills"],
"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: sonnet
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="sonnet" />
<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 repository 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
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": "{database-url}"
}
}
}
}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
Configured 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={database-url}
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
Slash Commands Reference
Comprehensive catalog of Claude Code slash commands for development workflows.
What Are Slash Commands?
Slash commands are user-defined operations that:
- Start with
/(e.g.,$cook,$test) - Expand to full prompts when executed
- Accept arguments
- Located in
.claude/skills/(previously.claude/commands/) - Can be project-specific or global
Development Commands
$cook [task]
Implement features step by step.
$cook implement user authentication with JWT
$cook add payment integration with StripeWhen to use: Feature implementation with iterative development
$plan [task]
Research, analyze, and create implementation plans.
$plan implement OAuth2 authentication
$plan migrate from one database engine to anotherWhen to use: Before starting complex implementations
$debug-investigate [issue]
Debug technical issues and provide solutions.
$debug-investigate the API returns 500 errors intermittently
$debug-investigate authentication flow not workingWhen to use: Investigating and diagnosing problems
$test
Run test suite.
$testWhen to use: Validate implementations, check for regressions
/refactor [target]
Improve code quality.
/refactor the authentication module
/refactor for better performanceWhen to use: Code quality improvements
Fix Commands
$fix:fast [issue]
Quick fixes for small issues.
$fix:fast the login button is not working
$fix:fast typo in error messageWhen to use: Simple, straightforward fixes
$fix:hard [issue]
Complex issues requiring planning and subagents.
$fix:hard database connection pooling issues
$fix:hard race condition in payment processingWhen to use: Complex bugs requiring deep investigation
$fix:types
Fix TypeScript type errors.
$fix:typesWhen to use: TypeScript compilation errors
$fix:test [issue]
Fix test failures.
$fix:test the user service tests are failing
$fix:test integration tests timing outWhen to use: Test suite failures
$fix:ui [issue]
Fix UI issues.
$fix:ui button alignment on mobile
$fix:ui dark mode colors inconsistentWhen to use: Visual or interaction issues
$fix:ci [url]
Analyze GitHub Actions logs and fix CI/CD issues.
$fix:ci https://github.com/owner/repo/actions/runs/123456When to use: Build or deployment failures
$fix:logs [issue]
Analyze logs and fix issues.
$fix:logs server error logs showing memory leaksWhen to use: Production issues with log evidence
Documentation Commands
/docs:init
Create initial documentation structure.
/docs:initWhen to use: New projects needing documentation
/docs:update
Update existing documentation based on code changes.
/docs:updateWhen to use: After significant code changes
/docs:summarize
Summarize codebase and create overview.
/docs:summarizeWhen to use: Generate project summaries
Git Commands
/git:cm
Stage all files and create commit.
/git:cmWhen to use: Commit changes with automatic message
/git:cp
Stage, commit, and push all code in current branch.
/git:cpWhen to use: Commit and push in one command
/git:pr [branch] [from-branch]
Create pull request.
/git:pr feature-branch main
/git:pr bugfix-auth developWhen to use: Creating PRs with automatic descriptions
Planning Commands
$plan:two [task]
Create implementation plan with 2 alternative approaches.
$plan:two implement caching layerWhen to use: Need to evaluate multiple approaches
$plan:ci [url]
Analyze GitHub Actions logs and create fix plan.
$plan:ci https://github.com/owner/repo/actions/runs/123456When to use: CI/CD failure analysis
$plan:cro [issue]
Create conversion rate optimization plan.
$plan:cro landing page conversion improvementWhen to use: Marketing/conversion optimization
Content Commands
/content:fast [request]
Quick copy writing.
/content:fast write product description for new featureWhen to use: Fast content generation
/content:good [request]
High-quality, conversion-focused copy.
/content:good write landing page hero sectionWhen to use: Marketing copy requiring polish
/content:enhance [issue]
Enhance existing content.
/content:enhance improve clarity of pricing pageWhen to use: Improving existing copy
/content:cro [issue]
Conversion rate optimization for content.
/content:cro optimize email campaign copyWhen to use: Conversion-focused content improvements
Design Commands
$design:fast [task]
Quick design implementation.
$design:fast create dashboard layoutWhen to use: Rapid prototyping
$design:good [task]
High-quality, polished design.
$design:good create landing page for SaaS productWhen to use: Production-ready designs
$design:3d [task]
Create 3D designs with Three.js.
$design:3d create interactive 3D product viewerWhen to use: 3D visualization needs
$design:screenshot [path]
Create design based on screenshot.
$design:screenshot screenshot.pngWhen to use: Recreating designs from images
$design:video [path]
Create design based on video.
$design:video demo-video.mp4When to use: Implementing designs from video demos
Deployment Commands
/deploy
Deploy using deployment tool.
/deployWhen to use: Production deployments
/deploy-check
Check deployment readiness.
/deploy-checkWhen to use: Pre-deployment validation
Integration Commands
/payment-integration [tasks]
Implement payment integrations (SePay, Polar, etc.).
/payment-integration add Vietnamese payment gatewayWhen to use: Payment gateway integration
Other Commands
$brainstorm [question]
Brainstorm features and ideas.
$brainstorm how to improve user onboardingWhen to use: Ideation and exploration
$ask [question]
Answer technical and architectural questions.
$ask what's the best way to handle websocket connectionsWhen to use: Technical guidance
$scout [prompt] [scale]
Scout directories to respond to requests.
$scout find authentication codeWhen to use: Code exploration
$watzup
Review recent changes and wrap up work.
$watzupWhen to use: End of session summary
/bootstrap [requirements]
Bootstrap new project step by step.
/bootstrap create React app with TypeScript and TailwindWhen to use: New project setup
/bootstrap:auto [requirements]
Bootstrap new project automatically.
/bootstrap:auto create Next.js appWhen to use: Automated project setup
$journal
Write journal entries for development log.
$journalWhen to use: Development documentation
/review:codebase [prompt]
Scan and analyze codebase.
/review:codebase analyze architecture patternsWhen to use: Codebase analysis
/skill:create [prompt]
Create new agent skill.
/skill:create create skill for API testingWhen to use: Extending Claude with custom skills
Creating Custom Slash Commands
Skill File Structure
.claude/skills/
└── my-skill/
└── SKILL.mdExample Skill File
# File: .claude/skills/my-skill/SKILL.md
Create comprehensive test suite for {{feature}}.
Include:
- Unit tests
- Integration tests
- Edge cases
- Mocking examplesUsage
/my-command authentication
# Expands to: "Create comprehensive test suite for authentication..."Best Practices
Clear prompts: Write specific, actionable prompts Use variables: {{variable}} for dynamic content Document usage: Add comments explaining the command Test thoroughly: Verify commands work as expected
Command Arguments
Single Argument
$cook implement user auth
# Argument: "implement user auth"Multiple Arguments
/git:pr feature-branch main
# Arguments: "feature-branch", "main"Optional Arguments
Some commands work with or without arguments:
$test # Run all tests
$test user.test.js # Run specific testSee Also
- Creating custom commands:
references/hooks-and-plugins.md - Command automation:
references/configuration.md - Best practices:
references/best-practices.md