The Complete Claude Code CLI Guide - Live & Auto-Updated Every 2 Days
Shell
2,867
46 commits
updated Jul 27, 2026
Quick Links: Get Started · Commands · MCP Setup · Settings · SDK · Changelog
🔄 Live Guide: Auto-updated every 2 days from official docs, GitHub releases, and Anthropic changelog. See update-log.md.
🤖 For AI Agents: Optimized for both humans and AI.
[OFFICIAL]= from code.claude.com.[COMMUNITY]= observed patterns.[EXPERIMENTAL]= unverified.
Claude Code is an agentic AI coding assistant that lives in your terminal. It understands your codebase, edits files directly, runs commands, and helps you code faster through natural language conversation.
Key Capabilities:
Installation:
# Quick Install (macOS, Linux, WSL)
curl -fsSL https://claude.ai/install.sh | bash
# Windows PowerShell
irm https://claude.ai/install.ps1 | iex
# Windows CMD
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
# Alternative: Homebrew (macOS/Linux)
brew install --cask claude-code
# Alternative: WinGet (Windows)
winget install Anthropic.ClaudeCode
# Alternative: NPM (⚠️ Deprecated - use native install instead)
npm install -g @anthropic-ai/claude-code
claude --version # Verify installation
Official Documentation: https://code.claude.com/docs/en/overview
# Starting Claude Code
claude # Start interactive session
claude -p "task" # Print mode (non-interactive)
claude --continue # Continue last session
claude --resume <id> # Resume specific session
# Session Management
/help # Show available commands
/exit # End session
/compact # Reduce context size
/compact [instructions] # Compact conversation with optional focus instructions
# Background Tasks
/bashes # List background processes
/kill <id> # Stop background process
# Discovery
/commands # List skills and commands
/hooks # Show configured hooks
/skills # List available Skills (NEW)
/plugin # Manage plugins
Source: CLI Reference
# Output Control
claude -p, --print "task" # Print mode: non-interactive, prints result and exits
claude --output-format json # Output format: text, json, or stream-json
claude --input-format text # Input format: text or stream-json
claude --verbose # Enable verbose logging (full turn-by-turn output)
# Session Management
claude --continue # Continue from last session
claude --resume <session-id> # Resume specific session by ID or name
claude --from-pr <pr> # Resume session linked to GitHub PR number or URL [NEW]
claude --fork-session # Create new session ID instead of reusing original
claude --session-id <uuid> # Use specific session ID (must be valid UUID)
# Remote Sessions (claude.ai subscribers)
claude --remote "task" # Create web session on claude.ai
claude --teleport # Resume web session in local terminal
claude --remote-control # Bridge this session to claude.ai/code (mobile/web)
claude --channels # Allow MCP servers to push messages in (research preview) [NEW]
# Background Sessions & Agent View [NEW]
claude agents # Open the agent view: every session, running/blocked/done
claude agents --json # List live sessions as JSON (add --all for completed)
claude agents --cwd <path> # Scope the session list to a directory
claude --bg "task" # Start the session in the background
claude --bg --exec '<command>' # Run a shell command as an attachable background session
claude --bg --name <label> # Name the background session
claude attach <id> # Attach to a background session
claude logs <id> # Show a background session's output
claude stop <id> / claude rm <id> # Stop or remove a background session
claude respawn <id> # Restart a stopped background session
claude daemon status # Inspect the background-session daemon
# Debugging & Logging
claude --debug # Enable debug mode (with optional category filtering)
claude --debug "api,mcp" # Debug specific categories
claude --debug "!statsig,!file" # Exclude categories with !
# Model & Agent Configuration
claude --model <name> # Specify model (sonnet, opus, haiku, or full name)
claude --fallback-model <name> # Fallback model when overloaded (interactive too, v2.1.166)
claude --effort high # Set reasoning effort (low/medium/high/xhigh/max/ultracode) [NEW]
claude --agent <name> # Specify custom agent (overrides settings)
claude --agents '<json>' # Define custom subagents dynamically via JSON
claude --forward-subagent-text # Include subagent text/thinking in stream-json output [NEW]
# System Prompt Customization
claude --system-prompt "prompt" # Replace entire default system prompt
claude --system-prompt-file <path> # Replace with file contents (print mode only)
claude --append-system-prompt "..." # Append to default system prompt
claude --append-system-prompt-file <path> # Append file contents (print mode only)
# Tool & Permission Management
claude --tools "Bash,Read,Edit" # Restrict built-in tools (use "" to disable all)
claude --allowedTools "Bash(git:*)" # Tools that execute without prompting
claude --disallowedTools "Edit" # Tools removed from context
claude --permission-mode plan # Begin in specified permission mode
claude --permission-mode manual # "default" mode renamed to "manual" in v2.1.200 [NEW]
claude --dangerously-skip-permissions # Skip all permission prompts ⚠️
claude --allow-dangerously-skip-permissions # Enable bypass option without activating [NEW]
claude --permission-prompt-tool <mcp-tool> # MCP tool for permission prompts (non-interactive) [NEW]
# Budget & Execution Limits (print mode)
claude --max-budget-usd 5.00 # Maximum dollar amount for API calls
claude --max-turns 3 # Limit number of agentic turns
claude --json-schema '<schema>' # Get validated JSON output matching schema (print mode) [NEW]
# Directory & Configuration
claude --add-dir ../apps ../lib # Add additional working directories
claude --plugin-dir ./my-plugins # Load plugins from a directory or .zip (repeat for more)
claude --plugin-url <url> # Fetch a plugin .zip archive from a URL for this session [NEW]
claude --worktree, -w <name> # Run the session in an isolated git worktree
claude --settings ./settings.json # Path to settings JSON file
claude --setting-sources user,project # Comma-separated list of setting sources [NEW]
claude --mcp-config ./mcp.json # Load MCP servers from JSON file
claude --strict-mcp-config # Only use MCP servers from --mcp-config
# IDE & Browser Integration
claude --ide # Auto-connect to IDE on startup
claude --chrome # Enable Chrome browser integration
claude --no-chrome # Disable Chrome browser integration
# Agent Teams [NEW]
claude --teammate-mode in-process # Teammates display in main terminal
claude --teammate-mode tmux # Each teammate in own pane (requires tmux/iTerm2)
claude --teammate-mode auto # Auto-detect (default)
# Setup & Maintenance
claude --init # Run Setup hooks and start interactive mode
claude --init-only # Run Setup hooks and exit (no interactive session)
claude --maintenance # Run Setup hooks with maintenance trigger and exit
# Troubleshooting & Accessibility [NEW]
claude --safe-mode # Start with CLAUDE.md, plugins, skills, hooks, MCP disabled
claude --bare # Minimal scripted -p runs (no hooks/LSP/plugin sync)
claude --ax-screen-reader # Opt-in plain-text rendering for screen readers
claude doctor # Full setup checkup that can diagnose and fix issues
# Other Options
claude -n, --name <name> # Set a display name for the session at startup [NEW]
claude --disable-slash-commands # Disable all skills and slash commands
claude --no-session-persistence # Disable session persistence (print mode)
claude --betas interleaved-thinking # Beta headers for API requests
claude --include-partial-messages # Include partial streaming events (with stream-json) [NEW]
claude --exclude-dynamic-system-prompt-sections # Better cross-user prompt caching (print) [NEW]
# Subcommands
claude auth login|status|logout # Manage authentication (--console for API billing)
claude mcp login|logout <name> # Authenticate an MCP server without opening /mcp
claude plugin init|list|details|prune|tag # Plugin authoring and maintenance
claude project purge [path] # Delete all Claude Code state for a project [NEW]
claude auto-mode reset # Restore the default auto-mode configuration [NEW]
Common Flag Combinations:
# One-off task with JSON output
claude --print "analyze this code" --output-format json
# Debug MCP and API issues
claude --debug "api,mcp"
# Resume session with specific model
claude --resume auth-refactor --model opus
# Non-interactive with budget limit (CI/CD)
claude -p --max-budget-usd 5.00 --output-format json "run tests"
# Custom subagents for specialized work
claude --agents '{"reviewer":{"description":"Code reviewer","prompt":"Review for bugs"}}'
# Remote session for claude.ai subscribers
claude --remote "fix the login bug"
Source: CLI Reference
| Tool | Purpose | Permission Required |
|---|---|---|
| Read | Read files, images, PDFs | No |
| Write | Create new files | Yes |
| Edit | Modify existing files | Yes |
| Bash | Execute shell commands | Yes |
| Grep | Search content with regex | No |
| Glob | Find files by pattern | No |
| TodoWrite | Task management | No |
| Task | Launch sub-agents | No |
| WebFetch | Fetch web content | Yes |
| WebSearch | Search the web | Yes |
| NotebookEdit | Edit Jupyter notebooks | Yes |
| NotebookRead | Read Jupyter notebooks | No |
Source: Settings Reference
Claude Code operates through a conversational interface in your terminal:
# You describe what you want
$ claude
> "Add user authentication to the API"
# Claude Code:
1. Analyzes your codebase structure
2. Plans the implementation
3. Requests permission for file edits (first time)
4. Writes code directly to your files
5. Can run tests and verify changes
6. Creates git commits if requested
Key Principles:
Source: Overview
Claude Code uses an incremental permission system for safety:
# Permission Rules — three buckets, each an ARRAY of "Tool(specifier)" strings
"allow" # Permit without asking
"ask" # Prompt before each use
"deny" # Block completely
# Permission Modes — the starting behavior, set with permissions.defaultMode
"default" # Prompt on first use of each tool (alias: "manual")
"acceptEdits" # Auto-accept file edits and common filesystem commands
"plan" # Explore read-only; no source edits
"auto" # Auto-approve with background safety checks
"dontAsk" # Auto-deny anything not pre-approved
"bypassPermissions" # Skip prompts entirely (isolated environments only)
# NOTE: rule buckets and modes are different things. There is no "ask" MODE.
# To prompt before acting, stay in "default" mode and add ask RULES:
# { "defaultMode": "default", "ask": ["Bash", "Edit"] }
# Permission Priority [NEW v2.1.27]
# Content-level rules override tool-level rules
# Example: allow: ["Bash"], ask: ["Bash(rm *)"]
# -> Bash is generally allowed, but "rm *" commands require confirmation
# Tools Requiring Permission
- Bash (command execution)
- Write/Edit/NotebookEdit (file modifications)
- WebFetch/WebSearch (network access)
- Skill (skills and custom commands)
# Tools Not Requiring Permission (Safe Operations)
- Read/NotebookRead (reading files)
- Grep/Glob (searching)
- TodoWrite (task tracking)
- Task (sub-agents)
Configuring Permissions:
Create .claude/settings.json in your project or ~/.claude/settings.json globally:
{
"permissions": {
"defaultMode": "default",
"allow": [
"Bash(git status)",
"Bash(git diff)",
"Bash(git log *)",
"Bash(npm test)",
"Bash(npm run *)",
"Read",
"Edit"
],
"deny": [
"Read(*.env)",
"Read(.env.*)",
"Edit(*.env)",
"Edit(.env.*)",
"Edit(.git/**)"
],
"additionalDirectories": [
"/path/to/other/project"
]
}
}
Rule syntax gotchas:
allow / ask / deny are arrays of "Tool(specifier)" strings, never objects keyed by tool name. An object such as "deny": { "Write": ["*.env"] } is silently ignored."Read" allows all reads.Edit(path), not Write(path). File permission checks match only Edit(path) and Read(path) rules; Write(path), NotebookEdit(path), and Glob(path) rules are accepted but never matched, and warn at startup (v2.1.210+). Edit rules cover all file-editing tools.* matters: Bash(npm run *) matches npm run build but not npm runfoo, while Bash(npm run*) matches both.Read and Edit specifiers use gitignore syntax; a bare filename matches at any depth, so Read(.env) and Read(**/.env) are equivalent.Read(...) and Edit(...) — denying edits alone still lets Claude read the file.Source: Permissions, Settings
A CLAUDE.md file in your project root provides persistent context across sessions:
# Project: My Application
## Critical Context (Read First)
- Language: TypeScript + Node.js
- Framework: Express + React
- Database: PostgreSQL with Prisma ORM
- Testing: Jest + React Testing Library
## Commands That Work
npm run dev # Start dev server (port 3000)
npm test # Run all tests
npm run lint # ESLint check
npm run typecheck # TypeScript validation
npm run db:migrate # Run Prisma migrations
## Important Patterns
- All API routes in /src/routes - RESTful structure
- Database queries use Prisma Client
- Auth uses JWT tokens (implementation in /src/auth)
- Frontend components in /src/components
- API responses: {success: boolean, data: any, error?: string}
## Gotchas & What NOT to Do
- DON'T modify /generated folder (auto-generated by Prisma)
- DON'T commit .env files (use .env.example instead)
- ALWAYS run npm run db:migrate after pulling schema changes
- DON'T use `any` type in TypeScript - use proper typing
## File Structure
/src
/routes # Express API routes
/services # Business logic
/models # Type definitions
/middleware # Express middleware
/utils # Shared utilities
/auth # Authentication logic
## Recent Learnings
- [2026-01-15] Payment webhook needs raw body parser for Stripe
- [2026-01-10] Redis pool: {maxRetriesPerRequest: 3}
Why CLAUDE.md Helps:
Note: While CLAUDE.md is not an official feature, it's a widely-adopted community pattern. Claude Code will automatically read it if present at project root.
Purpose: Read and analyze files
# Examples
Read file_path="/src/app.ts"
Read file_path="/docs/screenshot.png" # Can read images!
Read file_path="/docs/guide.pdf" # Can read PDFs!
Read file_path="/docs/guide.pdf" pages="1-5" # Read specific PDF pages [NEW v2.1.30]
Capabilities:
cat -n format)PDF Parameters [NEW v2.1.30]:
pages: Optional page range (e.g., "1-5", "1,3,5") to read specific pagesSpecial Features:
Purpose: Create new files
Write file_path="/src/newFile.ts"
content="export const config = {...}"
Behavior:
Best Practice: Use Edit tool for modifying existing files, Write tool only for new files.
Purpose: Modify existing files with precise string replacement
Edit file_path="/src/app.ts"
old_string="const port = 3000"
new_string="const port = process.env.PORT || 3000"
Important:
old_string is not unique in file (use larger context or replace_all)replace_all=true to replace all occurrences (useful for renaming)Common Pattern:
# 1. Read file to see exact content
Read file_path="/src/app.ts"
# 2. Edit with exact string match
Edit file_path="/src/app.ts"
old_string="function login() {
return 'TODO';
}"
new_string="function login() {
return authenticateUser();
}"
Purpose: Execute shell commands
Bash command="npm test"
Bash command="git status"
Bash command="find . -name '*.test.ts'"
Features:
run_in_background=true)Security:
Common Git Patterns:
# Check status
Bash command="git status"
# View changes
Bash command="git diff"
# Create commit
Bash command='git add . && git commit -m "feat: add authentication"'
# View history
Bash command="git log --oneline -10"
Purpose: Search file contents with regex patterns
# Find functions
Grep pattern="function.*auth" path="src/" output_mode="content"
# Find TODOs with context
Grep pattern="TODO" output_mode="content" -C=3
# Count occurrences
Grep pattern="import.*from" output_mode="count"
# Case insensitive
Grep pattern="error" -i=true output_mode="files_with_matches"
Parameters:
pattern: Regex pattern (ripgrep syntax)path: Directory or file to search (default: current directory)output_mode:
"files_with_matches" (default) - Just file paths"content" - Show matching lines"count" - Show match counts per file-A, -B, -C: Context lines (after, before, both)-i: Case insensitive-n: Show line numberstype: Filter by file type (e.g., "js", "py", "rust")glob: Filter by glob pattern (e.g., "*.test.ts")Fast and Powerful: Uses ripgrep under the hood, much faster than bash grep on large codebases.
Purpose: Find files by pattern
# Find test files
Glob pattern="**/*.test.ts"
# Find specific extensions
Glob pattern="src/**/*.{ts,tsx}"
# Find config files
Glob pattern="**/config.{json,yaml,yml}"
Features:
** for recursive, {} for alternatives)Purpose: Manage task lists during work
TodoWrite todos=[
{
"content": "Add authentication endpoint",
"status": "in_progress",
"activeForm": "Adding authentication endpoint"
},
{
"content": "Write integration tests",
"status": "pending",
"activeForm": "Writing integration tests"
},
{
"content": "Update API documentation",
"status": "pending",
"activeForm": "Updating API documentation"
}
]
Task States:
"pending" - Not started yet"in_progress" - Currently working on (should be only ONE at a time)"completed" - Finished successfullyDependency Tracking [NEW]: v2.1.16 introduced task dependency tracking, allowing tasks to define prerequisites that must complete before they start. This enables complex multi-step workflows with proper sequencing.
Best Practices:
in_progress at a timecontent (what to do) and activeForm (what you're doing)When to Use:
Purpose: Launch specialized AI agents for specific tasks
# Explore codebase
Task subagent_type="Explore"
prompt="Find all API endpoints and their authentication requirements"
# General purpose agent for complex tasks
Task subagent_type="general-purpose"
prompt="Research best practices for rate limiting APIs and implement a solution"
Available Sub-Agent Types:
"general-purpose" - Complex multi-step tasks, research, implementation"Explore" - Fast codebase exploration (Glob, Grep, Read, Bash)When to Use:
Purpose: Fetch and analyze web page content
WebFetch url="https://docs.example.com/api"
prompt="Extract all endpoint documentation"
Features:
Purpose: Search the web for current information
WebSearch query="React 19 new features 2024"
Use Cases:
Source: CLI Reference, Settings
Purpose: Get code intelligence features like go-to-definition, find references, and hover documentation.
LSP operation="goToDefinition"
filePath="src/utils/auth.ts"
line=42
character=15
Available Operations:
| Operation | Description |
|---|---|
goToDefinition | Find where a symbol is defined |
findReferences | Find all references to a symbol |
hover | Get documentation and type info for a symbol |
documentSymbol | Get all symbols in a document (functions, classes, variables) |
workspaceSymbol | Search for symbols across the entire workspace |
goToImplementation | Find implementations of an interface or abstract method |
prepareCallHierarchy | Get call hierarchy item at a position |
incomingCalls | Find all functions/methods that call the function at a position |
outgoingCalls | Find all functions/methods called by the function at a position |
Parameters:
operation (required): The LSP operation to performfilePath (required): Absolute or relative path to the fileline (required): Line number (1-based, as shown in editors)character (required): Character offset (1-based, as shown in editors)Use Cases:
# Find where a function is defined
> "Go to the definition of getUserById"
# Find all usages of a function
> "Find all references to the authenticate function"
# Get documentation for a symbol
> "What does the validateToken function do?"
# Explore code structure
> "List all symbols in the auth.ts file"
Note: LSP servers must be configured for the file type. If no server is available for a language, an error will be returned.
Source: CLI Reference
Claude Code maintains conversation context with smart management:
/compact # Reduce context by removing old information
/compact "keep auth work" # Compact with focus instructions (keeps specified context)
Use /compact when:
Use /compact with instructions when:
/compact "keep the authentication implementation context"Preserved:
Cleared:
Claude Code may automatically compact when:
Source: Settings
Claude Code can work with multiple directories simultaneously:
# Add another directory to current session
/add-dir /path/to/other/project
# Work across multiple projects
> "Update the User type in backend and propagate to frontend"
# Claude can now access both directories
Use Cases:
Configuration:
You can also pre-configure additional directories in .claude/settings.json:
{
"permissions": {
"additionalDirectories": [
"/path/to/frontend",
"/path/to/backend",
"/path/to/shared-libs"
]
}
}
Customize what information appears in your status line:
# Configure status line
/statusline
# Options typically include:
# - Current model
# - Token usage
# - Session duration
# - Active tools
# - Background processes
Benefits:
Source: CLI Reference
# 1. Navigate to your project
cd /path/to/your/project
# 2. Start Claude Code
claude
# 3. Ask Claude to understand your project
> "Read the codebase and explain the project structure"
# Claude will:
- Look for README, package.json, or similar entry points
- Read relevant files (asks permission first time)
- Analyze the code structure
- Provide a summary
# 4. Request an analysis
> "Review the authentication system for security issues"
# Claude will:
- Find authentication-related files
- Analyze the implementation
- Identify potential vulnerabilities
- Suggest improvements
# 5. Make changes
> "Add rate limiting to the login endpoint"
# Claude will:
- Plan the implementation
- Show you what changes will be made
- Request permission to edit files
- Implement the changes
- Can run tests to verify
# 6. Create a commit
> "Create a git commit for these changes"
# Claude will:
- Run git status to see changes
- Review git diff
- Create a descriptive commit message
- Commit the changes
This provides context that persists across all sessions:
# Ask Claude to help create it
> "Create a CLAUDE.md file documenting this project's structure, commands, and conventions"
# Or create manually with:
- Languages and frameworks used
- Important commands (dev, test, build, lint)
- Project structure overview
- Coding conventions
- Known gotchas or issues
Create .claude/settings.json in your project:
{
"permissions": {
"defaultMode": "default",
"allow": [
"Bash(npm test)",
"Bash(npm run *)",
"Bash(git status)",
"Bash(git diff)",
"Bash(git log *)",
"Read",
"Grep",
"Glob"
],
"deny": [
"Read(*.env)",
"Read(.env.*)",
"Edit(*.env)",
"Edit(.env.*)",
"Edit(.git/**)"
]
}
}
This configuration:
> "Run the tests"
# Should execute without permission prompt (if configured)
> "What commands are available?"
# Claude will read package.json and list scripts
> "What's in CLAUDE.md?"
# Claude will read and summarize your project context
Source: Quickstart, Settings
Claude Code supports extended thinking for complex reasoning tasks. Opus 4.5 has thinking mode enabled by default.
Activation Methods:
# Toggle with keyboard shortcut
Alt+T (or Option+T on macOS) # Toggle thinking on/off
# Or use natural language
> "think about this problem"
> "think harder about the architecture"
> "ultrathink about this security issue"
# Tab key (sticky toggle)
Press Tab to toggle thinking mode on/off for subsequent prompts
Thinking Levels:
| Trigger | Thinking Budget | Use Case |
|---|---|---|
think | Standard | General reasoning, code analysis |
think harder | Extended | Complex problems, multiple approaches |
ultrathink | Maximum | Critical decisions, deep architecture analysis |
Best Practices:
think harder for debugging complex issuesultrathink for architectural decisions or security reviewsCtrl+O transcript modeSource: Thinking Mode
Models added to Claude Code since v2.1.39, newest first. Switch with /model or --model.
| Model | Added | Notes |
|---|---|---|
Claude Opus 5 (claude-opus-5) | v2.1.219 (Jul 24, 2026) | Default Opus model. 1M context. Fast mode at $10/$50 per MTok |
| Claude Sonnet 5 | v2.1.197 (Jun 30, 2026) | Default model in Claude Code. Native 1M-token context. Promotional pricing of $2/$10 per MTok through August 31 |
| Claude Fable 5 | v2.1.170 (Jun 9, 2026) | Mythos-class model made safe for general use. Includes 1M context by default (no [1m] suffix needed) |
| Claude Opus 4.8 | v2.1.154 (May 28, 2026) | Defaults to high effort; /effort xhigh for the hardest tasks. Default Opus on Bedrock, Vertex, and Claude Platform on AWS since v2.1.207 |
| Claude Opus 4.7 | v2.1.111 (Apr 16, 2026) | Introduced the xhigh effort level. Native 1M context window |
| Claude Sonnet 4.6 | v2.1.45 (Feb 17, 2026) | Gained 1M context in v2.1.49 |
Removed / migrated:
Effort levels: /effort (added v2.1.76) accepts low, medium, high, xhigh, max, and ultracode, plus auto to reset to the model default. xhigh arrived in v2.1.111 and ultracode in v2.1.160; ultracode is a Claude Code setting rather than a model level — it sends xhigh and additionally orchestrates dynamic workflows, and it is session-only. max is also session-only unless set through CLAUDE_CODE_EFFORT_LEVEL, and the persisted effortLevel setting accepts only low, medium, high, and xhigh. Defaults have shifted several times — high for API-key/Bedrock/Vertex/Foundry/Team/Enterprise since v2.1.94, high for Pro/Max on Opus 4.6 and Sonnet 4.6 since v2.1.117, and high by default on Opus 4.8. Skills, slash commands, and agents can set effort: in frontmatter, and hooks receive effort.level / $CLAUDE_EFFORT.
Organization controls: admins can set an org default model (shown as "Org default" in /model, v2.1.196), restrict models with availableModels, and harden it with the enforceAvailableModels managed setting (v2.1.175).
Fast mode is a high-speed configuration that makes responses 2.5x faster at a higher cost per token. Available since v2.1.36.
Model support has moved. Fast mode launched on Opus 4.6, switched to Opus 4.7 by default in v2.1.142, added Opus 4.8 at a much lower premium in v2.1.154 (2x the standard rate for 2.5x the speed), and as of v2.1.219
/fastapplies to Opus 5 and Opus 4.8 — Opus 4.7 was removed from fast mode. Opus 5 fast mode is $10/$50 per MTok.CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDEwas deprecated in v2.1.154 and removed in v2.1.160. The pricing table below is the original Opus 4.6 launch pricing and is kept for historical reference.
Toggle Fast Mode:
# Toggle with built-in command
/fast # Toggle on/off
# Or set in settings
"fastMode": true # In user settings file
Visual Indicators:
↯ icon appears next to prompt when fast mode is activePricing (per MTok) — original Opus 4.6 launch pricing:
| Mode | Input (<200K) | Output | Input (>200K) | Output |
|---|---|---|---|---|
| Standard Opus 4.6 | $15 | $75 | $15 | $75 |
| Fast Mode | $30 | $150 | $60 | $225 |
Note: the Opus 4.6 fast-mode discount ran until February 16, 2026. Fast mode on Opus 4.8 is 2x the standard rate (v2.1.154), and Opus 5 fast mode is $10/$50 per MTok (v2.1.219).
Requirements:
/usage-credits, formerly /extra-usage)When to Use:
Fast Mode vs Effort Level:
| Setting | Effect |
|---|---|
| Fast mode | Same quality, lower latency, higher cost |
| Lower effort level | Faster responses, potentially lower quality |
You can combine both for maximum speed on straightforward tasks.
Rate Limits:
Source: Fast Mode
Plan Mode provides structured planning with model selection for complex tasks.
# Enter plan mode
/plan
# Or Claude may suggest plan mode for complex tasks
> "Implement a complete authentication system"
# Claude: "This is a complex task. Would you like me to create a plan first?"
Plan Mode Features:
/clearPlan Mode Workflow:
Source: Plan Mode
Run commands and agents in the background while continuing to work.
Keyboard Shortcut:
Ctrl+B # Background current command or agent (unified shortcut)
Background Commands:
# Start command in background
> "Run the dev server in background"
> "Start tests in watch mode in background"
# Or prefix with &
> "& npm run dev"
# View background tasks
/tasks
/bashes
# Kill a background task
/kill <task-id>
Background Agents:
# Launch agent in background
> "Have an Explore agent analyze the codebase architecture in background"
# Agents run asynchronously and notify you when complete
# You receive wake-up messages when background agents finish
Features:
Source: Background Tasks
Claude Code now automatically records and recalls memories as it works (v2.1.32+).
How It Works:
Memory Scopes for Agents:
---
name: my-agent
memory: project # Options: user, project, local
---
| Scope | Storage | Shared |
|---|---|---|
user | ~/.claude/ | All your projects |
project | .claude/ | Team via git |
local | .claude/*.local.* | No (gitignored) |
Disable Auto-Memory:
export CLAUDE_CODE_DISABLE_AUTO_MEMORY=1
Navigation & Editing:
| Shortcut | Action |
|---|---|
Ctrl+R | Search command history |
Ctrl+O | View transcript (shows thinking blocks) |
Ctrl+G | Edit prompt in system text editor |
Ctrl+Y | Readline-style paste (yank) |
Alt+Y | Yank-pop (cycle through kill ring) |
Ctrl+B | Background current command/agent |
Ctrl+Z | Suspend/Undo |
Model & Mode Switching:
| Shortcut | Action |
|---|---|
Alt+P (Win/Linux) / Option+P (macOS) | Switch models while typing |
Alt+T (Win/Linux) / Option+T (macOS) | Toggle thinking mode |
Tab | Toggle thinking (sticky) / Accept suggestions |
Shift+Tab | Auto-accept edits (plan mode) / Switch modes (Windows) |
Input & Submission:
| Shortcut | Action |
|---|---|
Enter | Submit prompt / Accept suggestion immediately |
Shift+Enter | New line (works in iTerm2, WezTerm, Ghostty, Kitty) |
Tab | Edit/accept prompt suggestion |
Ctrl+T | Toggle syntax highlighting in /theme |
Image & File Handling:
| Shortcut | Action |
|---|---|
Cmd+V (macOS) / Alt+V (Windows) | Paste image from clipboard |
Cmd+N / Ctrl+N | New conversation (VSCode) |
Vim Bindings (if enabled):
| Shortcut | Action |
|---|---|
; and , | Repeat last motion |
y | Yank operator |
p / P | Paste |
Alt+B / Alt+F | Word navigation |
Login & Authentication:
| Shortcut | Action |
|---|---|
c | Copy OAuth URL during login |
Bash Mode Autocomplete [NEW v2.1.14]:
| Shortcut | Action |
|---|---|
! + Tab | History-based autocomplete - complete partial commands from history |
Claude Code suggests prompts based on context (enabled by default).
# Claude suggests contextual prompts
> _ # Cursor blinking
# Suggestion appears: "Review the changes we made"
# Tab to edit the suggestion
Tab → Edit the suggestion text
# Enter to submit immediately
Enter → Submit the suggestion as-is
Configuration:
# Toggle in /config
/config
# Search for "prompt suggestions"
# Toggle enable/disable
Core Configuration:
| Variable | Description |
|---|---|
ANTHROPIC_API_KEY | Your API key |
CLAUDE_CODE_SHELL | Override shell detection |
CLAUDE_CODE_TMPDIR | Custom temp directory |
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS | Disable background task system |
CLAUDE_CODE_ENABLE_TASKS | Set to false to use legacy task system [NEW v2.1.19] |
CLAUDE_CODE_SAFE_MODE | Start with all customizations disabled (same as --safe-mode) [NEW v2.1.169] |
CLAUDE_CODE_SESSION_ID | Session ID exported to the Bash tool and stdio MCP servers [NEW v2.1.132] |
CLAUDE_CODE_DISABLE_BUNDLED_SKILLS | Hide bundled skills, workflows, and built-in slash commands [NEW v2.1.169] |
CLAUDE_CODE_PROCESS_WRAPPER | Run every Claude Code self-spawn through a wrapper executable [NEW v2.1.208] |
CLAUDE_CODE_DISABLE_CRON | Immediately stop scheduled cron jobs mid-session [NEW v2.1.72] |
Display & UI:
| Variable | Description |
|---|---|
CLAUDE_CODE_HIDE_ACCOUNT_INFO | Hide account info in UI |
CLAUDE_CODE_HIDE_CWD | Hide the working directory in the startup logo [NEW v2.1.119] |
CLAUDE_AX_SCREEN_READER | Set to 1 for screen reader mode (same as --ax-screen-reader) [NEW v2.1.208] |
CLAUDE_CODE_NO_FLICKER | Set to 1 for flicker-free alt-screen rendering [NEW v2.1.89] |
CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN | Set to 1 to keep the conversation in native scrollback [NEW v2.1.132] |
CLAUDE_CODE_FORCE_SYNC_OUTPUT | Force synchronized output where auto-detection misses it [NEW v2.1.129] |
CLAUDE_CODE_DISABLE_MOUSE | Disable mouse handling in fullscreen mode |
CLAUDE_CODE_DISABLE_MOUSE_CLICKS | Disable click/drag/hover but keep wheel scroll [NEW v2.1.195] |
CLAUDE_CODE_DISABLE_TERMINAL_TITLE | Don't set the terminal title |
Bash & Commands:
| Variable | Description |
|---|---|
BASH_DEFAULT_TIMEOUT_MS | Default bash command timeout |
BASH_MAX_TIMEOUT_MS | Maximum allowed timeout |
CLAUDE_BASH_NO_LOGIN | Don't use login shell |
CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR | Keep working directory |
CLAUDE_CODE_SHELL_PREFIX | Prefix for shell commands |
Model Configuration:
| Variable | Description |
|---|---|
ANTHROPIC_DEFAULT_SONNET_MODEL | Override default Sonnet model |
ANTHROPIC_DEFAULT_OPUS_MODEL | Override default Opus model |
ANTHROPIC_DEFAULT_HAIKU_MODEL | Override default Haiku model |
ANTHROPIC_DEFAULT_{OPUS,SONNET,HAIKU}_MODEL_SUPPORTS | Override effort/thinking capability detection for pinned 3P models [NEW v2.1.84] |
ANTHROPIC_DEFAULT_{...}_MODEL_NAME / _DESCRIPTION | Customize the /model picker label for pinned models [NEW v2.1.84] |
ANTHROPIC_CUSTOM_MODEL_OPTION | Add a custom entry to the /model picker [NEW v2.1.78] |
ANTHROPIC_BEDROCK_SERVICE_TIER | Bedrock service tier: default, flex, or priority [NEW v2.1.122] |
ANTHROPIC_WORKSPACE_ID | Scope a federated token to a specific workspace [NEW v2.1.141] |
CLAUDE_CODE_USE_MANTLE | Set to 1 for Amazon Bedrock powered by Mantle [NEW v2.1.94] |
CLAUDE_CODE_DISABLE_1M_CONTEXT | Disable 1M context window support [NEW v2.1.50] |
CLAUDE_CODE_ENABLE_AUTO_MODE | Opt into auto mode on Bedrock/Vertex/Foundry [NEW v2.1.158] |
CLAUDE_CODE_EFFORT_LEVEL | Override the reasoning effort level |
ANTHROPIC_LOG | Enable debug logging |
MCP Configuration:
| Variable | Description |
|---|---|
MCP_TIMEOUT | MCP connection timeout |
MCP_TOOL_TIMEOUT | Individual tool timeout |
MCP_CONNECTION_NONBLOCKING | true skips the MCP connection wait in -p mode [NEW v2.1.89] |
CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT | Abort remote MCP tool calls that hang (default 5 min) [NEW v2.1.187] |
CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS | Threshold before long MCP calls move to the background [NEW v2.1.212] |
CLAUDE_CODE_MCP_SERVER_NAME / _URL | Passed to MCP headersHelper scripts [NEW v2.1.85] |
ENABLE_CLAUDEAI_MCP_SERVERS | false opts out of claude.ai MCP servers [NEW v2.1.63] |
File & Context:
| Variable | Description |
|---|---|
CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS | Max tokens for file reads |
CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD | Set to 1 to load CLAUDE.md from --add-dir directories [NEW] |
CLAUDE_PROJECT_DIR | Override project directory |
CLAUDE_PLUGIN_ROOT | Plugin root substitution |
CLAUDE_CONFIG_DIR | Custom config directory |
XDG_CONFIG_HOME | XDG config base path |
Network & Proxy:
| Variable | Description |
|---|---|
NODE_EXTRA_CA_CERTS | Custom CA certificates |
NO_PROXY | Proxy bypass list |
CLAUDE_CODE_PROXY_RESOLVES_HOSTS | Proxy DNS resolution |
Auto-Update & Plugins:
| Variable | Description |
|---|---|
DISABLE_AUTOUPDATER | Disable auto-updates |
FORCE_AUTOUPDATE_PLUGINS | Force plugin updates |
CLAUDE_CODE_EXIT_AFTER_STOP_DELAY | Exit delay after stop |
Monitoring & Telemetry:
| Variable | Description |
|---|---|
CLAUDE_CODE_ENABLE_TELEMETRY | Enable OpenTelemetry collection (1) |
OTEL_METRICS_EXPORTER | OTel metrics exporter (e.g., otlp) |
DISABLE_TELEMETRY | Opt out of Statsig telemetry (1) |
DISABLE_ERROR_REPORTING | Opt out of Sentry error reporting (1) |
DISABLE_COST_WARNINGS | Disable cost warning messages (1) |
Advanced:
| Variable | Description |
|---|---|
CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS | Disable anthropic-beta headers (workaround for gateway users) |
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS | Enable agent teams feature (1) [NEW] |
CLAUDE_CODE_DISABLE_AUTO_MEMORY | Disable automatic memory recording (1) [NEW] |
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS | Disable background task system (1) |
DISABLE_INTERLEAVED_THINKING | Disable interleaved thinking |
USE_BUILTIN_RIPGREP | Use built-in ripgrep |
CLOUD_ML_REGION | Cloud ML region for Vertex |
AWS_BEARER_TOKEN_BEDROCK | AWS bearer token |
MAX_THINKING_TOKENS | Extended thinking budget (default: 31,999) |
MAX_MCP_OUTPUT_TOKENS | Max MCP tool response tokens (default: 25,000) |
CLAUDE_CODE_MAX_OUTPUT_TOKENS | Max output tokens (default: 32,000, max: 64,000) |
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC | Disable autoupdate, bug reporting, telemetry |
Subagents & Background Sessions: [NEW]
| Variable | Description |
|---|---|
CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS | Cap on subagents running at once (default 20) [v2.1.217] |
CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION | Cap on subagent spawns per session (default 200) [v2.1.212] |
CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH | Nested subagent depth (default 3 since v2.1.219; 1 disables nesting) |
CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION | Cap on WebSearch calls per session (default 200) [v2.1.212] |
CLAUDE_CODE_SUBAGENT_MODEL | Model used for subagents |
CLAUDE_CODE_FORK_SUBAGENT | Set to 1 to enable forked subagents on external builds [v2.1.117] |
CLAUDE_CODE_FORWARD_SUBAGENT_TEXT | Include subagent text/thinking in stream-json output [v2.1.211] |
CLAUDE_CODE_DISABLE_BG_SHELL_PRESSURE_REAP | Disable memory-pressure reaping of idle background shells [v2.1.193] |
Retries, Caching & Timeouts: [NEW]
| Variable | Description |
|---|---|
CLAUDE_CODE_MAX_RETRIES | Retry count (capped at 15 since v2.1.186) |
CLAUDE_CODE_RETRY_WATCHDOG | Raises the transient-error retry count to 300 for unattended sessions [v2.1.199] |
CLAUDE_ENABLE_STREAM_WATCHDOG | 0 disables the 5-minute stream idle watchdog [v2.1.196] |
CLAUDE_STREAM_IDLE_TIMEOUT_MS | Streaming idle watchdog threshold (default 90 s) [v2.1.84] |
ENABLE_PROMPT_CACHING_1H | Opt into 1-hour prompt cache TTL [v2.1.108] |
FORCE_PROMPT_CACHING_5M | Force 5-minute prompt cache TTL [v2.1.108] |
CLAUDE_CODE_STOP_HOOK_BLOCK_CAP | Consecutive Stop-hook blocks before the turn ends (default 8) [v2.1.143] |
CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS | SessionEnd hook timeout on exit [v2.1.74] |
Security & Enterprise: [NEW]
| Variable | Description |
|---|---|
CLAUDE_CODE_SUBPROCESS_ENV_SCRUB | Strip Anthropic and cloud credentials from subprocess environments [v2.1.83] |
CLAUDE_CODE_SCRIPT_CAPS | Limit per-session script invocations [v2.1.98] |
CLAUDE_CODE_CERT_STORE | bundled uses only bundled CAs instead of the OS trust store [v2.1.101] |
CLAUDE_CLIENT_PRESENCE_FILE | Marker file that suppresses mobile push while you're at the machine [v2.1.181] |
DISABLE_UPDATES | Block all update paths including manual claude update [v2.1.118] |
Windows & Shell: [NEW]
| Variable | Description |
|---|---|
CLAUDE_CODE_USE_POWERSHELL_TOOL | Opt in/out of the PowerShell tool [v2.1.111] |
CLAUDE_CODE_POWERSHELL_RESPECT_EXECUTION_POLICY | Don't pass -ExecutionPolicy Bypass [v2.1.143] |
CLAUDE_CODE_GIT_BASH_PATH | Path to Git Bash on Windows |
CLAUDE_CODE_PERFORCE_MODE | Fail on read-only files with a p4 edit hint instead of overwriting [v2.1.98] |
Telemetry (additions): [NEW]
| Variable | Description |
|---|---|
OTEL_LOG_ASSISTANT_RESPONSES | 1 un-redacts claude_code.assistant_response content; 0 keeps prompts-only [v2.1.193] |
OTEL_LOG_TOOL_DETAILS | Include tool parameters and custom command names in events [v2.1.85] |
OTEL_LOG_RAW_API_BODIES | Emit full API request/response bodies as OTel log events [v2.1.111] |
CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH | Truncation limit on OTel content attributes (default 60 KB) [v2.1.214] |
OTEL_METRICS_INCLUDE_ENTRYPOINT | Add the session entrypoint as a metric attribute [v2.1.152] |
Recent settings additions (configure in /config or settings.json):
{
// Response language
"language": "en", // Claude's response language
// Git integration
"attribution": true, // Add model name to commit bylines
"respectGitignore": true, // Respect .gitignore in searches
// UI preferences
"showTurnDuration": true, // Show turn duration messages
"fileSuggestion": "custom-cmd", // Custom @ file search command
"spinnerVerbs": ["analyzing", "thinking", "processing"], // Custom spinner verbs
"prefersReducedMotion": false, // Reduce UI animations for accessibility [NEW v2.1.30]
// Session behavior
"companyAnnouncements": true, // Show startup announcements
// Plan mode
"plansDirectory": ".claude/plans" // Custom directory for plan files
}
Settings Added Since v2.1.39 [NEW] [OFFICIAL]
| Setting | Description |
|---|---|
tui | Renderer mode; /tui fullscreen switches in-session [v2.1.110] |
autoScrollEnabled | Disable conversation auto-scroll in fullscreen mode [v2.1.110] |
showThinkingSummaries | true restores thinking summaries in interactive sessions [v2.1.89] |
axScreenReader | Opt-in plain-text rendering for screen readers [v2.1.208] |
wheelScrollAccelerationEnabled | Disable mouse-wheel scroll acceleration in fullscreen [v2.1.174] |
emojiCompletionEnabled | Toggle :shortcode: emoji autocomplete in the prompt [v2.1.217] |
vimInsertModeRemaps | Map two-key insert-mode sequences like jj to Escape [v2.1.208] |
footerLinksRegexes | Regex-matched link badges in the footer row [v2.1.176] |
prUrlTemplate | Point the footer PR badge at a custom code-review URL [v2.1.119] |
refreshInterval | Re-run the status line command every N seconds [v2.1.97] |
spinnerTipsOverride | Custom spinner tips (tips, excludeDefault) [v2.1.45] |
feedbackSurveyRate | Enterprise session-quality survey sample rate [v2.1.76] |
respondToBashCommands | false keeps ! bash output context-only [v2.1.186] |
showClearContextOnPlanAccept | Restore the "clear context" option on plan accept [v2.1.81] |
disableBundledSkills | Hide bundled skills, workflows, and built-in slash commands [v2.1.169] |
disableSkillShellExecution | Disable inline shell execution in skills and commands [v2.1.91] |
skillOverrides | off, user-invocable-only, or name-only per skill [v2.1.129] |
autoMemoryDirectory | Custom directory for auto-memory storage [v2.1.74] |
includeGitInstructions | Remove built-in commit/PR instructions from the system prompt [v2.1.69] |
attribution.sessionUrl | Omit the claude.ai session link from commits and PRs [v2.1.183] |
fallbackModel | Up to three fallback models tried in order [v2.1.166] |
modelOverrides | Map /model entries to custom provider model IDs (e.g. Bedrock ARNs) [v2.1.73] |
disableAutoMode | Turn auto mode off [v2.1.207] |
autoMode.classifyAllShell | Route all shell commands through the auto-mode classifier [v2.1.193] |
autoMode.hard_deny | Classifier rules that block unconditionally [v2.1.136] |
autoMode.allow / soft_deny / environment | Custom rules; include "$defaults" to keep built-ins [v2.1.118] |
worktree.baseRef | fresh (branch from origin/<default>) or head [v2.1.133] |
worktree.sparsePaths | Sparse-checkout paths for --worktree in monorepos [v2.1.76] |
worktree.bgIsolation | "none" lets background sessions edit the working copy directly [v2.1.143] |
workflowSizeGuideline | Advisory size guideline for dynamic workflows [v2.1.219] |
sandbox.credentials | Block sandboxed commands from reading credential files/secrets [v2.1.187] |
sandbox.filesystem.disabled | Skip filesystem isolation, keep network egress control [v2.1.216] |
sandbox.filesystem.allowRead | Re-allow reads inside a denyRead region [v2.1.77] |
sandbox.network.deniedDomains | Block domains a broader allowedDomains wildcard would permit [v2.1.113] |
sandbox.network.strictAllowlist | Deny non-allowlisted hosts without prompting [v2.1.219] |
sandbox.failIfUnavailable | Exit with an error instead of running unsandboxed [v2.1.83] |
sandbox.allowAppleEvents | Let sandboxed commands send Apple Events on macOS [v2.1.181] |
sandbox.enableWeakerNetworkIsolation | macOS TLS verification through a MITM proxy [v2.1.69] |
sandbox.bwrapPath / sandbox.socatPath | Custom bubblewrap/socat locations on Linux and WSL [v2.1.133] |
disableDeepLinkRegistration | Prevent claude-cli:// protocol handler registration [v2.1.83] |
Managed (admin) settings added since v2.1.39: enforceAvailableModels, requiredMinimumVersion / requiredMaximumVersion, forceRemoteSettingsRefresh, parentSettingsBehavior, pluginSuggestionMarketplaces, allowedChannelPlugins, allowAllClaudeAiMcps, pluginTrustMessage, wslInheritsWindowsSettings, plus the managed-settings.d/ drop-in directory.
Skills Variable Substitution: [NEW]
# In skill files, use ${CLAUDE_SESSION_ID} for session-specific operations
Session ID: ${CLAUDE_SESSION_ID}
Project Rules:
# New: .claude/rules/ directory for project-specific rules
.claude/rules/
├── coding-style.md # Coding conventions
├── testing.md # Testing requirements
└── security.md # Security guidelines
Wildcard Permissions:
{
"permissions": {
"allow": [
"Bash(npm *)",
"Bash(git *)",
"mcp__myserver__*"
]
}
}
Bash(npm *) and Bash(git *) are wildcard command patterns; mcp__myserver__* allows every tool from the myserver MCP server.
Skills are unified capabilities that extend Claude Code — both auto-activated by Claude and manually invoked via /skill-name.
Note: Custom slash commands (
.claude/commands/files) have been merged into skills as of v2.1.3. Your existing command files keep working unchanged. Skills are recommended for new work because they support additional features like supporting files, invocation control, and subagent execution. See Migration: Commands to Skills.
Claude Code skills follow the Agent Skills open standard, which works across multiple AI tools. Claude Code extends the standard with additional features like invocation control, subagent execution, and dynamic context injection.
Skills are instructions packaged as SKILL.md files that extend what Claude Code can do. Claude loads them when relevant to your request, or you invoke them directly:
# Claude auto-activates a skill based on your request
You: "Review this code for security issues"
Claude: [Loads security-reviewer skill automatically]
# Or you invoke a skill directly
You: /security-reviewer src/auth.ts
Claude: [Loads and executes the security-reviewer skill]
Two types of skill content:
/skill-name.Where you store a skill determines who can use it:
| Location | Path | Applies To |
|---|---|---|
| Enterprise | Managed settings | All users in organization |
| Personal | ~/.claude/skills/<skill-name>/SKILL.md | All your projects |
| Project | .claude/skills/<skill-name>/SKILL.md | This project only |
| Plugin | <plugin>/skills/<skill-name>/SKILL.md | Where plugin is enabled |
When skills share the same name, higher-priority locations win: Enterprise > Personal > Project. Plugin skills use a plugin-name:skill-name namespace, so they cannot conflict.
Legacy compatibility: Files in .claude/commands/ still work and support the same frontmatter. If a skill and a command share the same name, the skill takes precedence.
Automatic nested directory discovery: When you work with files in subdirectories, Claude Code discovers skills from nested .claude/skills/ directories. For example, editing a file in packages/frontend/ also loads skills from packages/frontend/.claude/skills/. This supports monorepo setups where packages have their own skills.
Live change detection: Skills from directories added via --add-dir are loaded automatically and picked up by live change detection — edit them during a session without restarting.
Each skill is a directory with SKILL.md as the entrypoint:
my-skill/
├── SKILL.md # Main instructions (required)
├── template.md # Template for Claude to fill in (optional)
├── examples/
│ └── sample.md # Example output (optional)
└── scripts/
└── validate.sh # Script Claude can execute (optional)
Reference supporting files from your SKILL.md so Claude knows what each file contains:
## Additional resources
- For complete API details, see [reference.md](reference.md)
- For usage examples, see [examples.md](examples.md)
Tip: Keep
SKILL.mdunder 500 lines. Move detailed reference material to separate files.
Step 1: Create the skill directory:
# Personal skill (available in all projects)
mkdir -p ~/.claude/skills/explain-code
# Project skill (shared with team via git)
mkdir -p .claude/skills/explain-code
Step 2: Write SKILL.md with frontmatter and instructions:
---
name: explain-code
description: Explains code with visual diagrams and analogies. Use when explaining how code works, teaching about a codebase, or when the user asks "how does this work?"
---
When explaining code, always include:
1. **Start with an analogy**: Compare the code to something from everyday life
2. **Draw a diagram**: Use ASCII art to show the flow, structure, or relationships
3. **Walk through the code**: Explain step-by-step what happens
4. **Highlight a gotcha**: What's a common mistake or misconception?
Keep explanations conversational. For complex concepts, use multiple analogies.
Step 3: Test the skill:
# Let Claude invoke it automatically
> "How does this code work?"
# Or invoke it directly
> /explain-code src/auth/login.ts
Configure skill behavior with YAML frontmatter between --- markers at the top of SKILL.md. All fields are optional; only description is recommended.
| Field | Required | Description |
|---|---|---|
name | No | Display name. If omitted, uses directory name. Lowercase letters, numbers, hyphens (max 64 chars). |
description | Recommended | What the skill does and when to use it. Claude uses this to decide when to load it. |
argument-hint | No | Hint shown during autocomplete (e.g., [issue-number] or [filename] [format]). |
disable-model-invocation | No | true → only user can invoke via /name. Default: false. |
user-invocable | No | false → hidden from / menu, only Claude can invoke. Default: true. |
allowed-tools | No | Tools Claude can use without asking permission when skill is active. |
model | No | Model to use when skill is active. |
context | No | Set to fork to run in a forked subagent context. |
agent | No | Which subagent type to use when context: fork is set. |
hooks | No | Hooks scoped to this skill's lifecycle. See Hooks. |
By default, both you and Claude can invoke any skill. Two frontmatter fields restrict this:
disable-model-invocation: true — Only you can invoke. Use for workflows with side effects (e.g., /deploy, /commit).user-invocable: false — Only Claude can invoke. Use for background knowledge that isn't actionable as a command.# User-only skill (Claude won't auto-trigger)
---
name: deploy
description: Deploy the application to production
disable-model-invocation: true
---
# Model-only skill (hidden from / menu)
---
name: legacy-system-context
description: Background knowledge about the legacy system
user-invocable: false
---
Invocation and context-loading behavior:
| Frontmatter | You Can Invoke | Claude Can Invoke | When Loaded into Context |
|---|---|---|---|
| (default) | Yes | Yes | Description always in context; full skill loads when invoked |
disable-model-invocation: true | Yes | No | Description not in context; full skill loads when you invoke |
user-invocable: false | No | Yes | Description always in context; full skill loads when invoked |
Restricting Claude's access via /permissions:
# Allow only specific skills
Skill(commit)
Skill(review-pr *)
# Deny specific skills
Skill(deploy *)
# Disable all skills
Skill # Add to deny rules
Permission syntax: Skill(name) for exact match, Skill(name *) for prefix match with any arguments.
Skills accept arguments via placeholder substitutions:
| Variable | Description |
|---|---|
$ARGUMENTS | All arguments passed when invoking the skill |
$ARGUMENTS[N] | Specific argument by 0-based index (e.g., $ARGUMENTS[0]) |
$N | Shorthand for $ARGUMENTS[N] (e.g., $0, $1) |
${CLAUDE_SESSION_ID} | Current session ID (useful for logging) |
Example:
---
name: fix-issue
description: Fix a GitHub issue
disable-model-invocation: true
---
Fix GitHub issue $ARGUMENTS following our coding standards.
1. Read the issue description
2. Implement the fix
3. Write tests
4. Create a commit
/fix-issue 123
# Claude receives: "Fix GitHub issue 123 following our coding standards..."
Indexed arguments:
---
name: compare-files
description: Compare two files
---
# Compare: $ARGUMENTS[0] vs $ARGUMENTS[1]
# Shorthand: $0 vs $1
Compare $0 and $1 for differences.
/compare-files "src/v1/api.ts" "src/v2/api.ts"
# $0 = "src/v1/api.ts", $1 = "src/v2/api.ts"
If $ARGUMENTS is not present in the skill content, arguments are appended as ARGUMENTS: <value>.
The !`command` syntax runs shell commands before the skill content is sent to Claude. The output replaces the placeholder:
---
name: pr-summary
description: Summarize changes in a pull request
context: fork
agent: Explore
allowed-tools: Bash(gh *)
---
## Pull request context
- PR diff: !`gh pr diff`
- PR comments: !`gh pr view --comments`
- Changed files: !`gh pr diff --name-only`
## Your task
Summarize this pull request...
Each !`command` executes immediately (before Claude sees anything). Claude only sees the final result with actual data.
Add context: fork to run a skill in isolation. The skill content becomes the prompt that drives the subagent (no access to conversation history):
---
name: deep-research
description: Research a topic thoroughly
context: fork
agent: Explore
---
Research $ARGUMENTS thoroughly:
1. Find relevant files using Glob and Grep
2. Read and analyze the code
3. Summarize findings with specific file references
The agent field specifies which subagent to use. Options: built-in agents (Explore, Plan, general-purpose) or custom subagents from .claude/agents/. Default: general-purpose.
Warning:
context: forkonly makes sense for skills with explicit instructions. Guidelines without a task will return without meaningful output.
To enable extended thinking in a skill, include the word ultrathink anywhere in your skill content:
---
name: architecture-review
description: Deep architectural analysis
---
Use ultrathink to analyze the architecture deeply.
Review the overall structure, identify patterns, and suggest improvements.
Example: Code Review Skill
.claude/skills/code-reviewer/SKILL.md:
---
name: code-reviewer
description: Reviews code for security vulnerabilities, bugs, performance issues, and style problems. Use when user asks to review, audit, or check code quality.
allowed-tools: [Read, Grep, Glob]
---
# Code Review Skill
## When to Activate
Use this skill when the user asks to:
- Review code for issues
- Audit security or find vulnerabilities
- Check code quality or best practices
## Review Process
### 1. Scope Detection
- Use Glob to identify files to review
- Prioritize recently modified files
- Focus on user-specified areas if mentioned
### 2. Analysis Layers
- **Security**: SQL injection, XSS, auth issues, exposed secrets
- **Bugs**: Logic errors, null checks, error handling
- **Performance**: N+1 queries, unnecessary loops, memory leaks
- **Style**: Naming conventions, code organization, readability
### 3. Reporting
Provide structured feedback organized by severity:
- **Critical/High**: Security issues
- **Medium**: Performance issues
- **Low**: Style and best practices
Each issue: file path, description, and fix suggestion.
Example: Test Generator Skill
.claude/skills/test-generator/SKILL.md:
---
name: test-generator
description: Generates comprehensive unit and integration tests. Use when user asks to write tests, add test coverage, or create test cases.
allowed-tools: [Read, Write, Grep, Glob, Bash]
---
# Test Generator Skill
## When to Activate
Use this skill when user requests:
- "Write tests for..."
- "Add test coverage"
- "Generate test cases"
## Test Generation Process
### 1. Analyze Target Code
- Read the file/function to test
- Identify inputs, outputs, side effects
- Check existing test patterns
### 2. Generate Comprehensive Tests
Cover all scenarios:
- Happy path (expected usage)
- Error cases (invalid inputs)
- Edge cases (empty, null, boundary values)
- Side effects (database, API calls)
### 3. Follow Project Patterns
- Check CLAUDE.md for testing conventions
- Match existing test file structure
- Use project's test framework
Example: Security Review Skill
.claude/skills/security-review/SKILL.md:
---
name: security-review
description: Comprehensive security audit of codebase. Use when asked to review security, audit vulnerabilities, or check for exploits.
allowed-tools: [Read, Grep, Glob]
disable-model-invocation: true
---
# Security Review: $ARGUMENTS
Perform a thorough security audit focusing on: $ARGUMENTS
## Review Checklist
### 1. Authentication & Authorization
- Check for weak password policies
- Verify JWT token validation
- Review session management
- Check for broken access control
### 2. Input Validation
- SQL injection vulnerabilities
- XSS (Cross-Site Scripting) risks
- Command injection possibilities
- Path traversal vulnerabilities
### 3. Data Protection
- Sensitive data exposure
- Encryption at rest and in transit
- API keys and secrets in code
- Database credential security
### 4. Dependencies
- Known vulnerabilities in packages
- Outdated dependencies
- License compliance issues
### 5. Configuration
- Security headers (CSP, HSTS, etc.)
- CORS configuration
- Error messages leaking information
- Debug mode in production
**Output Format** - Provide a detailed report with sections:
- Critical Issues (Fix Immediately)
- High Priority
- Medium Priority
- Low Priority / Recommendations
- Security Strengths
- Action Plan (prioritized list of fixes)
Usage:
/security-review "authentication and API endpoints"
Example: API Documentation Generator Skill
.claude/skills/api-docs/SKILL.md:
---
name: api-docs
description: Generate comprehensive API documentation from code. Use when asked to document APIs, create API docs, or generate OpenAPI specs.
allowed-tools: [Read, Write, Grep, Glob]
disable-model-invocation: true
---
# Generate API Documentation
Analyze the codebase and create comprehensive API documentation for: $ARGUMENTS
## Process
### 1. Discovery
- Find all API routes/endpoints
- Identify request/response types
- Note authentication requirements
- Document query parameters
### 2. Documentation
For each endpoint, document:
- Method and path
- Description
- Authentication requirements
- Request body/parameters
- Response codes and bodies
- Example requests
### 3. Output
- Create `/docs/API.md` with full documentation
- Create `/openapi.yaml` with OpenAPI spec if applicable
Usage:
/api-docs "all endpoints"
/api-docs "authentication routes"
Reference files with @ prefix for quick file inclusion:
# Reference single file
/review-code @src/auth.ts
# Reference multiple files
/review-code @src/auth.ts @src/api.ts @tests/auth.test.ts
# Works in regular prompts too
> "Review @src/services/payment.ts for security issues"
# Reference files with skill arguments
/analyze-file @src/components/UserProfile.tsx
How @ References Work:
@filename automatically expands to include file contentUse Cases:
# Code review with context
> "Compare @src/api/v1.ts and @src/api/v2.ts and list differences"
# Refactoring across files
> "Make @src/models/User.ts consistent with @src/types/user.d.ts"
# Bug investigation
> "This error occurs in @src/services/auth.ts, check @logs/error.log for clues"
# Test generation
> "Generate tests for @src/utils/validator.ts"
Best Practices:
MCP servers can expose prompts that become invocable skills automatically:
{
"prompts": [
{
"name": "search-docs",
"description": "Search internal documentation",
"arguments": [{"name": "query", "description": "Search query"}]
}
]
}
This becomes available as /search-docs in Claude Code.
# Add MCP server
claude mcp add github -- gh-mcp
# MCP prompts become skills:
/github-pr-review # Review current PR
/github-issues # List open issues
/github-create-pr # Create PR from current branch
The description field is critical — it helps Claude decide when to activate:
Good:
description: "Generates API documentation from code comments. Use when user asks to document APIs, create API docs, update endpoint documentation, or generate OpenAPI specs."
Bad:
description: "Documentation generator" # Too vague
Include terms users would naturally say:
# For security review skill
description: "Reviews code for security. Use when asked to: review security, audit code, find vulnerabilities, check for exploits, analyze risks."
# For performance optimization skill
description: "Optimizes code performance. Use when asked to: improve performance, optimize speed, reduce memory usage, make faster, profile code."
# Analysis only (can't modify code)
allowed-tools: [Read, Grep, Glob]
# Can create/modify code
allowed-tools: [Read, Write, Edit, Bash]
# Research and implementation
allowed-tools: [Read, Write, Edit, WebFetch, WebSearch]
Good (focused):
sql-optimizer — Optimizes SQL queries onlyapi-docs-generator — Generates API documentationsecurity-scanner — Finds security issuesBad (too broad):
database-everything — Too vaguecode-helper — What kind of help?Structure your SKILL.md:
Skill descriptions are loaded into context so Claude knows what's available. If you have many skills, they may exceed the character budget (2% of context window, fallback 16,000 characters). Run /context to check for warnings about excluded skills.
Override the limit with the SLASH_COMMAND_TOOL_CHAR_BUDGET environment variable.
Skill not triggering:
/skill-name to confirm it worksSkill triggers too often:
disable-model-invocation: true for manual-only invocationClaude doesn't see all skills:
/context to check for a warning about excluded skillsSLASH_COMMAND_TOOL_CHAR_BUDGET to a higher valueCustom slash commands (.claude/commands/ files) have been merged into the skills system. Your existing command files keep working unchanged. Skills are recommended for new work because they support:
Migration path:
# Old structure (still works)
.claude/commands/review.md
# New structure (recommended)
.claude/skills/review/SKILL.md
Both create /review and work the same way. If both exist, the skill takes precedence.
Source: Agent Skills
Built-in commands are native CLI commands for managing your Claude Code session. They are hardcoded into Claude Code and are NOT skills — you cannot customize or override them.
Note: For custom workflow commands, use Skills instead. Built-in commands like
/helpand/compactare not available through the Skill tool.
# Session Management
/help # Show all available commands
/exit # End current session
/clear # Clear conversation history
/compact [instr] # Compact context (optionally specify what to focus on)
/rewind # Undo code changes in conversation (/undo is an alias) [v2.1.108]
/recap # Summarize what happened while you were away [NEW v2.1.108]
/goal <condition> # Keep working across turns until a completion condition is met [NEW v2.1.139]
/loop [interval] # Run a prompt or slash command on a repeat (/proactive alias) [NEW v2.1.71]
/effort [level] # Set reasoning effort: low / medium / high / xhigh / max / ultracode
# (/effort auto resets to the model default) [NEW v2.1.76]
/focus # Toggle focus view (Ctrl+O now toggles verbose transcript) [NEW v2.1.110]
/tui [fullscreen] # Switch renderer mode in the same conversation [NEW v2.1.110]
# Session & History
/rename <name> # Give current session a name (auto-generates if omitted)
/resume [name|id] # Resume a previous session by name or ID (includes background sessions)
/export # Export conversation to file
/copy [N] # Copy a response or code block to the clipboard (N = Nth-latest)
/branch # Fork the conversation into a new session (/fork is an alias) [v2.1.77]
/fork # Copy the conversation into a new background session [v2.1.212]
/subtask # Run a sub-task as an in-session subagent [NEW v2.1.212]
/background # Send the current session to the background [NEW]
/cd <path> # Move the session to a new working directory [NEW v2.1.169]
/btw # Ask a side question without disturbing the main thread
# Usage & Stats
/usage # Plan limits, usage, and per-category breakdown (merges /cost and /stats)
/stats # Shortcut into the /usage stats tab
/usage-credits # Enable usage credits (formerly /extra-usage) [v2.1.144]
/fast # Toggle fast mode (Opus 5 and Opus 4.8 as of v2.1.219)
/insights # Usage insights report
# Background Process Management
/bashes # List all background processes
/tasks # List all background tasks (agents, shells, etc.)
/kill <id> # Stop a background process
# Discovery & Debugging
/bug # Report bugs (sends conversation to Anthropic)
/commands # List all skills and commands
/debug # Troubleshoot session issues [NEW v2.1.30]
/hooks # Show configured hooks
/skills # List available Skills
/plugin # Plugin management interface
/context # Context usage grid plus actionable optimization suggestions
/cost # Shortcut into the /usage cost tab
/doctor # Full setup checkup that can diagnose and fix issues (/checkup alias)
/reload-skills # Re-scan skill directories without restarting [NEW v2.1.152]
/reload-plugins # Activate pending plugin changes without restarting [NEW v2.1.69]
/powerup # Interactive lessons teaching Claude Code features [NEW v2.1.90]
/team-onboarding # Generate a teammate ramp-up guide from your usage [NEW v2.1.101]
/scroll-speed # Tune mouse wheel scroll speed with a live preview [NEW v2.1.139]
# Configuration
/config # General settings (type to search and filter)
/permissions # Manage tool permissions (with search)
/privacy-settings # View and update privacy settings
/status # Show session status (Status tab)
/statusline # Configure status line display
/model # Switch between models
/config key=value # Set any setting from the prompt (/config --help lists keys) [NEW v2.1.181]
/output-style # ⚠️ Deprecated in v2.1.73 - use /config instead
/theme # Theme picker; create named custom themes since v2.1.118
/color [name] # Set the prompt-bar color for this session (/color default resets) [NEW v2.1.75]
/terminal-setup # Configure terminal (Kitty, Alacritty, Zed, Warp)
/vim # ⚠️ Removed in v2.1.92 - toggle vim mode via /config → Editor mode
/sandbox # Enable sandboxed bash with filesystem/network isolation
# Workspace Management
/add-dir <path> # Add additional directory to workspace
/agents # ⚠️ Wizard removed in v2.1.198 - ask Claude or edit .claude/agents/ directly
/init # Initialize project with CLAUDE.md guide
/memory # Edit CLAUDE.md memory files
/install-github-app # Set up Claude GitHub Actions for repository
/pr-comments # View pull request comments
/review [pr] # Fast single-pass code review [v2.1.202]
/code-review [lvl] # Multi-agent review at a chosen effort level; --fix applies findings,
# --comment posts inline GitHub PR comments [NEW v2.1.147]
/simplify # Cleanup-only review (reuse, simplification, efficiency) [v2.1.152]
/ultrareview [pr] # Cloud multi-agent review of your branch or a PR [NEW v2.1.111]
/security-review # Complete security review of pending changes
/workflows # View dynamic workflow runs [NEW v2.1.154]
/deep-research # Run a multi-agent research task (manual invocation only)
/dataviz # Chart and dashboard design guidance skill [NEW v2.1.198]
/claude-api # Skill for building with the Claude API and Anthropic SDK [NEW v2.1.69]
/less-permission-prompts # Propose an allowlist from your transcripts [NEW v2.1.111]
/batch # Run a batch of related tasks [NEW v2.1.63]
/todos # List current TODO items
# MCP Server Management
/mcp # MCP server management and OAuth authentication
/mcp enable <srv> # Enable an MCP server
/mcp disable <srv> # Disable an MCP server
# Remote Sessions (claude.ai subscribers)
/teleport # Resume remote session from claude.ai by session ID
/remote-env # Configure remote session environment
/remote-control # Bridge this session to claude.ai/code for mobile/web control
/chrome # Manage the Claude in Chrome connection (GA in v2.1.198)
/voice # Voice dictation (20 languages as of v2.1.69)
/schedule # Manage scheduled tasks
# Account & Updates
/login # Switch Anthropic accounts
/logout # Sign out from Anthropic account
/release-notes # View release notes
# Plan Mode
/plan # Enter plan mode for structured planning
Source: CLI Reference, Interactive Mode
Hooks are automated scripts that execute at specific points in Claude Code's workflow.
Hooks let you intercept and control Claude's actions:
# Examples of what hooks can do:
- Block editing of sensitive files (.env)
- Inject context at session start
- Run linting before file edits
- Validate git commits
- Audit all commands executed
- Add custom security checks
Two Types:
type: "command") - Run shell scriptstype: "prompt") - Use LLM for context-aware decisionsHooks are configured in .claude/settings.json or ~/.claude/settings.json:
{
"hooks": {
"EventName": [
{
"matcher": "ToolPattern",
"hooks": [
{"type": "command", "command": "script"}
]
}
]
}
}
| Event | When It Fires | Can Block |
|---|---|---|
| Setup | Via --init, --init-only, or --maintenance flags | No |
| SessionStart | Session begins or resumes | No |
| SessionEnd | Session terminates | No |
| UserPromptSubmit | User submits a prompt | Yes |
| PreToolUse | Before tool execution | Yes |
| PostToolUse | After tool succeeds | No |
| PostToolUseFailure | After tool fails | No |
| PermissionRequest | When permission dialog appears | Yes |
| SubagentStart | When spawning a subagent | No |
| SubagentStop | When subagent finishes | Yes |
| Stop | Claude finishes responding | Yes |
| StopFailure | Turn ends due to an API error (rate limit, auth failure) [NEW v2.1.78] | No |
| Notification | Claude sends notification | No |
| PreCompact | Before context compaction (blocks via exit code 2 since v2.1.105) | Yes |
| PostCompact | After compaction completes [NEW v2.1.76] | No |
| TeammateIdle | Agent team teammate about to go idle | Yes |
| TaskCompleted | Task being marked as completed | Yes |
| TaskCreated | Task created via TaskCreate [NEW v2.1.84] | Yes |
| MessageDisplay | Assistant message about to be displayed — transform or hide it [NEW v2.1.152] | Yes |
| PermissionDenied | After an auto mode classifier denial (return {retry: true}) [NEW v2.1.89] | No |
| ConfigChange | Configuration files change during a session [NEW v2.1.49] | Yes |
| InstructionsLoaded | CLAUDE.md or .claude/rules/*.md loaded into context [NEW v2.1.69] | No |
| CwdChanged | Working directory changes [NEW v2.1.83] | No |
| FileChanged | A watched file changes [NEW v2.1.83] | No |
| DirectoryAdded | /add-dir registers a new working directory mid-session [NEW v2.1.219] | No |
| WorktreeCreate | Agent worktree isolation creates a worktree [NEW v2.1.50] | No |
| WorktreeRemove | Agent worktree isolation removes a worktree [NEW v2.1.50] | No |
| Elicitation | MCP server requests structured input [NEW v2.1.76] | Yes |
| ElicitationResult | Before an elicitation response is sent back [NEW v2.1.76] | Yes |
Hook configuration additions since v2.1.39:
| Feature | Description |
|---|---|
if: condition | Filter when a hook runs using permission-rule syntax, e.g. if: "Bash(git *)" [NEW v2.1.85] |
args: string[] | Exec form — spawns the command directly without a shell, so paths never need quoting [NEW v2.1.139] |
type: "http" | HTTP hooks POST JSON to a URL and receive JSON (needs allowedEnvVars to interpolate env) [NEW v2.1.63] |
type: "mcp_tool" | Hooks can invoke MCP tools directly [NEW v2.1.118] |
continueOnBlock | PostToolUse only — feed the rejection reason back to Claude and continue the turn [NEW v2.1.139] |
terminalSequence | Emit desktop notifications, window titles, and bells without a controlling terminal [NEW v2.1.141] |
"defer" decision | PreToolUse only — pause a headless session at a tool call, resume with -p --resume [NEW v2.1.89] |
hookSpecificOutput.updatedToolOutput | PostToolUse can replace tool output for all tools [NEW v2.1.121] |
hookSpecificOutput.sessionTitle | SessionStart / UserPromptSubmit can set the session title [NEW v2.1.94] |
hookSpecificOutput.additionalContext | Stop / SubagentStop feedback that keeps the turn going [NEW v2.1.163] |
reloadSkills: true | SessionStart can re-scan skill directories in the same session [NEW v2.1.152] |
effort.level / $CLAUDE_EFFORT | Hooks receive the active effort level [NEW v2.1.133] |
duration_ms | PostToolUse / PostToolUseFailure input includes tool execution time [NEW v2.1.119] |
last_assistant_message | Stop / SubagentStop input includes the final assistant response text [NEW v2.1.47] |
background_tasks, session_crons | Stop / SubagentStop input fields [NEW v2.1.145] |
agent_id / agent_type | Present on hook events for subagents and --agent sessions [NEW v2.1.69] |
.claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "bash -c 'FILE=$(echo \"$HOOK_INPUT\" | jq -r \".tool_input.file_path // empty\"); if [[ \"$FILE\" == *\".env\"* ]] || [[ \"$FILE\" == \".git/\"* ]]; then echo \"Cannot modify sensitive files\" >&2; exit 2; fi'"
}
]
}
]
}
}
How it works:
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "cat .claude/session-context.txt"
}
]
}
]
}
}
Creates: .claude/session-context.txt
Today's Focus: Working on authentication refactor
Recent Context: Migrated from sessions to JWT
Current Branch: feature/jwt-auth
Important: Don't modify legacy auth code in /old-auth
This context is injected at every session start.
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Evaluate if the current task is complete. Arguments: $ARGUMENTS. Check if all subtasks are done, tests pass, and documentation updated. Respond with {\"decision\": \"stop\" or \"continue\", \"reason\": \"explanation\"}"
}
]
}
]
}
}
Uses an LLM (Haiku) to intelligently decide if Claude should stop working.
Input (via stdin as JSON):
{
"sessionId": "abc123",
"tool_name": "Edit",
"tool_input": {
"file_path": "/src/app.ts",
"old_string": "...",
"new_string": "..."
},
"project_dir": "/home/user/project"
}
Output (exit codes):
0 - Success, continue2 - Block the actionJSON Output (optional):
{
"decision": "stop",
"reason": "All tasks complete",
"continue": false
}
⚠️ Critical: "By using hooks, you are solely responsible for configured commands, which can modify or delete files your user can access."
Best Practices:
# 1. Always quote variables
FILE="$HOOK_INPUT" # Good
FILE=$HOOK_INPUT # Bad - can break with spaces
# 2. Validate paths
if [[ "$FILE" == ../* ]]; then
echo "Path traversal attempt" >&2
exit 2
fi
# 3. Use absolute paths
cd "$CLAUDE_PROJECT_DIR" || exit 1
# 4. Sanitize inputs
jq -r '.tool_input.file_path' <<< "$HOOK_INPUT" # Good
eval "$SOME_VAR" # Bad - code injection risk
# 5. Block sensitive operations
case "$FILE" in
*.env|.git/*|.ssh/*)
echo "Blocked: sensitive file" >&2
exit 2
;;
esac
# Run Claude with debug mode
claude --debug
# Check hook configuration
> /hooks
# Test hook command manually
echo '{"tool_name":"Edit","tool_input":{"file_path":".env"}}' | bash your-hook-script.sh
# View logs
tail -f ~/.claude/logs/claude.log
Comprehensive collection of production-ready hook patterns for common automation needs.
Automatically formats code after Claude edits files using language-appropriate formatters.
Configuration (.claude/settings.json):
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|MultiEdit|Write",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/format-code.sh"
}
]
}
]
}
}
Script (~/.claude/hooks/format-code.sh):
#!/bin/bash
# Extract file path from JSON input
FILE=$(echo "$HOOK_INPUT" | jq -r '.tool_input.file_path // empty')
[[ -z "$FILE" ]] && exit 0
# Format based on extension
case "$FILE" in
*.ts|*.tsx|*.js|*.jsx)
# Try Biome first, fall back to Prettier
if command -v biome &> /dev/null; then
biome format --write "$FILE" &> /dev/null || true
elif command -v prettier &> /dev/null; then
prettier --write "$FILE" &> /dev/null || true
fi
;;
*.py)
# Python: Ruff
if command -v ruff &> /dev/null; then
ruff format "$FILE" &> /dev/null || true
fi
;;
*.go)
# Go: goimports + gofmt
if command -v goimports &> /dev/null; then
goimports -w "$FILE" &> /dev/null || true
fi
go fmt "$FILE" &> /dev/null || true
;;
*.md)
# Markdown: Prettier
if command -v prettier &> /dev/null; then
prettier --write "$FILE" &> /dev/null || true
fi
;;
esac
Make executable: chmod +x ~/.claude/hooks/format-code.sh
Automatically runs ESLint with --fix on JavaScript/TypeScript files.
Configuration:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|MultiEdit|Write",
"hooks": [
{
"type": "command",
"command": "bash -c 'FILE=$(echo \"$HOOK_INPUT\" | jq -r \".tool_input.file_path // empty\"); if [[ \"$FILE\" =~ \\.(ts|tsx|js|jsx)$ ]] && command -v eslint &>/dev/null; then eslint --fix \"$FILE\" &>/dev/null || true; fi'"
}
]
}
]
}
}
Prevents Claude from reading files matching .claudeignore patterns.
Configuration:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Read",
"hooks": [
{
"type": "command",
"command": "claude-ignore"
}
]
}
]
}
}
Installation: npm install -g claude-ignore && claude-ignore init
Validates that tests pass before allowing git commits.
Configuration:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/pre-commit-test.sh"
}
]
}
]
}
}
Script (~/.claude/hooks/pre-commit-test.sh):
#!/bin/bash
COMMAND=$(echo "$HOOK_INPUT" | jq -r '.tool_input.command // empty')
# Only intercept git commit commands
if [[ "$COMMAND" == git*commit* ]]; then
echo "Running tests before commit..." >&2
# Run tests
if npm test &>/dev/null; then
echo "✅ Tests passed" >&2
exit 0
else
echo "❌ Tests failed - blocking commit" >&2
exit 2
fi
fi
exit 0
Logs all tool usage for security auditing.
Configuration:
{
"hooks": {
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "bash -c 'echo \"$(date -Iseconds) $TOOL_NAME: $(echo \\\"$HOOK_INPUT\\\" | jq -c .)\" >> ~/.claude/audit.log'"
}
]
}
]
}
}
Monitors and logs token usage per session.
Configuration:
{
"hooks": {
"SessionEnd": [
{
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/log-session.sh"
}
]
}
]
}
}
Script:
#!/bin/bash
SESSION_ID=$(echo "$HOOK_INPUT" | jq -r '.session_id // "unknown"')
TRANSCRIPT=$(echo "$HOOK_INPUT" | jq -r '.transcript_path // empty')
if [[ -f "$TRANSCRIPT" ]]; then
TOKENS=$(jq '[.[] | select(.role=="assistant") | .usage.total_tokens] | add' "$TRANSCRIPT" 2>/dev/null || echo 0)
echo "$(date -Iseconds) Session $SESSION_ID: $TOKENS tokens" >> ~/.claude/token-usage.log
fi
Enforces conventional commit message format.
Configuration:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/validate-commit.sh"
}
]
}
]
}
}
Script:
#!/bin/bash
COMMAND=$(echo "$HOOK_INPUT" | jq -r '.tool_input.command // empty')
if [[ "$COMMAND" == git*commit*-m* ]]; then
MSG=$(echo "$COMMAND" | sed -n 's/.*-m[[:space:]]*["'"'"']\([^"'"'"']*\)["'"'"'].*/\1/p')
# Check conventional commit format: type(scope): message
if [[ ! "$MSG" =~ ^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: ]]; then
echo "❌ Commit message must follow format: type(scope): message" >&2
echo "Valid types: feat, fix, docs, style, refactor, test, chore" >&2
exit 2
fi
fi
exit 0
Prevents committing files containing potential secrets.
Configuration:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/detect-secrets.sh"
}
]
}
]
}
}
Script:
#!/bin/bash
FILE=$(echo "$HOOK_INPUT" | jq -r '.tool_input.file_path // empty')
NEW_CONTENT=$(echo "$HOOK_INPUT" | jq -r '.tool_input.new_string // .tool_input.content // empty')
# Check for common secret patterns
if echo "$NEW_CONTENT" | grep -iE '(api[_-]?key|password|secret|token|auth)["\s:=]+\S{16,}' &>/dev/null; then
echo "⚠️ Potential secret detected in $FILE" >&2
echo "Please review and use environment variables instead" >&2
exit 2
fi
exit 0
Updates README when code changes are made.
Configuration:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|MultiEdit|Write",
"hooks": [
{
"type": "command",
"command": "bash -c 'echo \"📝 Consider updating documentation for recent changes\" >&2'"
}
]
}
]
}
}
Tracks execution time of tool operations.
Configuration:
{
"hooks": {
"PreToolUse": [
{
"hooks": [
{
"type": "command",
"command": "bash -c 'echo \"$HOOK_INPUT\" > /tmp/claude-pre-$$.json; date +%s%N > /tmp/claude-time-$$.txt'"
}
]
}
],
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/profile-tool.sh"
}
]
}
]
}
}
Script:
#!/bin/bash
START=$(cat /tmp/claude-time-$$.txt 2>/dev/null || echo 0)
END=$(date +%s%N)
DURATION=$(( (END - START) / 1000000 )) # milliseconds
TOOL=$(echo "$HOOK_INPUT" | jq -r '.tool_name // "unknown"')
echo "$(date -Iseconds) $TOOL: ${DURATION}ms" >> ~/.claude/performance.log
rm -f /tmp/claude-pre-$$.json /tmp/claude-time-$$.txt
Source: Hooks Reference, Hooks Guide, Community GitHub repositories
Model Context Protocol (MCP) connects Claude Code to external data sources and tools.
MCP allows Claude Code to:
Common Use Cases:
MCP servers can be added via CLI or configuration files:
CLI Installation (Recommended):
# Remote HTTP Server (recommended for hosted services)
claude mcp add --transport http notion https://mcp.notion.com/mcp
claude mcp add --transport http github https://api.githubcopilot.com/mcp/
# With authentication headers
claude mcp add --transport http secure-api https://api.example.com/mcp \
--header "Authorization: Bearer your-token"
# Local Stdio Server (for local packages)
claude mcp add --transport stdio airtable -- npx -y airtable-mcp-server
claude mcp add --transport stdio postgres -- npx -y @modelcontextprotocol/server-postgres "$DATABASE_URL"
# With environment variables
claude mcp add --transport stdio --env AIRTABLE_API_KEY=your_key airtable -- npx -y airtable-mcp-server
# Windows (requires cmd /c wrapper)
claude mcp add --transport stdio myserver -- cmd /c npx -y @some/package
MCP Server Management:
claude mcp list # List all configured servers
claude mcp get github # Get details for specific server
claude mcp remove github # Remove a server
/mcp # Interactive management in Claude Code
Installation Scopes:
# Local scope (default) - stored in ~/.claude.json under project path
claude mcp add --transport http stripe https://mcp.stripe.com
# Project scope - stored in .mcp.json (shared via git)
claude mcp add --scope project --transport http paypal https://mcp.paypal.com/mcp
# User scope - stored in ~/.claude.json (available across all projects)
claude mcp add --scope user --transport http hubspot https://mcp.hubspot.com
Configuration File (.mcp.json):
{
"mcpServers": {
"github": {
"type": "http",
"url": "https://api.githubcopilot.com/mcp/"
},
"postgres": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres", "${DATABASE_URL}"],
"env": {
"DB_URL": "${DB_URL}",
"API_KEY": "${API_KEY:-default-value}"
}
},
"slack": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-slack"],
"env": {
"SLACK_BOT_TOKEN": "${SLACK_BOT_TOKEN}",
"SLACK_TEAM_ID": "${SLACK_TEAM_ID}"
}
}
}
}
Many MCP servers support OAuth for secure authentication:
# Add server that requires OAuth
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp
# Within Claude Code, authenticate via browser
/mcp
# Follow browser steps to complete OAuth login
Manual OAuth Configuration:
{
"mcpServers": {
"github": {
"type": "http",
"url": "https://api.githubcopilot.com/mcp/",
"oauth": {
"provider": "github",
"scopes": ["repo", "read:user"]
}
}
}
}
Claude Code opens a browser to complete the OAuth flow on first use.
Once configured, MCP tools appear with the pattern mcp__<server>__<tool>:
# Example: Google Drive search
> "Search our Google Drive for Q4 planning documents"
# Claude uses: mcp__google-drive__search_files
# Example: Database query
> "Show all users created in the last week"
# Claude uses: mcp__postgres__query with SQL
# Example: Slack search
> "Find conversations about the API redesign"
# Claude uses: mcp__slack__search_messages
You can reference MCP tools in hooks:
{
"hooks": {
"PreToolUse": [
{
"matcher": "mcp__postgres__query",
"hooks": [
{
"type": "command",
"command": "echo 'Database query requires review' && read -p 'Approve? (y/n) ' -n 1 -r && [[ $REPLY =~ ^[Yy]$ ]]"
}
]
}
]
}
}
# Official Servers
@modelcontextprotocol/server-google-drive # Google Drive access
@modelcontextprotocol/server-slack # Slack integration
@modelcontextprotocol/server-github # GitHub API
@modelcontextprotocol/server-postgres # PostgreSQL database
@modelcontextprotocol/server-sqlite # SQLite database
@modelcontextprotocol/server-filesystem # Extended file access
# Community Servers
# Check GitHub for community-built MCP servers
# Enable all project MCP servers automatically
{
"enableAllProjectMcpServers": true
}
# Whitelist specific servers
{
"enabledMcpjsonServers": ["google-drive", "postgres"]
}
# Blacklist servers
{
"disabledMcpjsonServers": ["risky-server"]
}
# Enterprise: Restrict to managed servers only
{
"useEnterpriseMcpConfigOnly": true,
"allowedMcpServers": ["approved-server-1", "approved-server-2"]
}
When MCP tool definitions exceed a threshold of the context window, they're automatically deferred via an MCPSearch tool:
# Configure tool search threshold (% of context window)
ENABLE_TOOL_SEARCH=auto:5 claude # Activate at 5%
ENABLE_TOOL_SEARCH=auto:10 claude # Activate at 10% (default)
ENABLE_TOOL_SEARCH=true claude # Always enabled
ENABLE_TOOL_SEARCH=false claude # Always disabled
# Or configure in settings.json
{
"permissions": {
"deny": ["MCPSearch"] # Disable MCP tool search
}
}
Source: MCP Documentation, Settings
Quick-start configurations for popular MCP servers.
# Installation
claude mcp add --transport stdio github -- npx -y @modelcontextprotocol/server-github
# Or via .mcp.json
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
}
}
}
}
Common operations: Create issues, manage PRs, search code, review repositories.
# Installation
claude mcp add --transport stdio slack -- npx -y @modelcontextprotocol/server-slack
# Configuration
{
"mcpServers": {
"slack": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-slack"],
"env": {
"SLACK_BOT_TOKEN": "${SLACK_BOT_TOKEN}",
"SLACK_TEAM_ID": "T01234567"
}
}
}
}
Usage: > "Search Slack for conversations about API redesign"
# Installation with OAuth
claude mcp add --transport http gdrive https://mcp.google.com/drive
# Or stdio with credentials
{
"mcpServers": {
"gdrive": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-gdrive"],
"env": {
"GDRIVE_CREDENTIALS_PATH": "${HOME}/.gdrive-credentials.json"
}
}
}
}
Authenticate: Run /mcp in Claude Code and follow OAuth flow.
# Installation
claude mcp add --transport stdio postgres -- npx -y @modelcontextprotocol/server-postgres postgresql://user:pass@localhost/db
# Configuration
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-postgres",
"${DATABASE_URL}"
]
}
}
}
Usage: > "Show all users created in the last week from the database"
# Installation
claude mcp add --transport http notion https://mcp.notion.com/mcp
# Requires Notion OAuth - authenticate via /mcp command
Common operations: Query databases, create pages, search workspace.
# Configuration
{
"mcpServers": {
"stripe": {
"command": "npx",
"args": ["-y", "@stripe/mcp-server"],
"env": {
"STRIPE_API_KEY": "${STRIPE_API_KEY}"
}
}
}
}
Usage: > "List recent Stripe transactions and summarize revenue"
Common issues and solutions from GitHub issues and production usage.
# Problem
claude mcp list
# Output: "No MCP servers configured"
# Solutions
1. Check file location:
- User scope: ~/.claude/settings.json
- Project scope: .mcp.json (in project root)
2. Verify JSON syntax:
cat .mcp.json | jq .
3. Check scope setting:
claude mcp add --scope project <name> ...
4. Restart Claude Code after config changes
# Problem
/mcp shows "✓ Connected" but tools don't appear
# Solutions
1. Check tool output size (max 25,000 tokens):
export MAX_MCP_OUTPUT_TOKENS=50000
2. Verify server actually started:
ps aux | grep mcp
3. Check debug logs:
claude --debug
tail -f ~/.claude/logs/claude.log
4. Reset project approvals:
claude mcp reset-project-choices
# Problem
Browser opens but OAuth fails or doesn't complete
# Solutions
1. Use /mcp command (not direct URL)
2. Check network/proxy settings:
# Try without VPN/Cloudflare Warp
3. Clear OAuth cache:
rm -rf ~/.claude/oauth-cache
4. Verify redirect URI in provider settings
# Problem
MCP server immediately closes on Windows
# Solution - Use cmd /c wrapper:
claude mcp add --transport stdio myserver -- cmd /c npx -y package-name
# In .mcp.json:
{
"mcpServers": {
"myserver": {
"command": "cmd",
"args": ["/c", "npx", "-y", "package-name"]
}
}
}
# Problem
${VAR} shows literally instead of expanding
# Solutions
1. Check .env file exists and is loaded
2. Use default syntax:
"${API_KEY:-default_value}"
3. Set in shell before running:
export API_KEY=xxx && claude
4. Use settings.local.json for sensitive values
# Debug steps:
1. Test server directly:
npx @modelcontextprotocol/server-github
2. Check stdout/stderr:
claude --debug | grep mcp
3. Verify dependencies installed:
npm list -g | grep mcp
4. Check memory/resource limits:
ulimit -a
Sub-agents are specialized AI assistants configured for specific tasks.
Sub-agents are instances of Claude optimized for particular workflows:
# Built-in Sub-Agents
- general-purpose: Complex multi-step tasks
- Explore: Fast codebase exploration
# Custom Sub-Agents
- You can create your own with custom prompts and tools
Launch with the Task tool:
# Explore codebase
> "Find all database queries in the codebase"
# Claude uses:
Task subagent_type="Explore"
prompt="Find all database queries and list files containing SQL, Prisma, or ORM code"
# General purpose research
> "Research best practices for API rate limiting and suggest implementation"
# Claude uses:
Task subagent_type="general-purpose"
prompt="Research API rate limiting approaches, compare options, and recommend implementation for Express.js"
Sub-agents are defined as Markdown files in .claude/agents/ or ~/.claude/agents/:
Example: Debug Assistant
.claude/agents/debugger.md:
---
name: debugger
description: Specialized debugging agent for production issues
model: claude-sonnet-4
allowedTools: [Read, Grep, Glob, Bash]
---
# Debug Assistant
You are a specialized debugging agent. Your role is to systematically investigate and identify the root cause of issues.
## Debugging Process
### 1. Gather Context
- Read error messages and stack traces
- Check recent code changes (git log)
- Review related log files
- Understand expected vs actual behavior
### 2. Hypothesis Generation
- List possible causes
- Prioritize by likelihood
- Consider recent changes first
### 3. Systematic Investigation
- Test each hypothesis methodically
- Use Grep to find related code
- Read implementation details
- Check for similar patterns elsewhere
### 4. Root Cause Analysis
- Identify the precise cause
- Explain why it happens
- Trace the execution path
### 5. Solution Proposal
- Suggest specific fixes
- Explain tradeoffs
- Provide code examples
- Recommend tests to prevent recurrence
## Constraints
- DO NOT modify code (read-only analysis)
- DO provide detailed explanations
- DO reference specific file:line locations
- DO consider edge cases
Example: Code Review Agent
.claude/agents/reviewer.md:
---
name: reviewer
description: Code review specialist focusing on quality and best practices
model: claude-sonnet-4
allowedTools: [Read, Grep, Glob]
---
# Code Reviewer
You are a senior code reviewer. Provide constructive, actionable feedback.
## Review Criteria
### Code Quality
- Readability and maintainability
- Naming conventions
- Code organization
- DRY principle adherence
### Correctness
- Logic errors
- Edge cases handling
- Error handling
- Null/undefined checks
### Performance
- Algorithm efficiency
- Unnecessary computations
- Memory usage
- Database query optimization
### Security
- Input validation
- SQL injection risks
- XSS vulnerabilities
- Authentication/authorization
### Testing
- Test coverage
- Test quality
- Edge cases tested
## Output Format
Provide structured feedback:
- **Strengths**: What's done well
- **Issues**: Problems found (with severity)
- **Suggestions**: Improvements
- **Examples**: Code snippets for fixes
Choose different models per agent:
---
name: fast-explorer
model: claude-haiku-4 # Fast, cost-effective
---
---
name: deep-analyzer
model: claude-opus-4 # Most capable
---
Limit tools for focused operation:
---
name: readonly-analyzer
allowedTools: [Read, Grep, Glob] # Analysis only
---
---
name: implementation-agent
allowedTools: [Read, Write, Edit, Bash] # Can modify code
---
> "Have multiple agents analyze different aspects"
# Launches multiple agents in parallel:
- Security review agent
- Performance analysis agent
- Code style agent
- Test coverage agent
# Aggregates results
> "Research → Design → Implement authentication"
# Sequential sub-agents:
1. Research agent: Find best practices
2. Design agent: Create architecture
3. Implementation agent: Write code
4. Review agent: Verify implementation
{
"frontend-agent": "React/UI specialist",
"backend-agent": "API/database specialist",
"devops-agent": "Deployment/infrastructure specialist"
}
Source: Sub-Agents
Agent Teams enable multiple Claude Code instances to collaborate on complex tasks with shared context and direct communication.
Agent Teams (experimental) allow you to coordinate multiple Claude Code sessions working together:
# Key differences from Sub-Agents:
- Sub-Agents: Run within a single session, report only to main agent
- Agent Teams: Independent sessions that can communicate directly with each other
# When to use Agent Teams:
✅ Research and review (multiple perspectives simultaneously)
✅ New modules/features (teammates own separate pieces)
✅ Debugging with competing hypotheses (parallel investigation)
✅ Cross-layer coordination (frontend, backend, tests)
# When NOT to use Agent Teams:
❌ Sequential tasks with dependencies
❌ Same-file edits (coordination overhead)
❌ Simple tasks (overkill)
Agent Teams are disabled by default. Enable in settings:
{
"env": {
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
}
}
Or set the environment variable:
export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
claude
# Describe the task and team structure
> "Create an agent team to review PR #142. Spawn three reviewers:
- One focused on security implications
- One checking performance impact
- One validating test coverage
Have them each review and report findings."
# Claude creates the team and coordinates work
# Use Shift+Up/Down to select and message teammates directly
| Mode | Description | Best For |
|---|---|---|
in-process | All teammates in main terminal | Any terminal, simple setup |
tmux | Each teammate in own pane | Parallel visibility, tmux/iTerm2 |
auto (default) | Uses tmux if already in tmux session | Automatic selection |
Configure in settings:
{
"teammateMode": "in-process"
}
Or via CLI flag:
claude --teammate-mode in-process
# Select teammates
Shift+Up/Down # Cycle through teammates
# View teammate session
Enter # View selected teammate's session
Escape # Interrupt teammate's turn
# Manage tasks
Ctrl+T # Toggle shared task list
# Delegate mode
Shift+Tab # Toggle delegate mode (lead only coordinates, doesn't implement)
# Shut down
> "Ask the researcher teammate to shut down"
> "Clean up the team"
| Component | Description |
|---|---|
| Team Lead | Main session that creates team, spawns teammates, coordinates work |
| Teammates | Independent Claude Code instances working on assigned tasks |
| Task List | Shared work items that teammates claim and complete |
| Mailbox | Messaging system for inter-agent communication |
Storage Locations:
~/.claude/teams/{team-name}/config.json~/.claude/tasks/{team-name}/Use hooks to enforce quality gates:
{
"hooks": {
"TeammateIdle": [
{
"hooks": [
{
"type": "command",
"command": "bash -c 'if [ ! -f ./dist/output.js ]; then echo \"Build artifact missing\" >&2; exit 2; fi'"
}
]
}
],
"TaskCompleted": [
{
"hooks": [
{
"type": "command",
"command": "bash -c 'if ! npm test 2>&1; then echo \"Tests failing\" >&2; exit 2; fi'"
}
]
}
]
}
}
Source: Agent Teams
The agent view is one list of every Claude Code session — running, blocked on you, or done. It shipped as a research preview in v2.1.139 and became the main surface for long-running work through the v2.1.14x–v2.1.21x releases. Background sessions keep working after you detach, survive updates and reboots of the CLI process, and can be attached to from any terminal.
# Open the dashboard
claude agents
# Or press the left arrow from an interactive session
# ← (single press from a foreground session since v2.1.196)
Sessions are grouped into Needs input, Working, and Completed. Rows show a colored state word, a classifier-written headline, linked pull requests, and how many background agents are waiting on you.
# Start a session directly in the background
claude --bg "refactor the auth module"
# Name it so you can address it later
claude --bg --name auth-refactor "refactor the auth module"
# Run a plain shell command as an attachable background session (v2.1.154)
claude --bg --exec 'npm run build:watch'
# Send the session you are in to the background
/background # or press ←
claude attach <id> # Attach to a running background session
claude logs <id> # Show its output
claude stop <id> # Stop it
claude respawn <id> # Restart a stopped session
claude rm <id> # Remove it permanently
claude daemon status # Inspect the background-session daemon
Scripting the list:
claude agents --json # Live sessions as JSON (id, state, waitingFor, PR links)
claude agents --json --all # Include completed sessions
claude agents --cwd ./services # Scope the list to a directory
--json output is designed for status bars, session pickers, and tmux integrations.
Since v2.1.142/v2.1.143, claude agents accepts the same configuration flags it will pass to sessions dispatched from the dashboard:
claude agents \
--add-dir ../lib --settings ./ci.json --mcp-config ./mcp.json --plugin-dir ./plugins \
--permission-mode plan --model opus --effort high
--agent <name> overrides the agent field from settings.json for dispatched sessions.
Background sessions edit code inside an isolated git worktree rather than your checkout, so your working tree stays untouched:
| Piece | Behavior |
|---|---|
EnterWorktree / ExitWorktree tools | Enter, switch between, and leave Claude-managed worktrees |
worktree.baseRef | fresh branches from origin/<default>, head from local HEAD |
worktree.sparsePaths | Sparse-checkout only the directories you need in a monorepo |
worktree.bgIsolation: "none" | Let background sessions edit the working copy directly |
isolation: "worktree" | Agent frontmatter option so a subagent runs in its own worktree |
WorktreeCreate / WorktreeRemove hooks | Custom VCS setup and teardown |
Background agents launched from claude agents commit, push, and open a draft PR when they finish code work in a worktree (v2.1.198).
| Key | Action |
|---|---|
← | Open the agent view / leave a session running in the background |
Enter | Open or wake the selected session |
Ctrl+T | Pin a session so it stays alive when idle |
Ctrl+R | Rename a session |
Ctrl+X | Delete a session (twice to confirm) |
Ctrl+X Ctrl+K | Stop all background agents |
! | Dispatch a shell command as a background session |
/resume | Open a picker of past sessions and resume one in the background |
Notifications: sessions that need input or finish fire the Notification hook with agent_needs_input / agent_completed (v2.1.198).
Source: Agent View
Dynamic workflows let Claude orchestrate work across tens to hundreds of agents in the background. Introduced in v2.1.154, a workflow is generated on demand for the task you describe, runs its agents in phases, and reports progress in a status row below the prompt.
# Ask for one in your own words
> ultracode: migrate every service off the deprecated auth client
# Or just describe the task and ask for a workflow
> run a workflow to add tests to every module missing coverage
# Review runs
/workflows
The trigger keyword was renamed from workflow to ultracode in v2.1.160 — the plain word "workflow" no longer starts a run. The keyword is highlighted in the prompt input, and alt+w (or Backspace right after typing it) dismisses the request.
{
"workflowSizeGuideline": "medium"
}
/config under Dynamic workflow size, or in any settings file via workflowSizeGuideline (v2.1.219)./config.| Capability | Notes |
|---|---|
agent({schema}) | Structured output per agent; aborts after 5 schema-validation failures |
isolation: "worktree" | Workflow agents can run in their own git worktree |
| Status filtering | Press f in the /workflows agent detail view |
| Telemetry | workflow.run_id and workflow.name OTel attributes on spawned agents |
Related: /effort ultracode is the session setting, not the prompt keyword — it sends xhigh to the model and has Claude orchestrate a workflow for every substantive task until the session ends. It is a Claude Code setting rather than a model effort level (max is the deepest model reasoning level), it applies to the current session only, and it is offered only on models that support xhigh.
Auto mode replaces per-tool permission prompts with a safety classifier that adjudicates each action. It moved from an opt-in experiment to the default-available permission mode over v2.1.111–v2.1.207.
| Release | Change |
|---|---|
| v2.1.111 | Auto mode available for Max subscribers on Opus 4.7; no longer needs --enable-auto-mode |
| v2.1.152 | Auto mode no longer requires opt-in consent |
| v2.1.158 | Available on Bedrock, Vertex, and Foundry with CLAUDE_CODE_ENABLE_AUTO_MODE=1 |
| v2.1.207 | No opt-in needed on Bedrock/Vertex/Foundry; disable with disableAutoMode |
| v2.1.210 | Classifier defaults to Sonnet 5 for external sessions, pinned for the session |
Cycle into it with Shift+Tab, or set "permissions": { "defaultMode": "auto" }.
{
"disableAutoMode": false,
"autoMode": {
"classifyAllShell": true,
"allow": ["$defaults", "Bash(npm test *)"],
"soft_deny": ["$defaults"],
"hard_deny": ["Bash(curl * | sh)"],
"environment": ["$defaults"]
}
}
"$defaults" keeps the built-in rule list instead of replacing it (v2.1.118).hard_deny rules block unconditionally, regardless of user intent or allow exceptions (v2.1.136).classifyAllShell routes all Bash/PowerShell commands through the classifier, not only arbitrary-code-execution patterns (v2.1.193).autoMode from ~/.claude/settings.json, not from repo-resident .claude/settings.local.json (v2.1.207).claude auto-mode reset restores the default configuration (v2.1.212).git reset --hard, git checkout -- ., git clean -fd, git stash drop) are blocked unless you asked to discard local work; git commit --amend is blocked when the commit wasn't made by the agent this session; terraform/pulumi/cdk destroy require you to name the stack (v2.1.183).PreToolUse hook returning ask floors the decision at a prompt — auto mode cannot override it (v2.1.211)./permissions → Recent, where r retries.{
"hooks": {
"PermissionDenied": [
{
"hooks": [
{ "type": "command", "command": ".claude/hooks/on-denied.sh" }
]
}
]
}
}
PermissionDenied fires after an auto mode classifier denial. Returning {"retry": true} tells the model it may try again.
Plugins bundle Skills, Hooks, and MCP servers for easy sharing.
Plugins are packages that extend Claude Code:
# A plugin can contain:
- Skills (capabilities and workflow templates)
- Hooks (automation)
- MCP Servers (external integrations)
- Sub-Agent definitions
# Interactive plugin management
> /plugin
# Options:
- Browse marketplace
- Install plugins
- Enable/disable plugins
- Remove plugins
- Add custom marketplaces
- Search installed plugins [v2.1.14]
Plugin Pinning [NEW v2.1.14]: Plugins can now be pinned to specific git commit SHAs for version stability:
{
"plugins": {
"enabledPlugins": {
"security-toolkit@official#abc123def": true
}
}
}
my-plugin/
├── .claude-plugin/
│ └── plugin.json # Metadata
├── commands/ # Legacy commands (treated as skills)
│ └── my-command.md
├── skills/ # Skills
│ └── my-skill/
│ └── SKILL.md
├── hooks.json # Hook definitions
└── agents/ # MCP servers & sub-agents
└── mcp.json
plugin.json:
{
"name": "my-plugin",
"version": "1.0.0",
"description": "My awesome plugin",
"author": "Your Name",
"homepage": "https://github.com/user/plugin",
"keywords": ["productivity", "testing"]
}
# From marketplace
> /plugin
# Select "Browse marketplace"
# Choose and install
# Team Configuration
# .claude/settings.json
{
"plugins": {
"enabledPlugins": {
"security-toolkit@official": true,
"custom-workflows@team": true
}
}
}
{
"extraKnownMarketplaces": [
{
"name": "company-internal",
"type": "github",
"url": "https://github.com/company/claude-plugins"
},
{
"name": "local-dev",
"type": "directory",
"path": "/path/to/plugins"
}
]
}
Configure in .claude/settings.json (committed to git):
{
"plugins": {
"enabledPlugins": {
"team-workflows@company": true
}
},
"extraKnownMarketplaces": [
{
"name": "company",
"type": "github",
"url": "https://github.com/company/claude-plugins"
}
]
}
When team members trust the repository, plugins install automatically.
When using Claude Code in VSCode:
/usage command [v2.1.14]: Display current plan usage directly in VSCodepython and pip use the correct interpreter (configure via claudeCode.usePythonEnvironment setting)Source: Plugins
The Claude desktop app provides a native interface for running Claude Code sessions locally and integrating with Claude Code on the web.
Key Features:
.worktreeinclude file: Automatically copy gitignored files (like .env) to new worktreesDiff View:
+12 -1) to open the diff viewerGit Worktrees:
Create a .worktreeinclude file in your repository root:
.env
.env.local
**/.claude/settings.local.json
Files matching these patterns that are also in .gitignore will be copied to new worktrees.
Installation:
Source: Desktop Documentation
Phase 1: Understand
# Start by understanding the codebase
> "Read the project structure and explain the architecture"
> "What testing framework is used?"
> "Show me the authentication flow"
# Claude will:
- Read README, package.json, etc.
- Analyze project structure
- Identify key patterns
Phase 2: Plan
# For complex features, plan first
> "I need to add user roles and permissions. Create a plan"
# Claude will:
- Break down the feature
- Identify affected files
- Consider edge cases
- Create TodoWrite tasks
Phase 3: Implement
# Implement incrementally
> "Implement step 1: Add roles to user model"
# Then verify
> "Run the tests"
# Continue
> "Implement step 2: Add permission checks to API"
Phase 4: Verify
# Always verify changes
> "Run all tests"
> "Check for TypeScript errors"
> "Review the changes we made"
# Create commit
> "Create a git commit for these changes"
For complex multi-step work:
> "Add user authentication system"
# Claude creates todos:
TodoWrite todos=[
{"content": "Create User model with password hashing", "status": "in_progress", ...},
{"content": "Implement JWT token generation", "status": "pending", ...},
{"content": "Add login/register endpoints", "status": "pending", ...},
{"content": "Add authentication middleware", "status": "pending", ...},
{"content": "Write integration tests", "status": "pending", ...}
]
# As work progresses, todos update:
# ✅ "Create User model..." - completed
# ⏳ "Implement JWT tokens..." - in_progress
# ⏸️ "Add login/register..." - pending
Parallel (Independent Tasks):
> "Create these three independent components"
# Claude can work on all simultaneously:
- Component A (no dependencies)
- Component B (no dependencies)
- Component C (no dependencies)
Sequential (Dependencies):
> "Set up database, then add user model, then create API"
# Must be done in order:
1. Database setup (others depend on this)
2. User model (API depends on this)
3. API endpoints (depends on model)
Automated Validation:
# After changes, verify automatically
> "Run the following checks:
- TypeScript compilation
- Linting
- All tests
- Build process"
# Or create a skill:
/verify-changes
Multi-Perspective Review:
# Use sub-agents for thorough review
> "Review these changes from multiple perspectives:
- Security issues
- Performance implications
- Code quality
- Test coverage"
# Launches specialized review agents
Claude Code's features form a layered automation stack. Understanding how they combine unlocks powerful workflows.
| # | Synergy | Use Case |
|---|---|---|
| 1 | Explore → Plan → Code → Commit | Standard development workflow |
| 2 | Test-Driven Development | Quality-first coding |
| 3 | MCP + Skills | External tool integrations |
| 4 | Skills + Hooks | Auto-apply expertise + enforce rules |
| 5 | Sub-agents + Background | Parallel isolated work |
| 6 | Multi-Claude Workflows | Git worktrees for parallelism |
| 7 | Context Preservation | Session continuity |
| 8 | Quality Pipeline | Automated quality enforcement |
| 9 | Visual-Driven Development | Screenshots/mockups → code |
| 10 | Log Analysis Pipeline | Unix pipes + Claude |
| 11 | Schema-Driven Development | DB schema → types/API/tests |
| 12 | Dependency Management | Update + test + fix cycle |
| 13 | Documentation Generation | Codebase → living docs |
| 14 | Refactoring with Safety | Large changes without breaking |
| 15 | Incident Response | Production debugging workflow |
Each feature serves a distinct purpose and they build on each other:
| Layer | Feature | Purpose | Invocation |
|---|---|---|---|
| Connection | MCP | External tools (GitHub, Jira, DBs) | Automatic when configured |
| Capability | Skills | Domain expertise + workflows | Auto-activated or via /skill-name |
| Enforcement | Hooks | Quality gates, auto-actions | Lifecycle events |
| Isolation | Sub-agents | Parallel specialized work | Task delegation |
| Bundling | Plugins | Package all of the above | Install once |
Key insight: MCP connects external systems. Skills provide expertise and workflows (both auto-activated and user-invoked). Hooks enforce standards. Sub-agents isolate heavy work.
The recommended workflow from Anthropic's best practices:
# Step 1: Explore - understand what exists
"Read src/auth/ and explain the current authentication flow.
List all files involved and their responsibilities."
# Step 2: Plan - use extended thinking
"Think hard about how to add OAuth2 support. Create a detailed plan
covering: files to modify, new files needed, dependencies, and test strategy."
# Step 3: Code - implement with explicit files
"Implement the OAuth2 changes following the plan. Start with
src/auth/oauth.ts, then update src/auth/index.ts to export it."
# Step 4: Commit - structured message
"Create a commit with message: 'feat(auth): add OAuth2 provider support'"
Why it works: Each step builds context. Exploring first prevents wrong assumptions. Planning with "think hard" engages extended reasoning. Explicit file names reduce ambiguity.
Write tests first, then implement:
# 1. Write failing tests first
"Write tests for a new validateEmail function in src/utils/validation.ts.
Cover: valid emails, invalid formats, empty input, null input.
Use Jest. The function doesn't exist yet - tests should fail."
# 2. Confirm tests fail
"Run npm test -- --testPathPattern=validation"
# 3. Commit the failing tests
"Commit with message: 'test(validation): add email validation tests (red)'"
# 4. Implement to pass
"Now implement validateEmail in src/utils/validation.ts to pass all tests.
Use a standard regex pattern. No external dependencies."
# 5. Verify and commit
"Run the tests again. If passing, commit: 'feat(validation): implement email validation (green)'"
Why it works: Tests define the contract before implementation. Claude iterates against concrete targets. Git history shows the TDD discipline.
MCP servers expose prompts that become skills:
# Add MCP server
claude mcp add github -- gh-mcp
# Now available as commands:
/github-pr-review # Review current PR
/github-issues # List open issues
/github-create-pr # Create PR from current branch
# Example workflow - complete ticket
/github-issues # "Show me issue #42"
# Claude fetches issue details via MCP
"Implement the feature described in issue #42.
Follow our patterns in src/features/."
/github-create-pr # Creates PR linked to issue
Real MCP integrations: GitHub, Jira, Linear, Notion, PostgreSQL, Slack, Figma, Google Drive. Each adds domain-specific commands.
Skills activate automatically; hooks enforce at lifecycle events:
.claude/
├── skills/
│ └── security-review/
│ └── SKILL.md # Auto-activates on security-related tasks
└── settings.json # Hook: block commits if security issues found
Skill definition (.claude/skills/security-review/SKILL.md):
---
name: security-review
description: Analyzes code for security vulnerabilities. Activates when
reviewing auth code, API endpoints, or user input handling.
allowed-tools: [Read, Grep, Glob]
---
When activated, check for:
- SQL injection (string concatenation in queries)
- XSS (unescaped user input in HTML)
- Exposed secrets (API keys, passwords in code)
- Broken auth (missing token validation)
Report findings with file:line references and severity.
Hook definition (in settings.json):
{
"hooks": {
"PreToolUse": [{
"tool": "Bash",
"command": "git commit",
"script": ".claude/hooks/security-check.sh"
}]
}
}
Workflow:
"Review the authentication code in src/auth/ for security issues"
# Skill auto-activates, finds issues
"Fix the SQL injection vulnerability in src/auth/login.ts:45"
# You fix it
"Commit the security fix"
# Hook runs security-check.sh before allowing commit
# Blocks if issues remain, allows if clean
Isolate work and run in parallel:
# Start services in background (Ctrl+B or explicit)
"Run npm run dev in background"
"Run npm test -- --watch in background"
# Check running tasks
/tasks
# Main session: Use explorer agent for research
"Use the explorer agent to find all API endpoints and their handlers"
# Parallel work happening:
# - Background: Dev server on port 3000
# - Background: Test watcher re-running on changes
# - Sub-agent: Scanning codebase for endpoints
# - Main session: Available for next task
# Later, retrieve agent results
"What did the explorer agent find?"
Sub-agent types: Explore (codebase search), Plan (architecture), custom agents defined in .claude/agents/.
Run multiple Claude instances for independent work:
# Terminal 1: Feature development
cd feature-branch-worktree
claude
"Implement the user dashboard feature"
# Terminal 2: Code review (same repo, different worktree)
cd review-worktree
claude
"Review the changes in the user-dashboard branch for security and performance"
# Terminal 3: Documentation
cd docs-worktree
claude
"Update API documentation based on recent changes"
Advanced: Claude reviewing Claude:
# Claude 1 writes code
"Implement rate limiting for the API endpoints in src/api/"
# Claude 2 reviews (different session)
"Review the rate limiting implementation. Check for:
- Edge cases (what happens at exactly the limit?)
- Race conditions (concurrent requests)
- Configuration flexibility (can limits be changed without deploy?)"
Combine CLAUDE.md + skills for continuity:
Project CLAUDE.md:
# Project: E-commerce API
## Current Sprint
- [ ] Implement payment webhooks
- [ ] Add inventory tracking
- [x] User authentication (completed Jan 10)
## Key Decisions
- Using Stripe for payments (see docs/adr/001-payment-provider.md)
- PostgreSQL for inventory (see src/db/schema.sql)
## Commands
npm run dev # Start on port 3000
npm test # Run Jest tests
npm run db:seed # Seed test data
Skill for context loading (.claude/skills/resume/SKILL.md):
---
name: resume
description: Resume work on current sprint
---
Read CLAUDE.md and the current sprint tasks.
Check git log for recent commits.
Summarize: what's done, what's in progress, what's next.
Ask what I want to work on.
Usage:
claude
/resume
# Claude reads context, summarizes state, ready to continue
Automated quality enforcement:
Hook configuration:
{
"hooks": {
"PostToolUse": [{
"tool": "Write",
"script": "npm run lint:fix -- $FILE"
}, {
"tool": "Edit",
"script": "npm run lint:fix -- $FILE"
}],
"PreToolUse": [{
"tool": "Bash",
"command": "git commit",
"script": ".claude/hooks/pre-commit.sh"
}]
}
}
Pre-commit hook script:
#!/bin/bash
npm run lint || exit 1
npm test || exit 1
echo "All checks passed"
Result: Every file edit auto-lints. Every commit requires passing tests. Quality enforced without manual intervention.
Use screenshots and mockups as implementation targets:
# Share a design mockup
"Here's the Figma mockup for the new dashboard @mockups/dashboard.png
Implement this in src/components/Dashboard.tsx using our existing
Button, Card, and Chart components. Match the layout exactly."
# Iterate on visual feedback
"Here's a screenshot of the current result @screenshots/current.png
Compare to the mockup. Fix: the spacing between cards is wrong,
and the chart colors don't match."
# Debug visual issues
"This screenshot shows a layout bug on mobile @bugs/mobile-layout.png
The sidebar overlaps the content. Fix the responsive styles in
src/styles/layout.css"
Why it works: Claude can see images. Concrete visual targets reduce ambiguity. Iteration is fast.
Unix pipes + Claude for real-time analysis:
# Monitor logs for anomalies
tail -f /var/log/app.log | claude -p "Alert me if you see errors or unusual patterns"
# Analyze crash dumps
cat crash.log | claude -p "Analyze this crash. Identify root cause and suggest fix."
# Parse and summarize
grep "ERROR" app.log | claude -p "Categorize these errors by type and frequency. Which is most critical?"
# CI/CD integration
npm test 2>&1 | claude -p "If tests failed, explain why and suggest fixes"
Why it works: Claude integrates with Unix pipelines. Composable with existing tools.
Database schema as source of truth:
# Generate types from schema
"Read prisma/schema.prisma and generate TypeScript interfaces
in src/types/database.ts. Include JSDoc comments explaining each field."
# Create API endpoints from schema
"Based on the User model in schema.prisma, create CRUD endpoints
in src/api/users.ts. Include validation using zod."
# Generate test fixtures
"Read the schema and create realistic test fixtures in
tests/fixtures/users.ts. Cover edge cases: empty strings,
max lengths, special characters."
# Migration safety check
"Compare prisma/schema.prisma with the current database.
Identify breaking changes. Suggest migration strategy."
Why it works: Schema is the contract. Generate everything from it. Single source of truth.
Update, test, and fix in one flow:
# Check for updates
"Run npm outdated. For each major update, explain breaking changes
and effort to upgrade."
# Upgrade with safety net
"Upgrade lodash to v5. Run tests. If anything breaks, fix it.
Commit only when tests pass."
# Security audit flow
"Run npm audit. For each vulnerability:
1. Check if we actually use the affected code path
2. If yes, upgrade or find alternative
3. If no, document why it's acceptable"
# License compliance
"Check licenses of all dependencies. Flag any GPL or unknown
licenses. We need MIT/Apache/BSD only."
Why it works: Dependency management is tedious. Claude handles the research and fixes.
Codebase exploration → living documentation:
# API documentation
"Explore src/api/ and generate OpenAPI spec in docs/api.yaml.
Include request/response examples from actual code."
# Architecture documentation
"Analyze the codebase structure. Create docs/ARCHITECTURE.md
explaining: folder structure, data flow, key patterns used."
# Onboarding guide
"Create docs/ONBOARDING.md for new developers. Include:
setup steps, key files to understand first, common tasks,
gotchas you found in the code."
# Changelog from commits
"Read git log for the last month. Generate CHANGELOG.md
grouped by: Features, Fixes, Breaking Changes."
Why it works: Documentation stays in sync with code. Generated from source, not memory.
Large refactors without breaking things:
# Rename with confidence
"Rename the User class to Account across the entire codebase.
Update all imports, types, and documentation. Run tests after."
# Extract component
"The Dashboard component is 500 lines. Extract the chart logic
into src/components/DashboardChart.tsx. Keep all behavior identical.
Tests must still pass."
# Change data structure
"Migrate from storing user.fullName to user.firstName + user.lastName.
Update: database schema, API responses, frontend display, tests.
Create migration script for existing data."
# Upgrade patterns
"Replace all callback-style async code in src/services/ with
async/await. One file at a time. Test after each file."
Why it works: TodoWrite tracks progress. Tests verify correctness. Safe incremental changes.
Debug production issues systematically:
# Initial triage
"Production is returning 500 errors. Here's the error log:
[paste log]
Identify the most likely cause. List files to investigate."
# Root cause analysis
"Read the files identified. Trace the code path from
API endpoint to error. Explain exactly where and why it fails."
# Fix with minimal blast radius
"Implement the smallest possible fix. Don't refactor.
Just stop the bleeding. Add a TODO for proper fix later."
# Post-mortem documentation
"Create docs/incidents/2024-01-15-500-errors.md documenting:
what happened, root cause, fix applied, prevention measures."
Why it works: Structured approach prevents panic. Documentation prevents recurrence.
Based on Anthropic's guidance:
| Instead of... | Write... |
|---|---|
| "Add tests" | "Write Jest tests for src/utils/date.ts covering: formatDate with valid dates, invalid inputs, and timezone handling" |
| "Fix the bug" | "The login fails when email contains '+'. Fix src/auth/validate.ts:23 to handle plus signs in email addresses" |
| "Review this" | "Review src/api/users.ts for: N+1 queries, missing error handling, and SQL injection risks" |
| "Make it faster" | "Profile the /api/products endpoint. Identify the slowest operation and optimize it. Target: <100ms response" |
Thinking modes (escalating reasoning depth):
"think" - Standard extended thinking"think hard" - More thorough analysis"think harder" - Deep exploration of options"ultrathink" - Maximum reasoning budgetFile references:
# Use tab-completion or explicit paths
"Read @src/auth/login.ts and explain the authentication flow"
# Multiple files
"Compare @src/api/v1/users.ts and @src/api/v2/users.ts - what changed?"
1. Understand the "when" of each feature:
| Feature | Activates When... |
|---|---|
| MCP | External data/action needed |
| Skills | Context matches description (automatic) |
| Commands | User types /command (manual) |
| Hooks | Lifecycle event fires (PreToolUse, PostToolUse, etc.) |
| Sub-agents | Task delegated for isolated work |
2. Combinations multiply value:
MCP alone = 1x (fetch data)
MCP + Skill = 3x (fetch + auto-expertise)
MCP + Skill + Hook = 9x (fetch + expertise + enforce)
Each layer multiplies the previous. Invest in setup.
3. Prompting is the foundation: All synergies fail with vague prompts. Master specificity first:
4. We showed 15 synergies. There are many more. These patterns are starting points. Combine them, adapt them, discover your own. The best workflows are the ones tailored to your project.
5. Setup cost amortizes:
One hour configuring .claude/ saves hundreds of hours across future sessions. Treat it as infrastructure.
# Understanding current system
> "Analyze the current user management system"
# Planning
> "Create a plan to add JWT-based authentication"
# Implementation
> "Implement the authentication system following the plan"
# (Claude creates TodoWrite tasks and works through them)
# Testing
> "Create comprehensive tests for authentication"
# Security review
> "Review the authentication implementation for security issues"
# Documentation
> "Update the API documentation with authentication endpoints"
# Commit
> "Create a git commit for the authentication feature"
# Identify issues
> "Analyze the codebase for performance bottlenecks"
# Create optimization plan
> "Create a plan to optimize the most critical issues found"
# Implement optimizations
> "Implement the database query optimizations"
# Benchmark
> "Create benchmarks to measure the improvements"
# Verify
> "Run the benchmarks and compare before/after"
# Provide context
> "Users report login fails intermittently. Here's the error log: [paste log]"
# Investigation with Debug agent
> "Use the debugger agent to investigate this issue"
# Root cause analysis
> "Explain what's causing this and why it's intermittent"
# Fix
> "Implement a fix for this issue"
# Prevention
> "Add tests and logging to prevent this in the future"
# Documentation
> "Update CLAUDE.md with what we learned about this issue"
# Analyze current API
> "Document all endpoints in the v1 API"
# Plan migration
> "Create a migration plan from v1 to v2 with these changes: [list changes]"
# Implement new version
> "Implement the v2 API alongside v1"
# Ensure backward compatibility
> "Create a compatibility layer so v1 clients still work"
# Testing
> "Create tests ensuring both v1 and v2 work correctly"
# Documentation
> "Generate migration guide for API consumers"
# Research
> "Research GitHub Actions best practices for Node.js projects"
# Create workflow
> "Create a GitHub Actions workflow that:
- Runs on pull requests
- Checks TypeScript compilation
- Runs linting
- Runs all tests
- Reports coverage"
# Security scanning
> "Add security scanning to the workflow"
# Deployment
> "Add automatic deployment to staging on merge to main"
# Documentation
> "Document the CI/CD setup in README.md"
# Add directories
> "Add the frontend and backend directories to the workspace"
# Synchronized changes
> "Update the User type definition in backend and propagate to frontend"
# Cross-project validation
> "Ensure the frontend API calls match the backend endpoints"
# Parallel testing
> "Run backend tests and frontend tests in parallel in background"
# Monitor both
> "Start both dev servers and monitor for errors"
# Start all development services in background
> "Start the frontend dev server in background"
> "Start the backend API server in background"
> "Run tests in watch mode in background"
# Configure status line to track all services
/statusline
# Monitor all services simultaneously
> "Monitor all background processes for errors"
# Claude watches logs from all background tasks
# Identifies issues across services
# Suggests fixes without stopping services
# Fix issues dynamically
> "I see an API timeout error"
# Claude checks backend logs, identifies cause, suggests solution
# Check all background tasks
/bashes
# Stop specific service if needed
/kill <id>
# Start major feature development
> "Build a complete user authentication system with JWT, refresh tokens, and password reset"
# Work progresses, context accumulates...
# After reading many files and multiple operations
# Context is getting large
# Use microcompact for intelligent cleanup
/compact "focus"
# Keeps: Current auth work, recent changes, patterns learned
# Removes: Old file reads, completed searches, stale context
# Continue seamlessly with clean context
> "Add two-factor authentication to the system"
# Full context available for current authentication work
# Major context switch to new feature
/compact
# Complete reset for fresh start
> "Implement Stripe payment integration"
# Clean slate for payment feature
# Plan with security considerations
> "Design a user input handling system for our forms. Focus on security best practices"
# Implement with immediate security review
> "Implement the form validation system"
> "Review the form validation code for security vulnerabilities"
# Fix identified issues
> "Fix the XSS vulnerability in the email field validation"
> "Verify the fix addresses all injection vectors"
# Document security patterns
> "Update CLAUDE.md with our input validation security patterns"
# Set up continuous security monitoring
> "Create a GitHub Action that runs security scans on every PR"
# Initialize multi-repo workspace
/add-dir ~/projects/backend
/add-dir ~/projects/frontend
/add-dir ~/projects/shared-types
# Synchronize type definitions across projects
> "Update the User type in shared-types and ensure backend and frontend are consistent"
# Parallel type checking
> "Run TypeScript type checking in all three projects simultaneously in background"
# Monitor and fix type errors
> "Check background tasks for any type errors"
> "Fix type mismatches found in frontend"
# Cross-repo validation
> "Verify that all API types in backend match the frontend client expectations"
# Start all dev servers
> "Start backend server, frontend server, and type watching in background"
# Unified development experience
> "Build the checkout flow, coordinating changes across backend API and frontend UI"
# Claude makes coordinated changes across all repos
1. Set Up CLAUDE.md First
- Document your project structure
- List important commands
- Note conventions and patterns
- Add known gotchas
- Update it as you learn
2. Use Descriptive Requests
# Good
> "Add input validation to the login endpoint, checking email format and password length"
# Less effective
> "Fix login"
3. Verify Changes
# Always review before committing
> "Show me all the changes made"
> "Run tests to verify the changes"
4. Incremental Development
# Break large features into steps
> "First, let's add the database model"
> "Now add the API endpoint"
> "Finally, add the frontend form"
5. Leverage Tools Intelligently
# Use Grep for finding patterns
> "Find all database queries using raw SQL"
# Use Glob for file discovery
> "Find all test files"
# Use sub-agents for exploration
> "Have an Explore agent map out the authentication flow"
Quick decision trees for common scenarios:
Something's not working:
→ Can you reproduce it?
→ Yes: Debug systematically
→ No: Gather more info first
→ Did it work before?
→ Yes: Check recent changes (git diff)
→ No: Check assumptions
→ Is error message clear?
→ Yes: Address directly
→ No: Trace execution with logging
Adding a new feature:
→ Similar feature exists?
→ Yes: Follow that pattern
→ No: Research best practices
→ Touches existing code?
→ Yes: Understand it first (read, analyze)
→ No: Design in isolation
→ Has complex logic?
→ Yes: Break down first (use TodoWrite)
→ No: Implement directly
Code seems slow:
→ Measured it? → No: Profile first
→ Know the bottleneck? → No: Find it (use ultrathink)
→ Have solution? → No: Research, then implement and measure again
Recovery When Things Go Wrong:
# Establish facts
> "What's the current state of the codebase?"
# Find smallest step forward
> "What's the simplest fix that would work?"
# Question assumptions
> "Let me re-read the relevant code"
# Find solid ground
> "Let's revert to the last working state with /rewind"
Complexity-Driven Approach:
| Task Type | Approach |
|---|---|
| Trivial (typo fix) | Just fix it |
| Simple (add button) | Quick implementation |
| Medium (new feature) | Plan → Implement → Test |
| Complex (architecture) | Research → Design → Prototype → Implement → Migrate |
| Unknown | Explore to assess, then choose approach |
1. Share Configuration
# Commit to git:
.claude/
├── settings.json # Shared permissions and config
├── commands/ # Team workflows
├── skills/ # Team Skills
└── agents/ # MCP servers & sub-agents
# Git-ignore:
.claude/settings.local.json # Personal overrides
2. Document Patterns in CLAUDE.md
## Team Conventions
- All API routes follow RESTful patterns
- Database migrations use Prisma
- Tests use the AAA pattern (Arrange, Act, Assert)
- Never commit directly to main
3. Create Workflow Skills
# .claude/skills/
├── code-review/
│ └── SKILL.md
├── deploy-staging/
│ └── SKILL.md
├── run-checks/
│ └── SKILL.md
└── security-audit/
└── SKILL.md
4. Use Hooks for Standards
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{"type": "command", "command": "eslint-check.sh"}
]
}
]
}
}
1. Protect Sensitive Files
{
"permissions": {
"deny": [
"Read(*.env)",
"Read(.env.*)",
"Read(*.key)",
"Read(*.pem)",
"Edit(*.env)",
"Edit(.env.*)",
"Edit(*.key)",
"Edit(*.pem)",
"Edit(.git/**)"
]
}
}
Deny Read as well as Edit — a rule that only blocks edits still lets Claude read the secret into context. Edit rules cover all file-editing tools, so no separate Write rule is needed.
2. Review Before Execution
{
"permissions": {
"defaultMode": "default",
"ask": ["Bash", "Edit"]
}
}
There is no "ask" permission mode. Stay in "default" mode and add ask rules for the tools you want to confirm every time.
3. Use Hooks for Auditing
{
"hooks": {
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "echo \"$(date): $TOOL_NAME\" >> .claude/audit.log"
}
]
}
]
}
}
4. Regular Security Reviews
# Use security review Skill or command
> "Perform a security audit of the authentication system"
Issue: "Context too large" error
# Solution 1: Compact context
> /compact
# Solution 2: Smart cleanup
> /compact "focus"
# Prevention: Regular compaction in long sessions
Issue: Edit tool fails with "string not found"
# Solution: Read the file first to see exact content
> Read the file to see the exact string
# Ensure exact match including:
- Whitespace and indentation
- Line breaks
- Special characters
# Use larger context if string appears multiple times
Issue: Permission denied
# Solution 1: Grant permission when asked
# Solution 2: Pre-configure in settings.json
# (allow/ask/deny are arrays of "Tool(specifier)" strings)
{
"permissions": {
"allow": ["Bash(npm test)", "Edit"]
}
}
# Check current permissions
> /hooks # Shows hook configuration
Issue: Claude doesn't see recent file changes
# Solution: Explicitly ask to re-read
> "Read the app.ts file again"
# Or provide the changes
> "I just updated the config, here's what changed: [paste]"
Issue: Background task not responding
# Check status
> /bashes
# Kill if stuck
> /kill <id>
# Restart
> "Start the dev server again in background"
Issue: Git operations fail
# Check git status
> "Run git status"
# Common fixes:
- Unstaged changes: "git add the files first"
- Merge conflicts: "Show me the conflicts and help resolve"
- Branch issues: "Switch to the correct branch"
Issue: MCP server not working
# Check configuration
> "Show me the MCP configuration"
# Verify server is running
> "Check if the MCP server started correctly"
# Check logs
~/.claude/logs/mcp-<server-name>.log
# Reinstall
> "Reinstall the MCP server package"
Systematic approaches to common error scenarios.
# If session disconnects mid-task:
1. Check recent history:
> "What was I working on?"
2. Review file changes:
git diff
3. Reconstruct state:
> "Based on recent changes, continue where we left off"
# If hook blocks unexpectedly:
1. Check hook output:
claude --debug
2. Test hook manually:
echo '{"tool_name":"Edit","tool_input":{...}}' | ~/.claude/hooks/script.sh
3. Temporarily disable:
mv ~/.claude/settings.json ~/.claude/settings.json.bak
4. Fix and restore:
# Fix the hook script, then restore settings
# When "context too large" appears during complex work:
# Quick recovery:
> /compact "focus"
> "Continue with [brief task summary]"
# Full reset if needed:
> /compact
> "Let me brief you: [key context]"
# Prevention:
- Use /compact "focus" every ~50 operations
- Start fresh sessions for new features
# When permissions repeatedly requested:
# Grant permanently (a bare tool name allows every use of that tool;
# "Edit" already covers all file-editing tools, including Write):
{
"permissions": {
"allow": ["Bash", "Edit"]
}
}
# Or specific patterns:
{
"permissions": {
"allow": ["Bash(npm test)", "Bash(npm run build)"]
}
}
# If operations timeout:
# Retry with backoff:
1st attempt → fails
Wait 2s → retry
Wait 4s → retry
Wait 8s → retry
# Switch model if persistent:
> "Use a different model to try this"
# Check network:
ping anthropic.com
curl -v https://api.anthropic.com
# If changes weren't saved:
1. Check git:
git status
git diff
2. Check file backups:
ls -la ~/.claude/backups/
3. Review session transcript:
# Transcripts saved in ~/.claude/transcripts/
4. Reconstruct from memory:
> "Based on our conversation, recreate the [feature]"
# Enable comprehensive debugging:
claude --debug --log-level trace
# Follow logs in real-time:
tail -f ~/.claude/logs/claude.log
# Filter for specific issues:
grep -i error ~/.claude/logs/claude.log
grep -i "mcp" ~/.claude/logs/claude.log
Claude Code operates with:
1. Permission System
2. Sandboxing (macOS/Linux)
{
"sandbox": {
"enabled": true,
"allowUnsandboxedCommands": false
}
}
3. File Access Control
{
"permissions": {
"additionalDirectories": ["/allowed/path"],
"deny": [
"Read(*.key)",
"Read(*.pem)",
"Read(*.env)",
"Edit(*.key)",
"Edit(*.pem)",
"Edit(*.env)",
"Edit(.git/**)"
]
}
}
1. Never Commit Secrets
# Block in settings
{
"permissions": {
"deny": [
"Read(*.env)",
"Read(*.key)",
"Read(*.pem)",
"Read(*secret*)",
"Edit(*.env)",
"Edit(*.key)",
"Edit(*.pem)",
"Edit(*secret*)"
]
}
}
# Use hooks to scan for secrets
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{"type": "command", "command": "detect-secrets-hook.sh"}
]
}
]
}
}
2. Review AI-Generated Code
# Always review before deploying
> "Explain the security implications of this code"
> "Review this for potential vulnerabilities"
3. Limit Tool Access
// For sub-agents doing analysis
{
"allowedTools": ["Read", "Grep", "Glob"] // No modifications
}
// For implementation agents
{
"allowedTools": ["Read", "Write", "Edit", "Bash"] // Can modify
}
4. Audit Trails
{
"hooks": {
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "logger.sh" // Log all operations
}
]
}
]
}
}
5. Network Restrictions
{
"sandbox": {
"network": {
"allowUnixSockets": ["/var/run/docker.sock"],
"allowLocalBinding": true,
"httpProxyPort": 8080
}
}
}
Source: Settings, Sandboxing
Claude Code can be used programmatically via TypeScript/Python SDKs.
import { ClaudeCodeSDK } from '@anthropic-ai/claude-code';
const sdk = new ClaudeCodeSDK({
apiKey: process.env.ANTHROPIC_API_KEY
});
// Start a session
const session = await sdk.startSession({
projectDir: '/path/to/project',
systemPrompt: 'You are a code reviewer'
});
// Send a task
const response = await session.chat({
message: 'Review this codebase for security issues'
});
console.log(response.content);
// End session
await session.end();
from anthropic_sdk import ClaudeCodeSDK
sdk = ClaudeCodeSDK(api_key=os.environ["ANTHROPIC_API_KEY"])
# Start session
session = sdk.start_session(
project_dir="/path/to/project",
system_prompt="You are a test generator"
)
# Send task
response = session.chat(
message="Generate tests for all API endpoints"
)
print(response.content)
# End session
session.end()
Source: SDK Overview
⚠️ Warning: This section contains theoretical concepts and patterns that are NOT verified in official documentation. These are experimental ideas for power users to explore.
Unverified theory about optimizing Claude's approach based on task type:
# Simple Creation Mode
> "Create 5 similar React components"
# Theory: Parallel processing, template-based
# Optimization Mode
> "Optimize this algorithm"
# Theory: Deep analysis, multiple approaches
# Research Mode
> "Research and implement best practice for X"
# Theory: Web search → analysis → implementation pipeline
Status: No official documentation supports "modes". Claude Code uses the same model for all tasks.
Unverified theoretical framework about multi-layered intelligence:
Theory:
┌─────────────────┐
│ Orchestrator │
└────────┬────────┘
│
┌────┴────┬────────┬─────────┐
│ │ │ │
Memory Intent Extract Validate
Kernel Kernel Kernel Kernel
Status: This is a conceptual model, not an actual Claude Code feature. Claude Code uses:
But NOT a "kernel architecture" system.
Unverified theory about advanced task management with AI validation:
# Theory: Multi-agent task validation
1. Intent Capture (4 approaches)
2. Multi-Agent Validation
3. Background Execution
4. Learning Integration
Status: TodoWrite is a real tool, but "meta-todo" with multi-agent validation is theoretical. Use the actual TodoWrite tool as documented.
The original guide mixed:
This caused confusion about what Claude Code actually does vs. conceptual ideas.
For AI Agents reading this: Focus on sections marked [OFFICIAL] and [COMMUNITY]. Treat [EXPERIMENTAL] as ideas to test, not established features.
For complete details, see the official CHANGELOG.md.
Version 2.1.220 (July 25, 2026) - Latest
Version 2.1.219 (July 24, 2026)
claude-opus-5) is now available and is the default Opus model — 1M context, fast mode at $10/$50 per MTok [NEW]sandbox.network.strictAllowlist setting to deny non-allowlisted hosts for sandboxed commands without promptingDirectoryAdded hook that fires after /add-dir (or the SDK register_repo_root control request) registers a new working directory mid-session [NEW]workflowSizeGuideline settings key so the Dynamic workflow size guideline can be set from any settings fileCLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH=1 to disable nestingmcp_server_errors to the headless stream-json init event, listing --mcp-config entries skipped by config validation--forward-subagent-text is set/config/fast now applies to Opus 5 and Opus 4.8claude mcp list and /mcp when a server fails to connectclaude -p text output dropping the answer already produced when a turn died on a mid-stream API errorCLAUDE_CODE_GIT_BASH_PATH on Windows exiting or being used as bash when the path isn't a bash/sh binaryVersion 2.1.218 (July 22, 2026)
/code-review now runs as a background subagent, so review work no longer fills your conversationcontext: fork now run in the background by default; opt out per skill with background: false/deep-research now starts only when invoked manually; Claude no longer launches it on its own--ax-screen-reader moderm, background-&, and suspicious-Windows-path checks no longer open permission dialogs; the classifier adjudicates them\u-prefixed segments (like C:\Users\unicorn) being corrupted into CJK characters in tool inputs/context reporting stale pre-compact token usage after compacting from the message pickertool_use block after interrupted tool calls:, which is reserved for plugin namespacingyes/no/on/off/1/0 alongside true/falseVersion 2.1.217 (July 21, 2026)
:heart:); disable with the emojiCompletionEnabled setting [NEW]CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS)--max-budget-usd not stopping background subagents — new spawns are denied and running background agents halted once the cap is reachedclaude.exe missing; failed updates now restore the preserved executable/compact failing once over the limitVersion 2.1.216 (July 20, 2026)
sandbox.filesystem.disabled setting to skip filesystem isolation while keeping network egress controlgit -C, --git-dir, or GIT_DIR/GIT_WORK_TREE.claude, which could redirect writes outside the project/rewind no longer restores or deletes files through symlinks or hard links at tracked paths&& lists or negationsclaude daemon stop --any potentially terminating an unrelated process via a stale legacy daemon lockfileVersion 2.1.215 (July 19, 2026)
/verify and /code-review skills on its own; invoke them explicitly when you want themVersion 2.1.214 (July 18, 2026)
dir/** allow rules like Edit(src/**) auto-approving writes to nested dir/ directories anywhere in the tree[[ ]]docker commands carrying daemon-redirect flags (--url, --connection, --identity, Podman remote mode)message.uuid, client_request_id, and tool_source attributes to OpenTelemetry log eventsCLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH to configure the 60 KB truncation limit on OpenTelemetry content attributesmodified timestamp to memory file frontmatterdir/** hook if: conditions now match only <cwd>/dir; write **/dir/** for any-depth matchingSessionStart hooks now report source "fork" when a session begins as a fork instead of "resume"UnicodeDecodeError/UnicodeEncodeError on non-UTF-8 data, and UTF-16LE redirect outputVersion 2.1.212 (July 17, 2026)
/fork now copies your conversation into a new background session (its own row in claude agents); the in-session subagent it used to launch is now /subtaskclaude auto-mode reset to restore the default auto-mode configuration (--yes skips the confirmation)CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION) to stop runaway search loopsCLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION); /clear resets the budgetCLAUDE_CODE_MCP_AUTO_BACKGROUND_MS)touch, rm) without a permission prompt or SDK canUseTool callback.claude/worktreescontinue:false hook's halt being dropped when the tool fails or completes mid-streammode parameter (now ignored); subagents inherit the parent session's permission mode by defaultforceLoginMethod is now enforced for VS Code, SDK, setup-token, and install-github-app logins, not just the terminal/background and claude --bg failing with uv_spawn errors on Windows when Group Policy blocks PowerShell 5.1SendMessage bodies are no longer duplicated into replayed historyVersion 2.1.211 (July 15, 2026)
--forward-subagent-text flag and CLAUDE_CODE_FORWARD_SUBAGENT_TEXT env var to include subagent text and thinking in stream-json output [NEW]PreToolUse hook's ask decision for unsandboxed Bash — a hook ask now floors the decision at a prompt/clear not resetting the session cost counter1e6 and 64_000 spellingsVersion 2.1.210 (July 14, 2026)
isolation: 'worktree' subagents being able to run git-mutating commands against the main repo checkoutWrite(path), NotebookEdit(path), and Glob(path) permission rules — use Edit(path) or Read(path) instead$1/$2 positional placeholders in skills and commands being silently stripped — they are now preserved verbatimVersion 2.1.209 (July 14, 2026)
/model and other dialogs being blocked in claude agents background sessionsVersion 2.1.208 (July 14, 2026)
claude --ax-screen-reader, CLAUDE_AX_SCREEN_READER=1, or "axScreenReader": true in settings [NEW]vimInsertModeRemaps setting to map two-key insert-mode sequences like jj to Escape in vim modeCLAUDE_CODE_PROCESS_WRAPPER so corporate launchers can wrap every Claude Code self-spawnclaude -pCLAUDE_CODE_MAX_OUTPUT_TOKENS and similar env vars silently using the mantissa of scientific-notation values (1e6 became 1)/release-notes adding the viewed notes to the model's context$(…)/backticks/<(…) now prompt in --dangerously-skip-permissions and auto modeVersion 2.1.207 (July 11, 2026)
CLAUDE_CODE_ENABLE_AUTO_MODE opt-in on Bedrock, Vertex AI, and Foundry; disable via disableAutoModeheadersHelper: ${user_config.*} in shell-form commands is now rejected (shell-injection fix)pluginConfigs) are no longer read from project-level .claude/settings.jsonautoMode from .claude/settings.local.json; use ~/.claude/settings.json instead~/.local/bin/claude on every releaseVersion 2.1.206 (July 10, 2026)
/cd, matching /add-dir behavior/doctor check that proposes trimming checked-in CLAUDE.md filesEnterWorktree now asks for confirmation before entering a git worktree outside .claude/worktrees//commit-push-pr now auto-allows git push to the repo's configured push remote (remote.pushDefault) in addition to origin--mcp-config or .mcp.json ignoring a per-server request_timeout_msCLAUDE_CODE_EXTRA_BODY being silently ignored by claude agents / --bg background workersclaude --resume and --continue not responding to keyboard input on startupVersion 2.1.205 (July 8, 2026)
/doctor is now a full setup checkup that can diagnose and fix issues; /checkup is an alias--json-schema silently producing unstructured output when the schema was invalid, and schemas using format being rejected--max-turns limitrm -rf on a variable it can't resolve from contextVersion 2.1.204 (July 8, 2026)
SessionStart hooks in headless sessions, which could cause remote workers to be idle-reaped mid-hookVersion 2.1.203 (July 7, 2026)
roots/list, with notifications/roots/list_changed on changeclaude agents silently stopping running subagents and re-running the prompt from scratchPATH from the daemon instead of the dispatching shellANTHROPIC_BASE_URLTaskStop and TaskOutput failing to find background agents spawned by another agentVersion 2.1.202 (July 6, 2026)
/config controlling how large Claude generally makes dynamic workflows (advisory, not an enforced cap)workflow.run_id and workflow.name OpenTelemetry attributes to telemetry emitted by workflow-spawned agents/review <pr> is back to a fast single-pass review; use /code-review <level> <pr#> for the multi-agent review/rename on background sessions being reverted when the job restartsVersion 2.1.201 (July 3, 2026)
Version 2.1.200 (July 3, 2026)
AskUserQuestion dialogs no longer auto-continue by default; opt into an idle timeout via /config--help, VS Code, and JetBrains; --permission-mode manual and "defaultMode": "manual" are accepted alongside defaultdisabledMcpServers or enabledMcpServers in .claude.json is set to a non-array valuedaemon.lock whose PID the OS reusedHeader: value. linesVersion 2.1.199 (July 2, 2026)
/skill-a /skill-b do XYZ now load all leading skills (up to 5), not just the firTruncated — view the full README on GitHub.
688 followers · starred Sep 2025
165 followers · starred Nov 2025
244 followers · starred Aug 2025
25 followers · starred Sep 2025
The Complete Claude Code CLI Guide - Live & Auto-Updated Every 2 Days
Shell
2,867
46 commits
updated Jul 27, 2026
Quick Links: Get Started · Commands · MCP Setup · Settings · SDK · Changelog
🔄 Live Guide: Auto-updated every 2 days from official docs, GitHub releases, and Anthropic changelog. See update-log.md.
🤖 For AI Agents: Optimized for both humans and AI.
[OFFICIAL]= from code.claude.com.[COMMUNITY]= observed patterns.[EXPERIMENTAL]= unverified.
Claude Code is an agentic AI coding assistant that lives in your terminal. It understands your codebase, edits files directly, runs commands, and helps you code faster through natural language conversation.
Key Capabilities:
Installation:
# Quick Install (macOS, Linux, WSL)
curl -fsSL https://claude.ai/install.sh | bash
# Windows PowerShell
irm https://claude.ai/install.ps1 | iex
# Windows CMD
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
# Alternative: Homebrew (macOS/Linux)
brew install --cask claude-code
# Alternative: WinGet (Windows)
winget install Anthropic.ClaudeCode
# Alternative: NPM (⚠️ Deprecated - use native install instead)
npm install -g @anthropic-ai/claude-code
claude --version # Verify installation
Official Documentation: https://code.claude.com/docs/en/overview
# Starting Claude Code
claude # Start interactive session
claude -p "task" # Print mode (non-interactive)
claude --continue # Continue last session
claude --resume <id> # Resume specific session
# Session Management
/help # Show available commands
/exit # End session
/compact # Reduce context size
/compact [instructions] # Compact conversation with optional focus instructions
# Background Tasks
/bashes # List background processes
/kill <id> # Stop background process
# Discovery
/commands # List skills and commands
/hooks # Show configured hooks
/skills # List available Skills (NEW)
/plugin # Manage plugins
Source: CLI Reference
# Output Control
claude -p, --print "task" # Print mode: non-interactive, prints result and exits
claude --output-format json # Output format: text, json, or stream-json
claude --input-format text # Input format: text or stream-json
claude --verbose # Enable verbose logging (full turn-by-turn output)
# Session Management
claude --continue # Continue from last session
claude --resume <session-id> # Resume specific session by ID or name
claude --from-pr <pr> # Resume session linked to GitHub PR number or URL [NEW]
claude --fork-session # Create new session ID instead of reusing original
claude --session-id <uuid> # Use specific session ID (must be valid UUID)
# Remote Sessions (claude.ai subscribers)
claude --remote "task" # Create web session on claude.ai
claude --teleport # Resume web session in local terminal
claude --remote-control # Bridge this session to claude.ai/code (mobile/web)
claude --channels # Allow MCP servers to push messages in (research preview) [NEW]
# Background Sessions & Agent View [NEW]
claude agents # Open the agent view: every session, running/blocked/done
claude agents --json # List live sessions as JSON (add --all for completed)
claude agents --cwd <path> # Scope the session list to a directory
claude --bg "task" # Start the session in the background
claude --bg --exec '<command>' # Run a shell command as an attachable background session
claude --bg --name <label> # Name the background session
claude attach <id> # Attach to a background session
claude logs <id> # Show a background session's output
claude stop <id> / claude rm <id> # Stop or remove a background session
claude respawn <id> # Restart a stopped background session
claude daemon status # Inspect the background-session daemon
# Debugging & Logging
claude --debug # Enable debug mode (with optional category filtering)
claude --debug "api,mcp" # Debug specific categories
claude --debug "!statsig,!file" # Exclude categories with !
# Model & Agent Configuration
claude --model <name> # Specify model (sonnet, opus, haiku, or full name)
claude --fallback-model <name> # Fallback model when overloaded (interactive too, v2.1.166)
claude --effort high # Set reasoning effort (low/medium/high/xhigh/max/ultracode) [NEW]
claude --agent <name> # Specify custom agent (overrides settings)
claude --agents '<json>' # Define custom subagents dynamically via JSON
claude --forward-subagent-text # Include subagent text/thinking in stream-json output [NEW]
# System Prompt Customization
claude --system-prompt "prompt" # Replace entire default system prompt
claude --system-prompt-file <path> # Replace with file contents (print mode only)
claude --append-system-prompt "..." # Append to default system prompt
claude --append-system-prompt-file <path> # Append file contents (print mode only)
# Tool & Permission Management
claude --tools "Bash,Read,Edit" # Restrict built-in tools (use "" to disable all)
claude --allowedTools "Bash(git:*)" # Tools that execute without prompting
claude --disallowedTools "Edit" # Tools removed from context
claude --permission-mode plan # Begin in specified permission mode
claude --permission-mode manual # "default" mode renamed to "manual" in v2.1.200 [NEW]
claude --dangerously-skip-permissions # Skip all permission prompts ⚠️
claude --allow-dangerously-skip-permissions # Enable bypass option without activating [NEW]
claude --permission-prompt-tool <mcp-tool> # MCP tool for permission prompts (non-interactive) [NEW]
# Budget & Execution Limits (print mode)
claude --max-budget-usd 5.00 # Maximum dollar amount for API calls
claude --max-turns 3 # Limit number of agentic turns
claude --json-schema '<schema>' # Get validated JSON output matching schema (print mode) [NEW]
# Directory & Configuration
claude --add-dir ../apps ../lib # Add additional working directories
claude --plugin-dir ./my-plugins # Load plugins from a directory or .zip (repeat for more)
claude --plugin-url <url> # Fetch a plugin .zip archive from a URL for this session [NEW]
claude --worktree, -w <name> # Run the session in an isolated git worktree
claude --settings ./settings.json # Path to settings JSON file
claude --setting-sources user,project # Comma-separated list of setting sources [NEW]
claude --mcp-config ./mcp.json # Load MCP servers from JSON file
claude --strict-mcp-config # Only use MCP servers from --mcp-config
# IDE & Browser Integration
claude --ide # Auto-connect to IDE on startup
claude --chrome # Enable Chrome browser integration
claude --no-chrome # Disable Chrome browser integration
# Agent Teams [NEW]
claude --teammate-mode in-process # Teammates display in main terminal
claude --teammate-mode tmux # Each teammate in own pane (requires tmux/iTerm2)
claude --teammate-mode auto # Auto-detect (default)
# Setup & Maintenance
claude --init # Run Setup hooks and start interactive mode
claude --init-only # Run Setup hooks and exit (no interactive session)
claude --maintenance # Run Setup hooks with maintenance trigger and exit
# Troubleshooting & Accessibility [NEW]
claude --safe-mode # Start with CLAUDE.md, plugins, skills, hooks, MCP disabled
claude --bare # Minimal scripted -p runs (no hooks/LSP/plugin sync)
claude --ax-screen-reader # Opt-in plain-text rendering for screen readers
claude doctor # Full setup checkup that can diagnose and fix issues
# Other Options
claude -n, --name <name> # Set a display name for the session at startup [NEW]
claude --disable-slash-commands # Disable all skills and slash commands
claude --no-session-persistence # Disable session persistence (print mode)
claude --betas interleaved-thinking # Beta headers for API requests
claude --include-partial-messages # Include partial streaming events (with stream-json) [NEW]
claude --exclude-dynamic-system-prompt-sections # Better cross-user prompt caching (print) [NEW]
# Subcommands
claude auth login|status|logout # Manage authentication (--console for API billing)
claude mcp login|logout <name> # Authenticate an MCP server without opening /mcp
claude plugin init|list|details|prune|tag # Plugin authoring and maintenance
claude project purge [path] # Delete all Claude Code state for a project [NEW]
claude auto-mode reset # Restore the default auto-mode configuration [NEW]
Common Flag Combinations:
# One-off task with JSON output
claude --print "analyze this code" --output-format json
# Debug MCP and API issues
claude --debug "api,mcp"
# Resume session with specific model
claude --resume auth-refactor --model opus
# Non-interactive with budget limit (CI/CD)
claude -p --max-budget-usd 5.00 --output-format json "run tests"
# Custom subagents for specialized work
claude --agents '{"reviewer":{"description":"Code reviewer","prompt":"Review for bugs"}}'
# Remote session for claude.ai subscribers
claude --remote "fix the login bug"
Source: CLI Reference
| Tool | Purpose | Permission Required |
|---|---|---|
| Read | Read files, images, PDFs | No |
| Write | Create new files | Yes |
| Edit | Modify existing files | Yes |
| Bash | Execute shell commands | Yes |
| Grep | Search content with regex | No |
| Glob | Find files by pattern | No |
| TodoWrite | Task management | No |
| Task | Launch sub-agents | No |
| WebFetch | Fetch web content | Yes |
| WebSearch | Search the web | Yes |
| NotebookEdit | Edit Jupyter notebooks | Yes |
| NotebookRead | Read Jupyter notebooks | No |
Source: Settings Reference
Claude Code operates through a conversational interface in your terminal:
# You describe what you want
$ claude
> "Add user authentication to the API"
# Claude Code:
1. Analyzes your codebase structure
2. Plans the implementation
3. Requests permission for file edits (first time)
4. Writes code directly to your files
5. Can run tests and verify changes
6. Creates git commits if requested
Key Principles:
Source: Overview
Claude Code uses an incremental permission system for safety:
# Permission Rules — three buckets, each an ARRAY of "Tool(specifier)" strings
"allow" # Permit without asking
"ask" # Prompt before each use
"deny" # Block completely
# Permission Modes — the starting behavior, set with permissions.defaultMode
"default" # Prompt on first use of each tool (alias: "manual")
"acceptEdits" # Auto-accept file edits and common filesystem commands
"plan" # Explore read-only; no source edits
"auto" # Auto-approve with background safety checks
"dontAsk" # Auto-deny anything not pre-approved
"bypassPermissions" # Skip prompts entirely (isolated environments only)
# NOTE: rule buckets and modes are different things. There is no "ask" MODE.
# To prompt before acting, stay in "default" mode and add ask RULES:
# { "defaultMode": "default", "ask": ["Bash", "Edit"] }
# Permission Priority [NEW v2.1.27]
# Content-level rules override tool-level rules
# Example: allow: ["Bash"], ask: ["Bash(rm *)"]
# -> Bash is generally allowed, but "rm *" commands require confirmation
# Tools Requiring Permission
- Bash (command execution)
- Write/Edit/NotebookEdit (file modifications)
- WebFetch/WebSearch (network access)
- Skill (skills and custom commands)
# Tools Not Requiring Permission (Safe Operations)
- Read/NotebookRead (reading files)
- Grep/Glob (searching)
- TodoWrite (task tracking)
- Task (sub-agents)
Configuring Permissions:
Create .claude/settings.json in your project or ~/.claude/settings.json globally:
{
"permissions": {
"defaultMode": "default",
"allow": [
"Bash(git status)",
"Bash(git diff)",
"Bash(git log *)",
"Bash(npm test)",
"Bash(npm run *)",
"Read",
"Edit"
],
"deny": [
"Read(*.env)",
"Read(.env.*)",
"Edit(*.env)",
"Edit(.env.*)",
"Edit(.git/**)"
],
"additionalDirectories": [
"/path/to/other/project"
]
}
}
Rule syntax gotchas:
allow / ask / deny are arrays of "Tool(specifier)" strings, never objects keyed by tool name. An object such as "deny": { "Write": ["*.env"] } is silently ignored."Read" allows all reads.Edit(path), not Write(path). File permission checks match only Edit(path) and Read(path) rules; Write(path), NotebookEdit(path), and Glob(path) rules are accepted but never matched, and warn at startup (v2.1.210+). Edit rules cover all file-editing tools.* matters: Bash(npm run *) matches npm run build but not npm runfoo, while Bash(npm run*) matches both.Read and Edit specifiers use gitignore syntax; a bare filename matches at any depth, so Read(.env) and Read(**/.env) are equivalent.Read(...) and Edit(...) — denying edits alone still lets Claude read the file.Source: Permissions, Settings
A CLAUDE.md file in your project root provides persistent context across sessions:
# Project: My Application
## Critical Context (Read First)
- Language: TypeScript + Node.js
- Framework: Express + React
- Database: PostgreSQL with Prisma ORM
- Testing: Jest + React Testing Library
## Commands That Work
npm run dev # Start dev server (port 3000)
npm test # Run all tests
npm run lint # ESLint check
npm run typecheck # TypeScript validation
npm run db:migrate # Run Prisma migrations
## Important Patterns
- All API routes in /src/routes - RESTful structure
- Database queries use Prisma Client
- Auth uses JWT tokens (implementation in /src/auth)
- Frontend components in /src/components
- API responses: {success: boolean, data: any, error?: string}
## Gotchas & What NOT to Do
- DON'T modify /generated folder (auto-generated by Prisma)
- DON'T commit .env files (use .env.example instead)
- ALWAYS run npm run db:migrate after pulling schema changes
- DON'T use `any` type in TypeScript - use proper typing
## File Structure
/src
/routes # Express API routes
/services # Business logic
/models # Type definitions
/middleware # Express middleware
/utils # Shared utilities
/auth # Authentication logic
## Recent Learnings
- [2026-01-15] Payment webhook needs raw body parser for Stripe
- [2026-01-10] Redis pool: {maxRetriesPerRequest: 3}
Why CLAUDE.md Helps:
Note: While CLAUDE.md is not an official feature, it's a widely-adopted community pattern. Claude Code will automatically read it if present at project root.
Purpose: Read and analyze files
# Examples
Read file_path="/src/app.ts"
Read file_path="/docs/screenshot.png" # Can read images!
Read file_path="/docs/guide.pdf" # Can read PDFs!
Read file_path="/docs/guide.pdf" pages="1-5" # Read specific PDF pages [NEW v2.1.30]
Capabilities:
cat -n format)PDF Parameters [NEW v2.1.30]:
pages: Optional page range (e.g., "1-5", "1,3,5") to read specific pagesSpecial Features:
Purpose: Create new files
Write file_path="/src/newFile.ts"
content="export const config = {...}"
Behavior:
Best Practice: Use Edit tool for modifying existing files, Write tool only for new files.
Purpose: Modify existing files with precise string replacement
Edit file_path="/src/app.ts"
old_string="const port = 3000"
new_string="const port = process.env.PORT || 3000"
Important:
old_string is not unique in file (use larger context or replace_all)replace_all=true to replace all occurrences (useful for renaming)Common Pattern:
# 1. Read file to see exact content
Read file_path="/src/app.ts"
# 2. Edit with exact string match
Edit file_path="/src/app.ts"
old_string="function login() {
return 'TODO';
}"
new_string="function login() {
return authenticateUser();
}"
Purpose: Execute shell commands
Bash command="npm test"
Bash command="git status"
Bash command="find . -name '*.test.ts'"
Features:
run_in_background=true)Security:
Common Git Patterns:
# Check status
Bash command="git status"
# View changes
Bash command="git diff"
# Create commit
Bash command='git add . && git commit -m "feat: add authentication"'
# View history
Bash command="git log --oneline -10"
Purpose: Search file contents with regex patterns
# Find functions
Grep pattern="function.*auth" path="src/" output_mode="content"
# Find TODOs with context
Grep pattern="TODO" output_mode="content" -C=3
# Count occurrences
Grep pattern="import.*from" output_mode="count"
# Case insensitive
Grep pattern="error" -i=true output_mode="files_with_matches"
Parameters:
pattern: Regex pattern (ripgrep syntax)path: Directory or file to search (default: current directory)output_mode:
"files_with_matches" (default) - Just file paths"content" - Show matching lines"count" - Show match counts per file-A, -B, -C: Context lines (after, before, both)-i: Case insensitive-n: Show line numberstype: Filter by file type (e.g., "js", "py", "rust")glob: Filter by glob pattern (e.g., "*.test.ts")Fast and Powerful: Uses ripgrep under the hood, much faster than bash grep on large codebases.
Purpose: Find files by pattern
# Find test files
Glob pattern="**/*.test.ts"
# Find specific extensions
Glob pattern="src/**/*.{ts,tsx}"
# Find config files
Glob pattern="**/config.{json,yaml,yml}"
Features:
** for recursive, {} for alternatives)Purpose: Manage task lists during work
TodoWrite todos=[
{
"content": "Add authentication endpoint",
"status": "in_progress",
"activeForm": "Adding authentication endpoint"
},
{
"content": "Write integration tests",
"status": "pending",
"activeForm": "Writing integration tests"
},
{
"content": "Update API documentation",
"status": "pending",
"activeForm": "Updating API documentation"
}
]
Task States:
"pending" - Not started yet"in_progress" - Currently working on (should be only ONE at a time)"completed" - Finished successfullyDependency Tracking [NEW]: v2.1.16 introduced task dependency tracking, allowing tasks to define prerequisites that must complete before they start. This enables complex multi-step workflows with proper sequencing.
Best Practices:
in_progress at a timecontent (what to do) and activeForm (what you're doing)When to Use:
Purpose: Launch specialized AI agents for specific tasks
# Explore codebase
Task subagent_type="Explore"
prompt="Find all API endpoints and their authentication requirements"
# General purpose agent for complex tasks
Task subagent_type="general-purpose"
prompt="Research best practices for rate limiting APIs and implement a solution"
Available Sub-Agent Types:
"general-purpose" - Complex multi-step tasks, research, implementation"Explore" - Fast codebase exploration (Glob, Grep, Read, Bash)When to Use:
Purpose: Fetch and analyze web page content
WebFetch url="https://docs.example.com/api"
prompt="Extract all endpoint documentation"
Features:
Purpose: Search the web for current information
WebSearch query="React 19 new features 2024"
Use Cases:
Source: CLI Reference, Settings
Purpose: Get code intelligence features like go-to-definition, find references, and hover documentation.
LSP operation="goToDefinition"
filePath="src/utils/auth.ts"
line=42
character=15
Available Operations:
| Operation | Description |
|---|---|
goToDefinition | Find where a symbol is defined |
findReferences | Find all references to a symbol |
hover | Get documentation and type info for a symbol |
documentSymbol | Get all symbols in a document (functions, classes, variables) |
workspaceSymbol | Search for symbols across the entire workspace |
goToImplementation | Find implementations of an interface or abstract method |
prepareCallHierarchy | Get call hierarchy item at a position |
incomingCalls | Find all functions/methods that call the function at a position |
outgoingCalls | Find all functions/methods called by the function at a position |
Parameters:
operation (required): The LSP operation to performfilePath (required): Absolute or relative path to the fileline (required): Line number (1-based, as shown in editors)character (required): Character offset (1-based, as shown in editors)Use Cases:
# Find where a function is defined
> "Go to the definition of getUserById"
# Find all usages of a function
> "Find all references to the authenticate function"
# Get documentation for a symbol
> "What does the validateToken function do?"
# Explore code structure
> "List all symbols in the auth.ts file"
Note: LSP servers must be configured for the file type. If no server is available for a language, an error will be returned.
Source: CLI Reference
Claude Code maintains conversation context with smart management:
/compact # Reduce context by removing old information
/compact "keep auth work" # Compact with focus instructions (keeps specified context)
Use /compact when:
Use /compact with instructions when:
/compact "keep the authentication implementation context"Preserved:
Cleared:
Claude Code may automatically compact when:
Source: Settings
Claude Code can work with multiple directories simultaneously:
# Add another directory to current session
/add-dir /path/to/other/project
# Work across multiple projects
> "Update the User type in backend and propagate to frontend"
# Claude can now access both directories
Use Cases:
Configuration:
You can also pre-configure additional directories in .claude/settings.json:
{
"permissions": {
"additionalDirectories": [
"/path/to/frontend",
"/path/to/backend",
"/path/to/shared-libs"
]
}
}
Customize what information appears in your status line:
# Configure status line
/statusline
# Options typically include:
# - Current model
# - Token usage
# - Session duration
# - Active tools
# - Background processes
Benefits:
Source: CLI Reference
# 1. Navigate to your project
cd /path/to/your/project
# 2. Start Claude Code
claude
# 3. Ask Claude to understand your project
> "Read the codebase and explain the project structure"
# Claude will:
- Look for README, package.json, or similar entry points
- Read relevant files (asks permission first time)
- Analyze the code structure
- Provide a summary
# 4. Request an analysis
> "Review the authentication system for security issues"
# Claude will:
- Find authentication-related files
- Analyze the implementation
- Identify potential vulnerabilities
- Suggest improvements
# 5. Make changes
> "Add rate limiting to the login endpoint"
# Claude will:
- Plan the implementation
- Show you what changes will be made
- Request permission to edit files
- Implement the changes
- Can run tests to verify
# 6. Create a commit
> "Create a git commit for these changes"
# Claude will:
- Run git status to see changes
- Review git diff
- Create a descriptive commit message
- Commit the changes
This provides context that persists across all sessions:
# Ask Claude to help create it
> "Create a CLAUDE.md file documenting this project's structure, commands, and conventions"
# Or create manually with:
- Languages and frameworks used
- Important commands (dev, test, build, lint)
- Project structure overview
- Coding conventions
- Known gotchas or issues
Create .claude/settings.json in your project:
{
"permissions": {
"defaultMode": "default",
"allow": [
"Bash(npm test)",
"Bash(npm run *)",
"Bash(git status)",
"Bash(git diff)",
"Bash(git log *)",
"Read",
"Grep",
"Glob"
],
"deny": [
"Read(*.env)",
"Read(.env.*)",
"Edit(*.env)",
"Edit(.env.*)",
"Edit(.git/**)"
]
}
}
This configuration:
> "Run the tests"
# Should execute without permission prompt (if configured)
> "What commands are available?"
# Claude will read package.json and list scripts
> "What's in CLAUDE.md?"
# Claude will read and summarize your project context
Source: Quickstart, Settings
Claude Code supports extended thinking for complex reasoning tasks. Opus 4.5 has thinking mode enabled by default.
Activation Methods:
# Toggle with keyboard shortcut
Alt+T (or Option+T on macOS) # Toggle thinking on/off
# Or use natural language
> "think about this problem"
> "think harder about the architecture"
> "ultrathink about this security issue"
# Tab key (sticky toggle)
Press Tab to toggle thinking mode on/off for subsequent prompts
Thinking Levels:
| Trigger | Thinking Budget | Use Case |
|---|---|---|
think | Standard | General reasoning, code analysis |
think harder | Extended | Complex problems, multiple approaches |
ultrathink | Maximum | Critical decisions, deep architecture analysis |
Best Practices:
think harder for debugging complex issuesultrathink for architectural decisions or security reviewsCtrl+O transcript modeSource: Thinking Mode
Models added to Claude Code since v2.1.39, newest first. Switch with /model or --model.
| Model | Added | Notes |
|---|---|---|
Claude Opus 5 (claude-opus-5) | v2.1.219 (Jul 24, 2026) | Default Opus model. 1M context. Fast mode at $10/$50 per MTok |
| Claude Sonnet 5 | v2.1.197 (Jun 30, 2026) | Default model in Claude Code. Native 1M-token context. Promotional pricing of $2/$10 per MTok through August 31 |
| Claude Fable 5 | v2.1.170 (Jun 9, 2026) | Mythos-class model made safe for general use. Includes 1M context by default (no [1m] suffix needed) |
| Claude Opus 4.8 | v2.1.154 (May 28, 2026) | Defaults to high effort; /effort xhigh for the hardest tasks. Default Opus on Bedrock, Vertex, and Claude Platform on AWS since v2.1.207 |
| Claude Opus 4.7 | v2.1.111 (Apr 16, 2026) | Introduced the xhigh effort level. Native 1M context window |
| Claude Sonnet 4.6 | v2.1.45 (Feb 17, 2026) | Gained 1M context in v2.1.49 |
Removed / migrated:
Effort levels: /effort (added v2.1.76) accepts low, medium, high, xhigh, max, and ultracode, plus auto to reset to the model default. xhigh arrived in v2.1.111 and ultracode in v2.1.160; ultracode is a Claude Code setting rather than a model level — it sends xhigh and additionally orchestrates dynamic workflows, and it is session-only. max is also session-only unless set through CLAUDE_CODE_EFFORT_LEVEL, and the persisted effortLevel setting accepts only low, medium, high, and xhigh. Defaults have shifted several times — high for API-key/Bedrock/Vertex/Foundry/Team/Enterprise since v2.1.94, high for Pro/Max on Opus 4.6 and Sonnet 4.6 since v2.1.117, and high by default on Opus 4.8. Skills, slash commands, and agents can set effort: in frontmatter, and hooks receive effort.level / $CLAUDE_EFFORT.
Organization controls: admins can set an org default model (shown as "Org default" in /model, v2.1.196), restrict models with availableModels, and harden it with the enforceAvailableModels managed setting (v2.1.175).
Fast mode is a high-speed configuration that makes responses 2.5x faster at a higher cost per token. Available since v2.1.36.
Model support has moved. Fast mode launched on Opus 4.6, switched to Opus 4.7 by default in v2.1.142, added Opus 4.8 at a much lower premium in v2.1.154 (2x the standard rate for 2.5x the speed), and as of v2.1.219
/fastapplies to Opus 5 and Opus 4.8 — Opus 4.7 was removed from fast mode. Opus 5 fast mode is $10/$50 per MTok.CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDEwas deprecated in v2.1.154 and removed in v2.1.160. The pricing table below is the original Opus 4.6 launch pricing and is kept for historical reference.
Toggle Fast Mode:
# Toggle with built-in command
/fast # Toggle on/off
# Or set in settings
"fastMode": true # In user settings file
Visual Indicators:
↯ icon appears next to prompt when fast mode is activePricing (per MTok) — original Opus 4.6 launch pricing:
| Mode | Input (<200K) | Output | Input (>200K) | Output |
|---|---|---|---|---|
| Standard Opus 4.6 | $15 | $75 | $15 | $75 |
| Fast Mode | $30 | $150 | $60 | $225 |
Note: the Opus 4.6 fast-mode discount ran until February 16, 2026. Fast mode on Opus 4.8 is 2x the standard rate (v2.1.154), and Opus 5 fast mode is $10/$50 per MTok (v2.1.219).
Requirements:
/usage-credits, formerly /extra-usage)When to Use:
Fast Mode vs Effort Level:
| Setting | Effect |
|---|---|
| Fast mode | Same quality, lower latency, higher cost |
| Lower effort level | Faster responses, potentially lower quality |
You can combine both for maximum speed on straightforward tasks.
Rate Limits:
Source: Fast Mode
Plan Mode provides structured planning with model selection for complex tasks.
# Enter plan mode
/plan
# Or Claude may suggest plan mode for complex tasks
> "Implement a complete authentication system"
# Claude: "This is a complex task. Would you like me to create a plan first?"
Plan Mode Features:
/clearPlan Mode Workflow:
Source: Plan Mode
Run commands and agents in the background while continuing to work.
Keyboard Shortcut:
Ctrl+B # Background current command or agent (unified shortcut)
Background Commands:
# Start command in background
> "Run the dev server in background"
> "Start tests in watch mode in background"
# Or prefix with &
> "& npm run dev"
# View background tasks
/tasks
/bashes
# Kill a background task
/kill <task-id>
Background Agents:
# Launch agent in background
> "Have an Explore agent analyze the codebase architecture in background"
# Agents run asynchronously and notify you when complete
# You receive wake-up messages when background agents finish
Features:
Source: Background Tasks
Claude Code now automatically records and recalls memories as it works (v2.1.32+).
How It Works:
Memory Scopes for Agents:
---
name: my-agent
memory: project # Options: user, project, local
---
| Scope | Storage | Shared |
|---|---|---|
user | ~/.claude/ | All your projects |
project | .claude/ | Team via git |
local | .claude/*.local.* | No (gitignored) |
Disable Auto-Memory:
export CLAUDE_CODE_DISABLE_AUTO_MEMORY=1
Navigation & Editing:
| Shortcut | Action |
|---|---|
Ctrl+R | Search command history |
Ctrl+O | View transcript (shows thinking blocks) |
Ctrl+G | Edit prompt in system text editor |
Ctrl+Y | Readline-style paste (yank) |
Alt+Y | Yank-pop (cycle through kill ring) |
Ctrl+B | Background current command/agent |
Ctrl+Z | Suspend/Undo |
Model & Mode Switching:
| Shortcut | Action |
|---|---|
Alt+P (Win/Linux) / Option+P (macOS) | Switch models while typing |
Alt+T (Win/Linux) / Option+T (macOS) | Toggle thinking mode |
Tab | Toggle thinking (sticky) / Accept suggestions |
Shift+Tab | Auto-accept edits (plan mode) / Switch modes (Windows) |
Input & Submission:
| Shortcut | Action |
|---|---|
Enter | Submit prompt / Accept suggestion immediately |
Shift+Enter | New line (works in iTerm2, WezTerm, Ghostty, Kitty) |
Tab | Edit/accept prompt suggestion |
Ctrl+T | Toggle syntax highlighting in /theme |
Image & File Handling:
| Shortcut | Action |
|---|---|
Cmd+V (macOS) / Alt+V (Windows) | Paste image from clipboard |
Cmd+N / Ctrl+N | New conversation (VSCode) |
Vim Bindings (if enabled):
| Shortcut | Action |
|---|---|
; and , | Repeat last motion |
y | Yank operator |
p / P | Paste |
Alt+B / Alt+F | Word navigation |
Login & Authentication:
| Shortcut | Action |
|---|---|
c | Copy OAuth URL during login |
Bash Mode Autocomplete [NEW v2.1.14]:
| Shortcut | Action |
|---|---|
! + Tab | History-based autocomplete - complete partial commands from history |
Claude Code suggests prompts based on context (enabled by default).
# Claude suggests contextual prompts
> _ # Cursor blinking
# Suggestion appears: "Review the changes we made"
# Tab to edit the suggestion
Tab → Edit the suggestion text
# Enter to submit immediately
Enter → Submit the suggestion as-is
Configuration:
# Toggle in /config
/config
# Search for "prompt suggestions"
# Toggle enable/disable
Core Configuration:
| Variable | Description |
|---|---|
ANTHROPIC_API_KEY | Your API key |
CLAUDE_CODE_SHELL | Override shell detection |
CLAUDE_CODE_TMPDIR | Custom temp directory |
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS | Disable background task system |
CLAUDE_CODE_ENABLE_TASKS | Set to false to use legacy task system [NEW v2.1.19] |
CLAUDE_CODE_SAFE_MODE | Start with all customizations disabled (same as --safe-mode) [NEW v2.1.169] |
CLAUDE_CODE_SESSION_ID | Session ID exported to the Bash tool and stdio MCP servers [NEW v2.1.132] |
CLAUDE_CODE_DISABLE_BUNDLED_SKILLS | Hide bundled skills, workflows, and built-in slash commands [NEW v2.1.169] |
CLAUDE_CODE_PROCESS_WRAPPER | Run every Claude Code self-spawn through a wrapper executable [NEW v2.1.208] |
CLAUDE_CODE_DISABLE_CRON | Immediately stop scheduled cron jobs mid-session [NEW v2.1.72] |
Display & UI:
| Variable | Description |
|---|---|
CLAUDE_CODE_HIDE_ACCOUNT_INFO | Hide account info in UI |
CLAUDE_CODE_HIDE_CWD | Hide the working directory in the startup logo [NEW v2.1.119] |
CLAUDE_AX_SCREEN_READER | Set to 1 for screen reader mode (same as --ax-screen-reader) [NEW v2.1.208] |
CLAUDE_CODE_NO_FLICKER | Set to 1 for flicker-free alt-screen rendering [NEW v2.1.89] |
CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN | Set to 1 to keep the conversation in native scrollback [NEW v2.1.132] |
CLAUDE_CODE_FORCE_SYNC_OUTPUT | Force synchronized output where auto-detection misses it [NEW v2.1.129] |
CLAUDE_CODE_DISABLE_MOUSE | Disable mouse handling in fullscreen mode |
CLAUDE_CODE_DISABLE_MOUSE_CLICKS | Disable click/drag/hover but keep wheel scroll [NEW v2.1.195] |
CLAUDE_CODE_DISABLE_TERMINAL_TITLE | Don't set the terminal title |
Bash & Commands:
| Variable | Description |
|---|---|
BASH_DEFAULT_TIMEOUT_MS | Default bash command timeout |
BASH_MAX_TIMEOUT_MS | Maximum allowed timeout |
CLAUDE_BASH_NO_LOGIN | Don't use login shell |
CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR | Keep working directory |
CLAUDE_CODE_SHELL_PREFIX | Prefix for shell commands |
Model Configuration:
| Variable | Description |
|---|---|
ANTHROPIC_DEFAULT_SONNET_MODEL | Override default Sonnet model |
ANTHROPIC_DEFAULT_OPUS_MODEL | Override default Opus model |
ANTHROPIC_DEFAULT_HAIKU_MODEL | Override default Haiku model |
ANTHROPIC_DEFAULT_{OPUS,SONNET,HAIKU}_MODEL_SUPPORTS | Override effort/thinking capability detection for pinned 3P models [NEW v2.1.84] |
ANTHROPIC_DEFAULT_{...}_MODEL_NAME / _DESCRIPTION | Customize the /model picker label for pinned models [NEW v2.1.84] |
ANTHROPIC_CUSTOM_MODEL_OPTION | Add a custom entry to the /model picker [NEW v2.1.78] |
ANTHROPIC_BEDROCK_SERVICE_TIER | Bedrock service tier: default, flex, or priority [NEW v2.1.122] |
ANTHROPIC_WORKSPACE_ID | Scope a federated token to a specific workspace [NEW v2.1.141] |
CLAUDE_CODE_USE_MANTLE | Set to 1 for Amazon Bedrock powered by Mantle [NEW v2.1.94] |
CLAUDE_CODE_DISABLE_1M_CONTEXT | Disable 1M context window support [NEW v2.1.50] |
CLAUDE_CODE_ENABLE_AUTO_MODE | Opt into auto mode on Bedrock/Vertex/Foundry [NEW v2.1.158] |
CLAUDE_CODE_EFFORT_LEVEL | Override the reasoning effort level |
ANTHROPIC_LOG | Enable debug logging |
MCP Configuration:
| Variable | Description |
|---|---|
MCP_TIMEOUT | MCP connection timeout |
MCP_TOOL_TIMEOUT | Individual tool timeout |
MCP_CONNECTION_NONBLOCKING | true skips the MCP connection wait in -p mode [NEW v2.1.89] |
CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT | Abort remote MCP tool calls that hang (default 5 min) [NEW v2.1.187] |
CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS | Threshold before long MCP calls move to the background [NEW v2.1.212] |
CLAUDE_CODE_MCP_SERVER_NAME / _URL | Passed to MCP headersHelper scripts [NEW v2.1.85] |
ENABLE_CLAUDEAI_MCP_SERVERS | false opts out of claude.ai MCP servers [NEW v2.1.63] |
File & Context:
| Variable | Description |
|---|---|
CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS | Max tokens for file reads |
CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD | Set to 1 to load CLAUDE.md from --add-dir directories [NEW] |
CLAUDE_PROJECT_DIR | Override project directory |
CLAUDE_PLUGIN_ROOT | Plugin root substitution |
CLAUDE_CONFIG_DIR | Custom config directory |
XDG_CONFIG_HOME | XDG config base path |
Network & Proxy:
| Variable | Description |
|---|---|
NODE_EXTRA_CA_CERTS | Custom CA certificates |
NO_PROXY | Proxy bypass list |
CLAUDE_CODE_PROXY_RESOLVES_HOSTS | Proxy DNS resolution |
Auto-Update & Plugins:
| Variable | Description |
|---|---|
DISABLE_AUTOUPDATER | Disable auto-updates |
FORCE_AUTOUPDATE_PLUGINS | Force plugin updates |
CLAUDE_CODE_EXIT_AFTER_STOP_DELAY | Exit delay after stop |
Monitoring & Telemetry:
| Variable | Description |
|---|---|
CLAUDE_CODE_ENABLE_TELEMETRY | Enable OpenTelemetry collection (1) |
OTEL_METRICS_EXPORTER | OTel metrics exporter (e.g., otlp) |
DISABLE_TELEMETRY | Opt out of Statsig telemetry (1) |
DISABLE_ERROR_REPORTING | Opt out of Sentry error reporting (1) |
DISABLE_COST_WARNINGS | Disable cost warning messages (1) |
Advanced:
| Variable | Description |
|---|---|
CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS | Disable anthropic-beta headers (workaround for gateway users) |
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS | Enable agent teams feature (1) [NEW] |
CLAUDE_CODE_DISABLE_AUTO_MEMORY | Disable automatic memory recording (1) [NEW] |
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS | Disable background task system (1) |
DISABLE_INTERLEAVED_THINKING | Disable interleaved thinking |
USE_BUILTIN_RIPGREP | Use built-in ripgrep |
CLOUD_ML_REGION | Cloud ML region for Vertex |
AWS_BEARER_TOKEN_BEDROCK | AWS bearer token |
MAX_THINKING_TOKENS | Extended thinking budget (default: 31,999) |
MAX_MCP_OUTPUT_TOKENS | Max MCP tool response tokens (default: 25,000) |
CLAUDE_CODE_MAX_OUTPUT_TOKENS | Max output tokens (default: 32,000, max: 64,000) |
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC | Disable autoupdate, bug reporting, telemetry |
Subagents & Background Sessions: [NEW]
| Variable | Description |
|---|---|
CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS | Cap on subagents running at once (default 20) [v2.1.217] |
CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION | Cap on subagent spawns per session (default 200) [v2.1.212] |
CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH | Nested subagent depth (default 3 since v2.1.219; 1 disables nesting) |
CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION | Cap on WebSearch calls per session (default 200) [v2.1.212] |
CLAUDE_CODE_SUBAGENT_MODEL | Model used for subagents |
CLAUDE_CODE_FORK_SUBAGENT | Set to 1 to enable forked subagents on external builds [v2.1.117] |
CLAUDE_CODE_FORWARD_SUBAGENT_TEXT | Include subagent text/thinking in stream-json output [v2.1.211] |
CLAUDE_CODE_DISABLE_BG_SHELL_PRESSURE_REAP | Disable memory-pressure reaping of idle background shells [v2.1.193] |
Retries, Caching & Timeouts: [NEW]
| Variable | Description |
|---|---|
CLAUDE_CODE_MAX_RETRIES | Retry count (capped at 15 since v2.1.186) |
CLAUDE_CODE_RETRY_WATCHDOG | Raises the transient-error retry count to 300 for unattended sessions [v2.1.199] |
CLAUDE_ENABLE_STREAM_WATCHDOG | 0 disables the 5-minute stream idle watchdog [v2.1.196] |
CLAUDE_STREAM_IDLE_TIMEOUT_MS | Streaming idle watchdog threshold (default 90 s) [v2.1.84] |
ENABLE_PROMPT_CACHING_1H | Opt into 1-hour prompt cache TTL [v2.1.108] |
FORCE_PROMPT_CACHING_5M | Force 5-minute prompt cache TTL [v2.1.108] |
CLAUDE_CODE_STOP_HOOK_BLOCK_CAP | Consecutive Stop-hook blocks before the turn ends (default 8) [v2.1.143] |
CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS | SessionEnd hook timeout on exit [v2.1.74] |
Security & Enterprise: [NEW]
| Variable | Description |
|---|---|
CLAUDE_CODE_SUBPROCESS_ENV_SCRUB | Strip Anthropic and cloud credentials from subprocess environments [v2.1.83] |
CLAUDE_CODE_SCRIPT_CAPS | Limit per-session script invocations [v2.1.98] |
CLAUDE_CODE_CERT_STORE | bundled uses only bundled CAs instead of the OS trust store [v2.1.101] |
CLAUDE_CLIENT_PRESENCE_FILE | Marker file that suppresses mobile push while you're at the machine [v2.1.181] |
DISABLE_UPDATES | Block all update paths including manual claude update [v2.1.118] |
Windows & Shell: [NEW]
| Variable | Description |
|---|---|
CLAUDE_CODE_USE_POWERSHELL_TOOL | Opt in/out of the PowerShell tool [v2.1.111] |
CLAUDE_CODE_POWERSHELL_RESPECT_EXECUTION_POLICY | Don't pass -ExecutionPolicy Bypass [v2.1.143] |
CLAUDE_CODE_GIT_BASH_PATH | Path to Git Bash on Windows |
CLAUDE_CODE_PERFORCE_MODE | Fail on read-only files with a p4 edit hint instead of overwriting [v2.1.98] |
Telemetry (additions): [NEW]
| Variable | Description |
|---|---|
OTEL_LOG_ASSISTANT_RESPONSES | 1 un-redacts claude_code.assistant_response content; 0 keeps prompts-only [v2.1.193] |
OTEL_LOG_TOOL_DETAILS | Include tool parameters and custom command names in events [v2.1.85] |
OTEL_LOG_RAW_API_BODIES | Emit full API request/response bodies as OTel log events [v2.1.111] |
CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH | Truncation limit on OTel content attributes (default 60 KB) [v2.1.214] |
OTEL_METRICS_INCLUDE_ENTRYPOINT | Add the session entrypoint as a metric attribute [v2.1.152] |
Recent settings additions (configure in /config or settings.json):
{
// Response language
"language": "en", // Claude's response language
// Git integration
"attribution": true, // Add model name to commit bylines
"respectGitignore": true, // Respect .gitignore in searches
// UI preferences
"showTurnDuration": true, // Show turn duration messages
"fileSuggestion": "custom-cmd", // Custom @ file search command
"spinnerVerbs": ["analyzing", "thinking", "processing"], // Custom spinner verbs
"prefersReducedMotion": false, // Reduce UI animations for accessibility [NEW v2.1.30]
// Session behavior
"companyAnnouncements": true, // Show startup announcements
// Plan mode
"plansDirectory": ".claude/plans" // Custom directory for plan files
}
Settings Added Since v2.1.39 [NEW] [OFFICIAL]
| Setting | Description |
|---|---|
tui | Renderer mode; /tui fullscreen switches in-session [v2.1.110] |
autoScrollEnabled | Disable conversation auto-scroll in fullscreen mode [v2.1.110] |
showThinkingSummaries | true restores thinking summaries in interactive sessions [v2.1.89] |
axScreenReader | Opt-in plain-text rendering for screen readers [v2.1.208] |
wheelScrollAccelerationEnabled | Disable mouse-wheel scroll acceleration in fullscreen [v2.1.174] |
emojiCompletionEnabled | Toggle :shortcode: emoji autocomplete in the prompt [v2.1.217] |
vimInsertModeRemaps | Map two-key insert-mode sequences like jj to Escape [v2.1.208] |
footerLinksRegexes | Regex-matched link badges in the footer row [v2.1.176] |
prUrlTemplate | Point the footer PR badge at a custom code-review URL [v2.1.119] |
refreshInterval | Re-run the status line command every N seconds [v2.1.97] |
spinnerTipsOverride | Custom spinner tips (tips, excludeDefault) [v2.1.45] |
feedbackSurveyRate | Enterprise session-quality survey sample rate [v2.1.76] |
respondToBashCommands | false keeps ! bash output context-only [v2.1.186] |
showClearContextOnPlanAccept | Restore the "clear context" option on plan accept [v2.1.81] |
disableBundledSkills | Hide bundled skills, workflows, and built-in slash commands [v2.1.169] |
disableSkillShellExecution | Disable inline shell execution in skills and commands [v2.1.91] |
skillOverrides | off, user-invocable-only, or name-only per skill [v2.1.129] |
autoMemoryDirectory | Custom directory for auto-memory storage [v2.1.74] |
includeGitInstructions | Remove built-in commit/PR instructions from the system prompt [v2.1.69] |
attribution.sessionUrl | Omit the claude.ai session link from commits and PRs [v2.1.183] |
fallbackModel | Up to three fallback models tried in order [v2.1.166] |
modelOverrides | Map /model entries to custom provider model IDs (e.g. Bedrock ARNs) [v2.1.73] |
disableAutoMode | Turn auto mode off [v2.1.207] |
autoMode.classifyAllShell | Route all shell commands through the auto-mode classifier [v2.1.193] |
autoMode.hard_deny | Classifier rules that block unconditionally [v2.1.136] |
autoMode.allow / soft_deny / environment | Custom rules; include "$defaults" to keep built-ins [v2.1.118] |
worktree.baseRef | fresh (branch from origin/<default>) or head [v2.1.133] |
worktree.sparsePaths | Sparse-checkout paths for --worktree in monorepos [v2.1.76] |
worktree.bgIsolation | "none" lets background sessions edit the working copy directly [v2.1.143] |
workflowSizeGuideline | Advisory size guideline for dynamic workflows [v2.1.219] |
sandbox.credentials | Block sandboxed commands from reading credential files/secrets [v2.1.187] |
sandbox.filesystem.disabled | Skip filesystem isolation, keep network egress control [v2.1.216] |
sandbox.filesystem.allowRead | Re-allow reads inside a denyRead region [v2.1.77] |
sandbox.network.deniedDomains | Block domains a broader allowedDomains wildcard would permit [v2.1.113] |
sandbox.network.strictAllowlist | Deny non-allowlisted hosts without prompting [v2.1.219] |
sandbox.failIfUnavailable | Exit with an error instead of running unsandboxed [v2.1.83] |
sandbox.allowAppleEvents | Let sandboxed commands send Apple Events on macOS [v2.1.181] |
sandbox.enableWeakerNetworkIsolation | macOS TLS verification through a MITM proxy [v2.1.69] |
sandbox.bwrapPath / sandbox.socatPath | Custom bubblewrap/socat locations on Linux and WSL [v2.1.133] |
disableDeepLinkRegistration | Prevent claude-cli:// protocol handler registration [v2.1.83] |
Managed (admin) settings added since v2.1.39: enforceAvailableModels, requiredMinimumVersion / requiredMaximumVersion, forceRemoteSettingsRefresh, parentSettingsBehavior, pluginSuggestionMarketplaces, allowedChannelPlugins, allowAllClaudeAiMcps, pluginTrustMessage, wslInheritsWindowsSettings, plus the managed-settings.d/ drop-in directory.
Skills Variable Substitution: [NEW]
# In skill files, use ${CLAUDE_SESSION_ID} for session-specific operations
Session ID: ${CLAUDE_SESSION_ID}
Project Rules:
# New: .claude/rules/ directory for project-specific rules
.claude/rules/
├── coding-style.md # Coding conventions
├── testing.md # Testing requirements
└── security.md # Security guidelines
Wildcard Permissions:
{
"permissions": {
"allow": [
"Bash(npm *)",
"Bash(git *)",
"mcp__myserver__*"
]
}
}
Bash(npm *) and Bash(git *) are wildcard command patterns; mcp__myserver__* allows every tool from the myserver MCP server.
Skills are unified capabilities that extend Claude Code — both auto-activated by Claude and manually invoked via /skill-name.
Note: Custom slash commands (
.claude/commands/files) have been merged into skills as of v2.1.3. Your existing command files keep working unchanged. Skills are recommended for new work because they support additional features like supporting files, invocation control, and subagent execution. See Migration: Commands to Skills.
Claude Code skills follow the Agent Skills open standard, which works across multiple AI tools. Claude Code extends the standard with additional features like invocation control, subagent execution, and dynamic context injection.
Skills are instructions packaged as SKILL.md files that extend what Claude Code can do. Claude loads them when relevant to your request, or you invoke them directly:
# Claude auto-activates a skill based on your request
You: "Review this code for security issues"
Claude: [Loads security-reviewer skill automatically]
# Or you invoke a skill directly
You: /security-reviewer src/auth.ts
Claude: [Loads and executes the security-reviewer skill]
Two types of skill content:
/skill-name.Where you store a skill determines who can use it:
| Location | Path | Applies To |
|---|---|---|
| Enterprise | Managed settings | All users in organization |
| Personal | ~/.claude/skills/<skill-name>/SKILL.md | All your projects |
| Project | .claude/skills/<skill-name>/SKILL.md | This project only |
| Plugin | <plugin>/skills/<skill-name>/SKILL.md | Where plugin is enabled |
When skills share the same name, higher-priority locations win: Enterprise > Personal > Project. Plugin skills use a plugin-name:skill-name namespace, so they cannot conflict.
Legacy compatibility: Files in .claude/commands/ still work and support the same frontmatter. If a skill and a command share the same name, the skill takes precedence.
Automatic nested directory discovery: When you work with files in subdirectories, Claude Code discovers skills from nested .claude/skills/ directories. For example, editing a file in packages/frontend/ also loads skills from packages/frontend/.claude/skills/. This supports monorepo setups where packages have their own skills.
Live change detection: Skills from directories added via --add-dir are loaded automatically and picked up by live change detection — edit them during a session without restarting.
Each skill is a directory with SKILL.md as the entrypoint:
my-skill/
├── SKILL.md # Main instructions (required)
├── template.md # Template for Claude to fill in (optional)
├── examples/
│ └── sample.md # Example output (optional)
└── scripts/
└── validate.sh # Script Claude can execute (optional)
Reference supporting files from your SKILL.md so Claude knows what each file contains:
## Additional resources
- For complete API details, see [reference.md](reference.md)
- For usage examples, see [examples.md](examples.md)
Tip: Keep
SKILL.mdunder 500 lines. Move detailed reference material to separate files.
Step 1: Create the skill directory:
# Personal skill (available in all projects)
mkdir -p ~/.claude/skills/explain-code
# Project skill (shared with team via git)
mkdir -p .claude/skills/explain-code
Step 2: Write SKILL.md with frontmatter and instructions:
---
name: explain-code
description: Explains code with visual diagrams and analogies. Use when explaining how code works, teaching about a codebase, or when the user asks "how does this work?"
---
When explaining code, always include:
1. **Start with an analogy**: Compare the code to something from everyday life
2. **Draw a diagram**: Use ASCII art to show the flow, structure, or relationships
3. **Walk through the code**: Explain step-by-step what happens
4. **Highlight a gotcha**: What's a common mistake or misconception?
Keep explanations conversational. For complex concepts, use multiple analogies.
Step 3: Test the skill:
# Let Claude invoke it automatically
> "How does this code work?"
# Or invoke it directly
> /explain-code src/auth/login.ts
Configure skill behavior with YAML frontmatter between --- markers at the top of SKILL.md. All fields are optional; only description is recommended.
| Field | Required | Description |
|---|---|---|
name | No | Display name. If omitted, uses directory name. Lowercase letters, numbers, hyphens (max 64 chars). |
description | Recommended | What the skill does and when to use it. Claude uses this to decide when to load it. |
argument-hint | No | Hint shown during autocomplete (e.g., [issue-number] or [filename] [format]). |
disable-model-invocation | No | true → only user can invoke via /name. Default: false. |
user-invocable | No | false → hidden from / menu, only Claude can invoke. Default: true. |
allowed-tools | No | Tools Claude can use without asking permission when skill is active. |
model | No | Model to use when skill is active. |
context | No | Set to fork to run in a forked subagent context. |
agent | No | Which subagent type to use when context: fork is set. |
hooks | No | Hooks scoped to this skill's lifecycle. See Hooks. |
By default, both you and Claude can invoke any skill. Two frontmatter fields restrict this:
disable-model-invocation: true — Only you can invoke. Use for workflows with side effects (e.g., /deploy, /commit).user-invocable: false — Only Claude can invoke. Use for background knowledge that isn't actionable as a command.# User-only skill (Claude won't auto-trigger)
---
name: deploy
description: Deploy the application to production
disable-model-invocation: true
---
# Model-only skill (hidden from / menu)
---
name: legacy-system-context
description: Background knowledge about the legacy system
user-invocable: false
---
Invocation and context-loading behavior:
| Frontmatter | You Can Invoke | Claude Can Invoke | When Loaded into Context |
|---|---|---|---|
| (default) | Yes | Yes | Description always in context; full skill loads when invoked |
disable-model-invocation: true | Yes | No | Description not in context; full skill loads when you invoke |
user-invocable: false | No | Yes | Description always in context; full skill loads when invoked |
Restricting Claude's access via /permissions:
# Allow only specific skills
Skill(commit)
Skill(review-pr *)
# Deny specific skills
Skill(deploy *)
# Disable all skills
Skill # Add to deny rules
Permission syntax: Skill(name) for exact match, Skill(name *) for prefix match with any arguments.
Skills accept arguments via placeholder substitutions:
| Variable | Description |
|---|---|
$ARGUMENTS | All arguments passed when invoking the skill |
$ARGUMENTS[N] | Specific argument by 0-based index (e.g., $ARGUMENTS[0]) |
$N | Shorthand for $ARGUMENTS[N] (e.g., $0, $1) |
${CLAUDE_SESSION_ID} | Current session ID (useful for logging) |
Example:
---
name: fix-issue
description: Fix a GitHub issue
disable-model-invocation: true
---
Fix GitHub issue $ARGUMENTS following our coding standards.
1. Read the issue description
2. Implement the fix
3. Write tests
4. Create a commit
/fix-issue 123
# Claude receives: "Fix GitHub issue 123 following our coding standards..."
Indexed arguments:
---
name: compare-files
description: Compare two files
---
# Compare: $ARGUMENTS[0] vs $ARGUMENTS[1]
# Shorthand: $0 vs $1
Compare $0 and $1 for differences.
/compare-files "src/v1/api.ts" "src/v2/api.ts"
# $0 = "src/v1/api.ts", $1 = "src/v2/api.ts"
If $ARGUMENTS is not present in the skill content, arguments are appended as ARGUMENTS: <value>.
The !`command` syntax runs shell commands before the skill content is sent to Claude. The output replaces the placeholder:
---
name: pr-summary
description: Summarize changes in a pull request
context: fork
agent: Explore
allowed-tools: Bash(gh *)
---
## Pull request context
- PR diff: !`gh pr diff`
- PR comments: !`gh pr view --comments`
- Changed files: !`gh pr diff --name-only`
## Your task
Summarize this pull request...
Each !`command` executes immediately (before Claude sees anything). Claude only sees the final result with actual data.
Add context: fork to run a skill in isolation. The skill content becomes the prompt that drives the subagent (no access to conversation history):
---
name: deep-research
description: Research a topic thoroughly
context: fork
agent: Explore
---
Research $ARGUMENTS thoroughly:
1. Find relevant files using Glob and Grep
2. Read and analyze the code
3. Summarize findings with specific file references
The agent field specifies which subagent to use. Options: built-in agents (Explore, Plan, general-purpose) or custom subagents from .claude/agents/. Default: general-purpose.
Warning:
context: forkonly makes sense for skills with explicit instructions. Guidelines without a task will return without meaningful output.
To enable extended thinking in a skill, include the word ultrathink anywhere in your skill content:
---
name: architecture-review
description: Deep architectural analysis
---
Use ultrathink to analyze the architecture deeply.
Review the overall structure, identify patterns, and suggest improvements.
Example: Code Review Skill
.claude/skills/code-reviewer/SKILL.md:
---
name: code-reviewer
description: Reviews code for security vulnerabilities, bugs, performance issues, and style problems. Use when user asks to review, audit, or check code quality.
allowed-tools: [Read, Grep, Glob]
---
# Code Review Skill
## When to Activate
Use this skill when the user asks to:
- Review code for issues
- Audit security or find vulnerabilities
- Check code quality or best practices
## Review Process
### 1. Scope Detection
- Use Glob to identify files to review
- Prioritize recently modified files
- Focus on user-specified areas if mentioned
### 2. Analysis Layers
- **Security**: SQL injection, XSS, auth issues, exposed secrets
- **Bugs**: Logic errors, null checks, error handling
- **Performance**: N+1 queries, unnecessary loops, memory leaks
- **Style**: Naming conventions, code organization, readability
### 3. Reporting
Provide structured feedback organized by severity:
- **Critical/High**: Security issues
- **Medium**: Performance issues
- **Low**: Style and best practices
Each issue: file path, description, and fix suggestion.
Example: Test Generator Skill
.claude/skills/test-generator/SKILL.md:
---
name: test-generator
description: Generates comprehensive unit and integration tests. Use when user asks to write tests, add test coverage, or create test cases.
allowed-tools: [Read, Write, Grep, Glob, Bash]
---
# Test Generator Skill
## When to Activate
Use this skill when user requests:
- "Write tests for..."
- "Add test coverage"
- "Generate test cases"
## Test Generation Process
### 1. Analyze Target Code
- Read the file/function to test
- Identify inputs, outputs, side effects
- Check existing test patterns
### 2. Generate Comprehensive Tests
Cover all scenarios:
- Happy path (expected usage)
- Error cases (invalid inputs)
- Edge cases (empty, null, boundary values)
- Side effects (database, API calls)
### 3. Follow Project Patterns
- Check CLAUDE.md for testing conventions
- Match existing test file structure
- Use project's test framework
Example: Security Review Skill
.claude/skills/security-review/SKILL.md:
---
name: security-review
description: Comprehensive security audit of codebase. Use when asked to review security, audit vulnerabilities, or check for exploits.
allowed-tools: [Read, Grep, Glob]
disable-model-invocation: true
---
# Security Review: $ARGUMENTS
Perform a thorough security audit focusing on: $ARGUMENTS
## Review Checklist
### 1. Authentication & Authorization
- Check for weak password policies
- Verify JWT token validation
- Review session management
- Check for broken access control
### 2. Input Validation
- SQL injection vulnerabilities
- XSS (Cross-Site Scripting) risks
- Command injection possibilities
- Path traversal vulnerabilities
### 3. Data Protection
- Sensitive data exposure
- Encryption at rest and in transit
- API keys and secrets in code
- Database credential security
### 4. Dependencies
- Known vulnerabilities in packages
- Outdated dependencies
- License compliance issues
### 5. Configuration
- Security headers (CSP, HSTS, etc.)
- CORS configuration
- Error messages leaking information
- Debug mode in production
**Output Format** - Provide a detailed report with sections:
- Critical Issues (Fix Immediately)
- High Priority
- Medium Priority
- Low Priority / Recommendations
- Security Strengths
- Action Plan (prioritized list of fixes)
Usage:
/security-review "authentication and API endpoints"
Example: API Documentation Generator Skill
.claude/skills/api-docs/SKILL.md:
---
name: api-docs
description: Generate comprehensive API documentation from code. Use when asked to document APIs, create API docs, or generate OpenAPI specs.
allowed-tools: [Read, Write, Grep, Glob]
disable-model-invocation: true
---
# Generate API Documentation
Analyze the codebase and create comprehensive API documentation for: $ARGUMENTS
## Process
### 1. Discovery
- Find all API routes/endpoints
- Identify request/response types
- Note authentication requirements
- Document query parameters
### 2. Documentation
For each endpoint, document:
- Method and path
- Description
- Authentication requirements
- Request body/parameters
- Response codes and bodies
- Example requests
### 3. Output
- Create `/docs/API.md` with full documentation
- Create `/openapi.yaml` with OpenAPI spec if applicable
Usage:
/api-docs "all endpoints"
/api-docs "authentication routes"
Reference files with @ prefix for quick file inclusion:
# Reference single file
/review-code @src/auth.ts
# Reference multiple files
/review-code @src/auth.ts @src/api.ts @tests/auth.test.ts
# Works in regular prompts too
> "Review @src/services/payment.ts for security issues"
# Reference files with skill arguments
/analyze-file @src/components/UserProfile.tsx
How @ References Work:
@filename automatically expands to include file contentUse Cases:
# Code review with context
> "Compare @src/api/v1.ts and @src/api/v2.ts and list differences"
# Refactoring across files
> "Make @src/models/User.ts consistent with @src/types/user.d.ts"
# Bug investigation
> "This error occurs in @src/services/auth.ts, check @logs/error.log for clues"
# Test generation
> "Generate tests for @src/utils/validator.ts"
Best Practices:
MCP servers can expose prompts that become invocable skills automatically:
{
"prompts": [
{
"name": "search-docs",
"description": "Search internal documentation",
"arguments": [{"name": "query", "description": "Search query"}]
}
]
}
This becomes available as /search-docs in Claude Code.
# Add MCP server
claude mcp add github -- gh-mcp
# MCP prompts become skills:
/github-pr-review # Review current PR
/github-issues # List open issues
/github-create-pr # Create PR from current branch
The description field is critical — it helps Claude decide when to activate:
Good:
description: "Generates API documentation from code comments. Use when user asks to document APIs, create API docs, update endpoint documentation, or generate OpenAPI specs."
Bad:
description: "Documentation generator" # Too vague
Include terms users would naturally say:
# For security review skill
description: "Reviews code for security. Use when asked to: review security, audit code, find vulnerabilities, check for exploits, analyze risks."
# For performance optimization skill
description: "Optimizes code performance. Use when asked to: improve performance, optimize speed, reduce memory usage, make faster, profile code."
# Analysis only (can't modify code)
allowed-tools: [Read, Grep, Glob]
# Can create/modify code
allowed-tools: [Read, Write, Edit, Bash]
# Research and implementation
allowed-tools: [Read, Write, Edit, WebFetch, WebSearch]
Good (focused):
sql-optimizer — Optimizes SQL queries onlyapi-docs-generator — Generates API documentationsecurity-scanner — Finds security issuesBad (too broad):
database-everything — Too vaguecode-helper — What kind of help?Structure your SKILL.md:
Skill descriptions are loaded into context so Claude knows what's available. If you have many skills, they may exceed the character budget (2% of context window, fallback 16,000 characters). Run /context to check for warnings about excluded skills.
Override the limit with the SLASH_COMMAND_TOOL_CHAR_BUDGET environment variable.
Skill not triggering:
/skill-name to confirm it worksSkill triggers too often:
disable-model-invocation: true for manual-only invocationClaude doesn't see all skills:
/context to check for a warning about excluded skillsSLASH_COMMAND_TOOL_CHAR_BUDGET to a higher valueCustom slash commands (.claude/commands/ files) have been merged into the skills system. Your existing command files keep working unchanged. Skills are recommended for new work because they support:
Migration path:
# Old structure (still works)
.claude/commands/review.md
# New structure (recommended)
.claude/skills/review/SKILL.md
Both create /review and work the same way. If both exist, the skill takes precedence.
Source: Agent Skills
Built-in commands are native CLI commands for managing your Claude Code session. They are hardcoded into Claude Code and are NOT skills — you cannot customize or override them.
Note: For custom workflow commands, use Skills instead. Built-in commands like
/helpand/compactare not available through the Skill tool.
# Session Management
/help # Show all available commands
/exit # End current session
/clear # Clear conversation history
/compact [instr] # Compact context (optionally specify what to focus on)
/rewind # Undo code changes in conversation (/undo is an alias) [v2.1.108]
/recap # Summarize what happened while you were away [NEW v2.1.108]
/goal <condition> # Keep working across turns until a completion condition is met [NEW v2.1.139]
/loop [interval] # Run a prompt or slash command on a repeat (/proactive alias) [NEW v2.1.71]
/effort [level] # Set reasoning effort: low / medium / high / xhigh / max / ultracode
# (/effort auto resets to the model default) [NEW v2.1.76]
/focus # Toggle focus view (Ctrl+O now toggles verbose transcript) [NEW v2.1.110]
/tui [fullscreen] # Switch renderer mode in the same conversation [NEW v2.1.110]
# Session & History
/rename <name> # Give current session a name (auto-generates if omitted)
/resume [name|id] # Resume a previous session by name or ID (includes background sessions)
/export # Export conversation to file
/copy [N] # Copy a response or code block to the clipboard (N = Nth-latest)
/branch # Fork the conversation into a new session (/fork is an alias) [v2.1.77]
/fork # Copy the conversation into a new background session [v2.1.212]
/subtask # Run a sub-task as an in-session subagent [NEW v2.1.212]
/background # Send the current session to the background [NEW]
/cd <path> # Move the session to a new working directory [NEW v2.1.169]
/btw # Ask a side question without disturbing the main thread
# Usage & Stats
/usage # Plan limits, usage, and per-category breakdown (merges /cost and /stats)
/stats # Shortcut into the /usage stats tab
/usage-credits # Enable usage credits (formerly /extra-usage) [v2.1.144]
/fast # Toggle fast mode (Opus 5 and Opus 4.8 as of v2.1.219)
/insights # Usage insights report
# Background Process Management
/bashes # List all background processes
/tasks # List all background tasks (agents, shells, etc.)
/kill <id> # Stop a background process
# Discovery & Debugging
/bug # Report bugs (sends conversation to Anthropic)
/commands # List all skills and commands
/debug # Troubleshoot session issues [NEW v2.1.30]
/hooks # Show configured hooks
/skills # List available Skills
/plugin # Plugin management interface
/context # Context usage grid plus actionable optimization suggestions
/cost # Shortcut into the /usage cost tab
/doctor # Full setup checkup that can diagnose and fix issues (/checkup alias)
/reload-skills # Re-scan skill directories without restarting [NEW v2.1.152]
/reload-plugins # Activate pending plugin changes without restarting [NEW v2.1.69]
/powerup # Interactive lessons teaching Claude Code features [NEW v2.1.90]
/team-onboarding # Generate a teammate ramp-up guide from your usage [NEW v2.1.101]
/scroll-speed # Tune mouse wheel scroll speed with a live preview [NEW v2.1.139]
# Configuration
/config # General settings (type to search and filter)
/permissions # Manage tool permissions (with search)
/privacy-settings # View and update privacy settings
/status # Show session status (Status tab)
/statusline # Configure status line display
/model # Switch between models
/config key=value # Set any setting from the prompt (/config --help lists keys) [NEW v2.1.181]
/output-style # ⚠️ Deprecated in v2.1.73 - use /config instead
/theme # Theme picker; create named custom themes since v2.1.118
/color [name] # Set the prompt-bar color for this session (/color default resets) [NEW v2.1.75]
/terminal-setup # Configure terminal (Kitty, Alacritty, Zed, Warp)
/vim # ⚠️ Removed in v2.1.92 - toggle vim mode via /config → Editor mode
/sandbox # Enable sandboxed bash with filesystem/network isolation
# Workspace Management
/add-dir <path> # Add additional directory to workspace
/agents # ⚠️ Wizard removed in v2.1.198 - ask Claude or edit .claude/agents/ directly
/init # Initialize project with CLAUDE.md guide
/memory # Edit CLAUDE.md memory files
/install-github-app # Set up Claude GitHub Actions for repository
/pr-comments # View pull request comments
/review [pr] # Fast single-pass code review [v2.1.202]
/code-review [lvl] # Multi-agent review at a chosen effort level; --fix applies findings,
# --comment posts inline GitHub PR comments [NEW v2.1.147]
/simplify # Cleanup-only review (reuse, simplification, efficiency) [v2.1.152]
/ultrareview [pr] # Cloud multi-agent review of your branch or a PR [NEW v2.1.111]
/security-review # Complete security review of pending changes
/workflows # View dynamic workflow runs [NEW v2.1.154]
/deep-research # Run a multi-agent research task (manual invocation only)
/dataviz # Chart and dashboard design guidance skill [NEW v2.1.198]
/claude-api # Skill for building with the Claude API and Anthropic SDK [NEW v2.1.69]
/less-permission-prompts # Propose an allowlist from your transcripts [NEW v2.1.111]
/batch # Run a batch of related tasks [NEW v2.1.63]
/todos # List current TODO items
# MCP Server Management
/mcp # MCP server management and OAuth authentication
/mcp enable <srv> # Enable an MCP server
/mcp disable <srv> # Disable an MCP server
# Remote Sessions (claude.ai subscribers)
/teleport # Resume remote session from claude.ai by session ID
/remote-env # Configure remote session environment
/remote-control # Bridge this session to claude.ai/code for mobile/web control
/chrome # Manage the Claude in Chrome connection (GA in v2.1.198)
/voice # Voice dictation (20 languages as of v2.1.69)
/schedule # Manage scheduled tasks
# Account & Updates
/login # Switch Anthropic accounts
/logout # Sign out from Anthropic account
/release-notes # View release notes
# Plan Mode
/plan # Enter plan mode for structured planning
Source: CLI Reference, Interactive Mode
Hooks are automated scripts that execute at specific points in Claude Code's workflow.
Hooks let you intercept and control Claude's actions:
# Examples of what hooks can do:
- Block editing of sensitive files (.env)
- Inject context at session start
- Run linting before file edits
- Validate git commits
- Audit all commands executed
- Add custom security checks
Two Types:
type: "command") - Run shell scriptstype: "prompt") - Use LLM for context-aware decisionsHooks are configured in .claude/settings.json or ~/.claude/settings.json:
{
"hooks": {
"EventName": [
{
"matcher": "ToolPattern",
"hooks": [
{"type": "command", "command": "script"}
]
}
]
}
}
| Event | When It Fires | Can Block |
|---|---|---|
| Setup | Via --init, --init-only, or --maintenance flags | No |
| SessionStart | Session begins or resumes | No |
| SessionEnd | Session terminates | No |
| UserPromptSubmit | User submits a prompt | Yes |
| PreToolUse | Before tool execution | Yes |
| PostToolUse | After tool succeeds | No |
| PostToolUseFailure | After tool fails | No |
| PermissionRequest | When permission dialog appears | Yes |
| SubagentStart | When spawning a subagent | No |
| SubagentStop | When subagent finishes | Yes |
| Stop | Claude finishes responding | Yes |
| StopFailure | Turn ends due to an API error (rate limit, auth failure) [NEW v2.1.78] | No |
| Notification | Claude sends notification | No |
| PreCompact | Before context compaction (blocks via exit code 2 since v2.1.105) | Yes |
| PostCompact | After compaction completes [NEW v2.1.76] | No |
| TeammateIdle | Agent team teammate about to go idle | Yes |
| TaskCompleted | Task being marked as completed | Yes |
| TaskCreated | Task created via TaskCreate [NEW v2.1.84] | Yes |
| MessageDisplay | Assistant message about to be displayed — transform or hide it [NEW v2.1.152] | Yes |
| PermissionDenied | After an auto mode classifier denial (return {retry: true}) [NEW v2.1.89] | No |
| ConfigChange | Configuration files change during a session [NEW v2.1.49] | Yes |
| InstructionsLoaded | CLAUDE.md or .claude/rules/*.md loaded into context [NEW v2.1.69] | No |
| CwdChanged | Working directory changes [NEW v2.1.83] | No |
| FileChanged | A watched file changes [NEW v2.1.83] | No |
| DirectoryAdded | /add-dir registers a new working directory mid-session [NEW v2.1.219] | No |
| WorktreeCreate | Agent worktree isolation creates a worktree [NEW v2.1.50] | No |
| WorktreeRemove | Agent worktree isolation removes a worktree [NEW v2.1.50] | No |
| Elicitation | MCP server requests structured input [NEW v2.1.76] | Yes |
| ElicitationResult | Before an elicitation response is sent back [NEW v2.1.76] | Yes |
Hook configuration additions since v2.1.39:
| Feature | Description |
|---|---|
if: condition | Filter when a hook runs using permission-rule syntax, e.g. if: "Bash(git *)" [NEW v2.1.85] |
args: string[] | Exec form — spawns the command directly without a shell, so paths never need quoting [NEW v2.1.139] |
type: "http" | HTTP hooks POST JSON to a URL and receive JSON (needs allowedEnvVars to interpolate env) [NEW v2.1.63] |
type: "mcp_tool" | Hooks can invoke MCP tools directly [NEW v2.1.118] |
continueOnBlock | PostToolUse only — feed the rejection reason back to Claude and continue the turn [NEW v2.1.139] |
terminalSequence | Emit desktop notifications, window titles, and bells without a controlling terminal [NEW v2.1.141] |
"defer" decision | PreToolUse only — pause a headless session at a tool call, resume with -p --resume [NEW v2.1.89] |
hookSpecificOutput.updatedToolOutput | PostToolUse can replace tool output for all tools [NEW v2.1.121] |
hookSpecificOutput.sessionTitle | SessionStart / UserPromptSubmit can set the session title [NEW v2.1.94] |
hookSpecificOutput.additionalContext | Stop / SubagentStop feedback that keeps the turn going [NEW v2.1.163] |
reloadSkills: true | SessionStart can re-scan skill directories in the same session [NEW v2.1.152] |
effort.level / $CLAUDE_EFFORT | Hooks receive the active effort level [NEW v2.1.133] |
duration_ms | PostToolUse / PostToolUseFailure input includes tool execution time [NEW v2.1.119] |
last_assistant_message | Stop / SubagentStop input includes the final assistant response text [NEW v2.1.47] |
background_tasks, session_crons | Stop / SubagentStop input fields [NEW v2.1.145] |
agent_id / agent_type | Present on hook events for subagents and --agent sessions [NEW v2.1.69] |
.claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "bash -c 'FILE=$(echo \"$HOOK_INPUT\" | jq -r \".tool_input.file_path // empty\"); if [[ \"$FILE\" == *\".env\"* ]] || [[ \"$FILE\" == \".git/\"* ]]; then echo \"Cannot modify sensitive files\" >&2; exit 2; fi'"
}
]
}
]
}
}
How it works:
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "cat .claude/session-context.txt"
}
]
}
]
}
}
Creates: .claude/session-context.txt
Today's Focus: Working on authentication refactor
Recent Context: Migrated from sessions to JWT
Current Branch: feature/jwt-auth
Important: Don't modify legacy auth code in /old-auth
This context is injected at every session start.
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Evaluate if the current task is complete. Arguments: $ARGUMENTS. Check if all subtasks are done, tests pass, and documentation updated. Respond with {\"decision\": \"stop\" or \"continue\", \"reason\": \"explanation\"}"
}
]
}
]
}
}
Uses an LLM (Haiku) to intelligently decide if Claude should stop working.
Input (via stdin as JSON):
{
"sessionId": "abc123",
"tool_name": "Edit",
"tool_input": {
"file_path": "/src/app.ts",
"old_string": "...",
"new_string": "..."
},
"project_dir": "/home/user/project"
}
Output (exit codes):
0 - Success, continue2 - Block the actionJSON Output (optional):
{
"decision": "stop",
"reason": "All tasks complete",
"continue": false
}
⚠️ Critical: "By using hooks, you are solely responsible for configured commands, which can modify or delete files your user can access."
Best Practices:
# 1. Always quote variables
FILE="$HOOK_INPUT" # Good
FILE=$HOOK_INPUT # Bad - can break with spaces
# 2. Validate paths
if [[ "$FILE" == ../* ]]; then
echo "Path traversal attempt" >&2
exit 2
fi
# 3. Use absolute paths
cd "$CLAUDE_PROJECT_DIR" || exit 1
# 4. Sanitize inputs
jq -r '.tool_input.file_path' <<< "$HOOK_INPUT" # Good
eval "$SOME_VAR" # Bad - code injection risk
# 5. Block sensitive operations
case "$FILE" in
*.env|.git/*|.ssh/*)
echo "Blocked: sensitive file" >&2
exit 2
;;
esac
# Run Claude with debug mode
claude --debug
# Check hook configuration
> /hooks
# Test hook command manually
echo '{"tool_name":"Edit","tool_input":{"file_path":".env"}}' | bash your-hook-script.sh
# View logs
tail -f ~/.claude/logs/claude.log
Comprehensive collection of production-ready hook patterns for common automation needs.
Automatically formats code after Claude edits files using language-appropriate formatters.
Configuration (.claude/settings.json):
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|MultiEdit|Write",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/format-code.sh"
}
]
}
]
}
}
Script (~/.claude/hooks/format-code.sh):
#!/bin/bash
# Extract file path from JSON input
FILE=$(echo "$HOOK_INPUT" | jq -r '.tool_input.file_path // empty')
[[ -z "$FILE" ]] && exit 0
# Format based on extension
case "$FILE" in
*.ts|*.tsx|*.js|*.jsx)
# Try Biome first, fall back to Prettier
if command -v biome &> /dev/null; then
biome format --write "$FILE" &> /dev/null || true
elif command -v prettier &> /dev/null; then
prettier --write "$FILE" &> /dev/null || true
fi
;;
*.py)
# Python: Ruff
if command -v ruff &> /dev/null; then
ruff format "$FILE" &> /dev/null || true
fi
;;
*.go)
# Go: goimports + gofmt
if command -v goimports &> /dev/null; then
goimports -w "$FILE" &> /dev/null || true
fi
go fmt "$FILE" &> /dev/null || true
;;
*.md)
# Markdown: Prettier
if command -v prettier &> /dev/null; then
prettier --write "$FILE" &> /dev/null || true
fi
;;
esac
Make executable: chmod +x ~/.claude/hooks/format-code.sh
Automatically runs ESLint with --fix on JavaScript/TypeScript files.
Configuration:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|MultiEdit|Write",
"hooks": [
{
"type": "command",
"command": "bash -c 'FILE=$(echo \"$HOOK_INPUT\" | jq -r \".tool_input.file_path // empty\"); if [[ \"$FILE\" =~ \\.(ts|tsx|js|jsx)$ ]] && command -v eslint &>/dev/null; then eslint --fix \"$FILE\" &>/dev/null || true; fi'"
}
]
}
]
}
}
Prevents Claude from reading files matching .claudeignore patterns.
Configuration:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Read",
"hooks": [
{
"type": "command",
"command": "claude-ignore"
}
]
}
]
}
}
Installation: npm install -g claude-ignore && claude-ignore init
Validates that tests pass before allowing git commits.
Configuration:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/pre-commit-test.sh"
}
]
}
]
}
}
Script (~/.claude/hooks/pre-commit-test.sh):
#!/bin/bash
COMMAND=$(echo "$HOOK_INPUT" | jq -r '.tool_input.command // empty')
# Only intercept git commit commands
if [[ "$COMMAND" == git*commit* ]]; then
echo "Running tests before commit..." >&2
# Run tests
if npm test &>/dev/null; then
echo "✅ Tests passed" >&2
exit 0
else
echo "❌ Tests failed - blocking commit" >&2
exit 2
fi
fi
exit 0
Logs all tool usage for security auditing.
Configuration:
{
"hooks": {
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "bash -c 'echo \"$(date -Iseconds) $TOOL_NAME: $(echo \\\"$HOOK_INPUT\\\" | jq -c .)\" >> ~/.claude/audit.log'"
}
]
}
]
}
}
Monitors and logs token usage per session.
Configuration:
{
"hooks": {
"SessionEnd": [
{
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/log-session.sh"
}
]
}
]
}
}
Script:
#!/bin/bash
SESSION_ID=$(echo "$HOOK_INPUT" | jq -r '.session_id // "unknown"')
TRANSCRIPT=$(echo "$HOOK_INPUT" | jq -r '.transcript_path // empty')
if [[ -f "$TRANSCRIPT" ]]; then
TOKENS=$(jq '[.[] | select(.role=="assistant") | .usage.total_tokens] | add' "$TRANSCRIPT" 2>/dev/null || echo 0)
echo "$(date -Iseconds) Session $SESSION_ID: $TOKENS tokens" >> ~/.claude/token-usage.log
fi
Enforces conventional commit message format.
Configuration:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/validate-commit.sh"
}
]
}
]
}
}
Script:
#!/bin/bash
COMMAND=$(echo "$HOOK_INPUT" | jq -r '.tool_input.command // empty')
if [[ "$COMMAND" == git*commit*-m* ]]; then
MSG=$(echo "$COMMAND" | sed -n 's/.*-m[[:space:]]*["'"'"']\([^"'"'"']*\)["'"'"'].*/\1/p')
# Check conventional commit format: type(scope): message
if [[ ! "$MSG" =~ ^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: ]]; then
echo "❌ Commit message must follow format: type(scope): message" >&2
echo "Valid types: feat, fix, docs, style, refactor, test, chore" >&2
exit 2
fi
fi
exit 0
Prevents committing files containing potential secrets.
Configuration:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/detect-secrets.sh"
}
]
}
]
}
}
Script:
#!/bin/bash
FILE=$(echo "$HOOK_INPUT" | jq -r '.tool_input.file_path // empty')
NEW_CONTENT=$(echo "$HOOK_INPUT" | jq -r '.tool_input.new_string // .tool_input.content // empty')
# Check for common secret patterns
if echo "$NEW_CONTENT" | grep -iE '(api[_-]?key|password|secret|token|auth)["\s:=]+\S{16,}' &>/dev/null; then
echo "⚠️ Potential secret detected in $FILE" >&2
echo "Please review and use environment variables instead" >&2
exit 2
fi
exit 0
Updates README when code changes are made.
Configuration:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|MultiEdit|Write",
"hooks": [
{
"type": "command",
"command": "bash -c 'echo \"📝 Consider updating documentation for recent changes\" >&2'"
}
]
}
]
}
}
Tracks execution time of tool operations.
Configuration:
{
"hooks": {
"PreToolUse": [
{
"hooks": [
{
"type": "command",
"command": "bash -c 'echo \"$HOOK_INPUT\" > /tmp/claude-pre-$$.json; date +%s%N > /tmp/claude-time-$$.txt'"
}
]
}
],
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "bash ~/.claude/hooks/profile-tool.sh"
}
]
}
]
}
}
Script:
#!/bin/bash
START=$(cat /tmp/claude-time-$$.txt 2>/dev/null || echo 0)
END=$(date +%s%N)
DURATION=$(( (END - START) / 1000000 )) # milliseconds
TOOL=$(echo "$HOOK_INPUT" | jq -r '.tool_name // "unknown"')
echo "$(date -Iseconds) $TOOL: ${DURATION}ms" >> ~/.claude/performance.log
rm -f /tmp/claude-pre-$$.json /tmp/claude-time-$$.txt
Source: Hooks Reference, Hooks Guide, Community GitHub repositories
Model Context Protocol (MCP) connects Claude Code to external data sources and tools.
MCP allows Claude Code to:
Common Use Cases:
MCP servers can be added via CLI or configuration files:
CLI Installation (Recommended):
# Remote HTTP Server (recommended for hosted services)
claude mcp add --transport http notion https://mcp.notion.com/mcp
claude mcp add --transport http github https://api.githubcopilot.com/mcp/
# With authentication headers
claude mcp add --transport http secure-api https://api.example.com/mcp \
--header "Authorization: Bearer your-token"
# Local Stdio Server (for local packages)
claude mcp add --transport stdio airtable -- npx -y airtable-mcp-server
claude mcp add --transport stdio postgres -- npx -y @modelcontextprotocol/server-postgres "$DATABASE_URL"
# With environment variables
claude mcp add --transport stdio --env AIRTABLE_API_KEY=your_key airtable -- npx -y airtable-mcp-server
# Windows (requires cmd /c wrapper)
claude mcp add --transport stdio myserver -- cmd /c npx -y @some/package
MCP Server Management:
claude mcp list # List all configured servers
claude mcp get github # Get details for specific server
claude mcp remove github # Remove a server
/mcp # Interactive management in Claude Code
Installation Scopes:
# Local scope (default) - stored in ~/.claude.json under project path
claude mcp add --transport http stripe https://mcp.stripe.com
# Project scope - stored in .mcp.json (shared via git)
claude mcp add --scope project --transport http paypal https://mcp.paypal.com/mcp
# User scope - stored in ~/.claude.json (available across all projects)
claude mcp add --scope user --transport http hubspot https://mcp.hubspot.com
Configuration File (.mcp.json):
{
"mcpServers": {
"github": {
"type": "http",
"url": "https://api.githubcopilot.com/mcp/"
},
"postgres": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres", "${DATABASE_URL}"],
"env": {
"DB_URL": "${DB_URL}",
"API_KEY": "${API_KEY:-default-value}"
}
},
"slack": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-slack"],
"env": {
"SLACK_BOT_TOKEN": "${SLACK_BOT_TOKEN}",
"SLACK_TEAM_ID": "${SLACK_TEAM_ID}"
}
}
}
}
Many MCP servers support OAuth for secure authentication:
# Add server that requires OAuth
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp
# Within Claude Code, authenticate via browser
/mcp
# Follow browser steps to complete OAuth login
Manual OAuth Configuration:
{
"mcpServers": {
"github": {
"type": "http",
"url": "https://api.githubcopilot.com/mcp/",
"oauth": {
"provider": "github",
"scopes": ["repo", "read:user"]
}
}
}
}
Claude Code opens a browser to complete the OAuth flow on first use.
Once configured, MCP tools appear with the pattern mcp__<server>__<tool>:
# Example: Google Drive search
> "Search our Google Drive for Q4 planning documents"
# Claude uses: mcp__google-drive__search_files
# Example: Database query
> "Show all users created in the last week"
# Claude uses: mcp__postgres__query with SQL
# Example: Slack search
> "Find conversations about the API redesign"
# Claude uses: mcp__slack__search_messages
You can reference MCP tools in hooks:
{
"hooks": {
"PreToolUse": [
{
"matcher": "mcp__postgres__query",
"hooks": [
{
"type": "command",
"command": "echo 'Database query requires review' && read -p 'Approve? (y/n) ' -n 1 -r && [[ $REPLY =~ ^[Yy]$ ]]"
}
]
}
]
}
}
# Official Servers
@modelcontextprotocol/server-google-drive # Google Drive access
@modelcontextprotocol/server-slack # Slack integration
@modelcontextprotocol/server-github # GitHub API
@modelcontextprotocol/server-postgres # PostgreSQL database
@modelcontextprotocol/server-sqlite # SQLite database
@modelcontextprotocol/server-filesystem # Extended file access
# Community Servers
# Check GitHub for community-built MCP servers
# Enable all project MCP servers automatically
{
"enableAllProjectMcpServers": true
}
# Whitelist specific servers
{
"enabledMcpjsonServers": ["google-drive", "postgres"]
}
# Blacklist servers
{
"disabledMcpjsonServers": ["risky-server"]
}
# Enterprise: Restrict to managed servers only
{
"useEnterpriseMcpConfigOnly": true,
"allowedMcpServers": ["approved-server-1", "approved-server-2"]
}
When MCP tool definitions exceed a threshold of the context window, they're automatically deferred via an MCPSearch tool:
# Configure tool search threshold (% of context window)
ENABLE_TOOL_SEARCH=auto:5 claude # Activate at 5%
ENABLE_TOOL_SEARCH=auto:10 claude # Activate at 10% (default)
ENABLE_TOOL_SEARCH=true claude # Always enabled
ENABLE_TOOL_SEARCH=false claude # Always disabled
# Or configure in settings.json
{
"permissions": {
"deny": ["MCPSearch"] # Disable MCP tool search
}
}
Source: MCP Documentation, Settings
Quick-start configurations for popular MCP servers.
# Installation
claude mcp add --transport stdio github -- npx -y @modelcontextprotocol/server-github
# Or via .mcp.json
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
}
}
}
}
Common operations: Create issues, manage PRs, search code, review repositories.
# Installation
claude mcp add --transport stdio slack -- npx -y @modelcontextprotocol/server-slack
# Configuration
{
"mcpServers": {
"slack": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-slack"],
"env": {
"SLACK_BOT_TOKEN": "${SLACK_BOT_TOKEN}",
"SLACK_TEAM_ID": "T01234567"
}
}
}
}
Usage: > "Search Slack for conversations about API redesign"
# Installation with OAuth
claude mcp add --transport http gdrive https://mcp.google.com/drive
# Or stdio with credentials
{
"mcpServers": {
"gdrive": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-gdrive"],
"env": {
"GDRIVE_CREDENTIALS_PATH": "${HOME}/.gdrive-credentials.json"
}
}
}
}
Authenticate: Run /mcp in Claude Code and follow OAuth flow.
# Installation
claude mcp add --transport stdio postgres -- npx -y @modelcontextprotocol/server-postgres postgresql://user:pass@localhost/db
# Configuration
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-postgres",
"${DATABASE_URL}"
]
}
}
}
Usage: > "Show all users created in the last week from the database"
# Installation
claude mcp add --transport http notion https://mcp.notion.com/mcp
# Requires Notion OAuth - authenticate via /mcp command
Common operations: Query databases, create pages, search workspace.
# Configuration
{
"mcpServers": {
"stripe": {
"command": "npx",
"args": ["-y", "@stripe/mcp-server"],
"env": {
"STRIPE_API_KEY": "${STRIPE_API_KEY}"
}
}
}
}
Usage: > "List recent Stripe transactions and summarize revenue"
Common issues and solutions from GitHub issues and production usage.
# Problem
claude mcp list
# Output: "No MCP servers configured"
# Solutions
1. Check file location:
- User scope: ~/.claude/settings.json
- Project scope: .mcp.json (in project root)
2. Verify JSON syntax:
cat .mcp.json | jq .
3. Check scope setting:
claude mcp add --scope project <name> ...
4. Restart Claude Code after config changes
# Problem
/mcp shows "✓ Connected" but tools don't appear
# Solutions
1. Check tool output size (max 25,000 tokens):
export MAX_MCP_OUTPUT_TOKENS=50000
2. Verify server actually started:
ps aux | grep mcp
3. Check debug logs:
claude --debug
tail -f ~/.claude/logs/claude.log
4. Reset project approvals:
claude mcp reset-project-choices
# Problem
Browser opens but OAuth fails or doesn't complete
# Solutions
1. Use /mcp command (not direct URL)
2. Check network/proxy settings:
# Try without VPN/Cloudflare Warp
3. Clear OAuth cache:
rm -rf ~/.claude/oauth-cache
4. Verify redirect URI in provider settings
# Problem
MCP server immediately closes on Windows
# Solution - Use cmd /c wrapper:
claude mcp add --transport stdio myserver -- cmd /c npx -y package-name
# In .mcp.json:
{
"mcpServers": {
"myserver": {
"command": "cmd",
"args": ["/c", "npx", "-y", "package-name"]
}
}
}
# Problem
${VAR} shows literally instead of expanding
# Solutions
1. Check .env file exists and is loaded
2. Use default syntax:
"${API_KEY:-default_value}"
3. Set in shell before running:
export API_KEY=xxx && claude
4. Use settings.local.json for sensitive values
# Debug steps:
1. Test server directly:
npx @modelcontextprotocol/server-github
2. Check stdout/stderr:
claude --debug | grep mcp
3. Verify dependencies installed:
npm list -g | grep mcp
4. Check memory/resource limits:
ulimit -a
Sub-agents are specialized AI assistants configured for specific tasks.
Sub-agents are instances of Claude optimized for particular workflows:
# Built-in Sub-Agents
- general-purpose: Complex multi-step tasks
- Explore: Fast codebase exploration
# Custom Sub-Agents
- You can create your own with custom prompts and tools
Launch with the Task tool:
# Explore codebase
> "Find all database queries in the codebase"
# Claude uses:
Task subagent_type="Explore"
prompt="Find all database queries and list files containing SQL, Prisma, or ORM code"
# General purpose research
> "Research best practices for API rate limiting and suggest implementation"
# Claude uses:
Task subagent_type="general-purpose"
prompt="Research API rate limiting approaches, compare options, and recommend implementation for Express.js"
Sub-agents are defined as Markdown files in .claude/agents/ or ~/.claude/agents/:
Example: Debug Assistant
.claude/agents/debugger.md:
---
name: debugger
description: Specialized debugging agent for production issues
model: claude-sonnet-4
allowedTools: [Read, Grep, Glob, Bash]
---
# Debug Assistant
You are a specialized debugging agent. Your role is to systematically investigate and identify the root cause of issues.
## Debugging Process
### 1. Gather Context
- Read error messages and stack traces
- Check recent code changes (git log)
- Review related log files
- Understand expected vs actual behavior
### 2. Hypothesis Generation
- List possible causes
- Prioritize by likelihood
- Consider recent changes first
### 3. Systematic Investigation
- Test each hypothesis methodically
- Use Grep to find related code
- Read implementation details
- Check for similar patterns elsewhere
### 4. Root Cause Analysis
- Identify the precise cause
- Explain why it happens
- Trace the execution path
### 5. Solution Proposal
- Suggest specific fixes
- Explain tradeoffs
- Provide code examples
- Recommend tests to prevent recurrence
## Constraints
- DO NOT modify code (read-only analysis)
- DO provide detailed explanations
- DO reference specific file:line locations
- DO consider edge cases
Example: Code Review Agent
.claude/agents/reviewer.md:
---
name: reviewer
description: Code review specialist focusing on quality and best practices
model: claude-sonnet-4
allowedTools: [Read, Grep, Glob]
---
# Code Reviewer
You are a senior code reviewer. Provide constructive, actionable feedback.
## Review Criteria
### Code Quality
- Readability and maintainability
- Naming conventions
- Code organization
- DRY principle adherence
### Correctness
- Logic errors
- Edge cases handling
- Error handling
- Null/undefined checks
### Performance
- Algorithm efficiency
- Unnecessary computations
- Memory usage
- Database query optimization
### Security
- Input validation
- SQL injection risks
- XSS vulnerabilities
- Authentication/authorization
### Testing
- Test coverage
- Test quality
- Edge cases tested
## Output Format
Provide structured feedback:
- **Strengths**: What's done well
- **Issues**: Problems found (with severity)
- **Suggestions**: Improvements
- **Examples**: Code snippets for fixes
Choose different models per agent:
---
name: fast-explorer
model: claude-haiku-4 # Fast, cost-effective
---
---
name: deep-analyzer
model: claude-opus-4 # Most capable
---
Limit tools for focused operation:
---
name: readonly-analyzer
allowedTools: [Read, Grep, Glob] # Analysis only
---
---
name: implementation-agent
allowedTools: [Read, Write, Edit, Bash] # Can modify code
---
> "Have multiple agents analyze different aspects"
# Launches multiple agents in parallel:
- Security review agent
- Performance analysis agent
- Code style agent
- Test coverage agent
# Aggregates results
> "Research → Design → Implement authentication"
# Sequential sub-agents:
1. Research agent: Find best practices
2. Design agent: Create architecture
3. Implementation agent: Write code
4. Review agent: Verify implementation
{
"frontend-agent": "React/UI specialist",
"backend-agent": "API/database specialist",
"devops-agent": "Deployment/infrastructure specialist"
}
Source: Sub-Agents
Agent Teams enable multiple Claude Code instances to collaborate on complex tasks with shared context and direct communication.
Agent Teams (experimental) allow you to coordinate multiple Claude Code sessions working together:
# Key differences from Sub-Agents:
- Sub-Agents: Run within a single session, report only to main agent
- Agent Teams: Independent sessions that can communicate directly with each other
# When to use Agent Teams:
✅ Research and review (multiple perspectives simultaneously)
✅ New modules/features (teammates own separate pieces)
✅ Debugging with competing hypotheses (parallel investigation)
✅ Cross-layer coordination (frontend, backend, tests)
# When NOT to use Agent Teams:
❌ Sequential tasks with dependencies
❌ Same-file edits (coordination overhead)
❌ Simple tasks (overkill)
Agent Teams are disabled by default. Enable in settings:
{
"env": {
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
}
}
Or set the environment variable:
export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
claude
# Describe the task and team structure
> "Create an agent team to review PR #142. Spawn three reviewers:
- One focused on security implications
- One checking performance impact
- One validating test coverage
Have them each review and report findings."
# Claude creates the team and coordinates work
# Use Shift+Up/Down to select and message teammates directly
| Mode | Description | Best For |
|---|---|---|
in-process | All teammates in main terminal | Any terminal, simple setup |
tmux | Each teammate in own pane | Parallel visibility, tmux/iTerm2 |
auto (default) | Uses tmux if already in tmux session | Automatic selection |
Configure in settings:
{
"teammateMode": "in-process"
}
Or via CLI flag:
claude --teammate-mode in-process
# Select teammates
Shift+Up/Down # Cycle through teammates
# View teammate session
Enter # View selected teammate's session
Escape # Interrupt teammate's turn
# Manage tasks
Ctrl+T # Toggle shared task list
# Delegate mode
Shift+Tab # Toggle delegate mode (lead only coordinates, doesn't implement)
# Shut down
> "Ask the researcher teammate to shut down"
> "Clean up the team"
| Component | Description |
|---|---|
| Team Lead | Main session that creates team, spawns teammates, coordinates work |
| Teammates | Independent Claude Code instances working on assigned tasks |
| Task List | Shared work items that teammates claim and complete |
| Mailbox | Messaging system for inter-agent communication |
Storage Locations:
~/.claude/teams/{team-name}/config.json~/.claude/tasks/{team-name}/Use hooks to enforce quality gates:
{
"hooks": {
"TeammateIdle": [
{
"hooks": [
{
"type": "command",
"command": "bash -c 'if [ ! -f ./dist/output.js ]; then echo \"Build artifact missing\" >&2; exit 2; fi'"
}
]
}
],
"TaskCompleted": [
{
"hooks": [
{
"type": "command",
"command": "bash -c 'if ! npm test 2>&1; then echo \"Tests failing\" >&2; exit 2; fi'"
}
]
}
]
}
}
Source: Agent Teams
The agent view is one list of every Claude Code session — running, blocked on you, or done. It shipped as a research preview in v2.1.139 and became the main surface for long-running work through the v2.1.14x–v2.1.21x releases. Background sessions keep working after you detach, survive updates and reboots of the CLI process, and can be attached to from any terminal.
# Open the dashboard
claude agents
# Or press the left arrow from an interactive session
# ← (single press from a foreground session since v2.1.196)
Sessions are grouped into Needs input, Working, and Completed. Rows show a colored state word, a classifier-written headline, linked pull requests, and how many background agents are waiting on you.
# Start a session directly in the background
claude --bg "refactor the auth module"
# Name it so you can address it later
claude --bg --name auth-refactor "refactor the auth module"
# Run a plain shell command as an attachable background session (v2.1.154)
claude --bg --exec 'npm run build:watch'
# Send the session you are in to the background
/background # or press ←
claude attach <id> # Attach to a running background session
claude logs <id> # Show its output
claude stop <id> # Stop it
claude respawn <id> # Restart a stopped session
claude rm <id> # Remove it permanently
claude daemon status # Inspect the background-session daemon
Scripting the list:
claude agents --json # Live sessions as JSON (id, state, waitingFor, PR links)
claude agents --json --all # Include completed sessions
claude agents --cwd ./services # Scope the list to a directory
--json output is designed for status bars, session pickers, and tmux integrations.
Since v2.1.142/v2.1.143, claude agents accepts the same configuration flags it will pass to sessions dispatched from the dashboard:
claude agents \
--add-dir ../lib --settings ./ci.json --mcp-config ./mcp.json --plugin-dir ./plugins \
--permission-mode plan --model opus --effort high
--agent <name> overrides the agent field from settings.json for dispatched sessions.
Background sessions edit code inside an isolated git worktree rather than your checkout, so your working tree stays untouched:
| Piece | Behavior |
|---|---|
EnterWorktree / ExitWorktree tools | Enter, switch between, and leave Claude-managed worktrees |
worktree.baseRef | fresh branches from origin/<default>, head from local HEAD |
worktree.sparsePaths | Sparse-checkout only the directories you need in a monorepo |
worktree.bgIsolation: "none" | Let background sessions edit the working copy directly |
isolation: "worktree" | Agent frontmatter option so a subagent runs in its own worktree |
WorktreeCreate / WorktreeRemove hooks | Custom VCS setup and teardown |
Background agents launched from claude agents commit, push, and open a draft PR when they finish code work in a worktree (v2.1.198).
| Key | Action |
|---|---|
← | Open the agent view / leave a session running in the background |
Enter | Open or wake the selected session |
Ctrl+T | Pin a session so it stays alive when idle |
Ctrl+R | Rename a session |
Ctrl+X | Delete a session (twice to confirm) |
Ctrl+X Ctrl+K | Stop all background agents |
! | Dispatch a shell command as a background session |
/resume | Open a picker of past sessions and resume one in the background |
Notifications: sessions that need input or finish fire the Notification hook with agent_needs_input / agent_completed (v2.1.198).
Source: Agent View
Dynamic workflows let Claude orchestrate work across tens to hundreds of agents in the background. Introduced in v2.1.154, a workflow is generated on demand for the task you describe, runs its agents in phases, and reports progress in a status row below the prompt.
# Ask for one in your own words
> ultracode: migrate every service off the deprecated auth client
# Or just describe the task and ask for a workflow
> run a workflow to add tests to every module missing coverage
# Review runs
/workflows
The trigger keyword was renamed from workflow to ultracode in v2.1.160 — the plain word "workflow" no longer starts a run. The keyword is highlighted in the prompt input, and alt+w (or Backspace right after typing it) dismisses the request.
{
"workflowSizeGuideline": "medium"
}
/config under Dynamic workflow size, or in any settings file via workflowSizeGuideline (v2.1.219)./config.| Capability | Notes |
|---|---|
agent({schema}) | Structured output per agent; aborts after 5 schema-validation failures |
isolation: "worktree" | Workflow agents can run in their own git worktree |
| Status filtering | Press f in the /workflows agent detail view |
| Telemetry | workflow.run_id and workflow.name OTel attributes on spawned agents |
Related: /effort ultracode is the session setting, not the prompt keyword — it sends xhigh to the model and has Claude orchestrate a workflow for every substantive task until the session ends. It is a Claude Code setting rather than a model effort level (max is the deepest model reasoning level), it applies to the current session only, and it is offered only on models that support xhigh.
Auto mode replaces per-tool permission prompts with a safety classifier that adjudicates each action. It moved from an opt-in experiment to the default-available permission mode over v2.1.111–v2.1.207.
| Release | Change |
|---|---|
| v2.1.111 | Auto mode available for Max subscribers on Opus 4.7; no longer needs --enable-auto-mode |
| v2.1.152 | Auto mode no longer requires opt-in consent |
| v2.1.158 | Available on Bedrock, Vertex, and Foundry with CLAUDE_CODE_ENABLE_AUTO_MODE=1 |
| v2.1.207 | No opt-in needed on Bedrock/Vertex/Foundry; disable with disableAutoMode |
| v2.1.210 | Classifier defaults to Sonnet 5 for external sessions, pinned for the session |
Cycle into it with Shift+Tab, or set "permissions": { "defaultMode": "auto" }.
{
"disableAutoMode": false,
"autoMode": {
"classifyAllShell": true,
"allow": ["$defaults", "Bash(npm test *)"],
"soft_deny": ["$defaults"],
"hard_deny": ["Bash(curl * | sh)"],
"environment": ["$defaults"]
}
}
"$defaults" keeps the built-in rule list instead of replacing it (v2.1.118).hard_deny rules block unconditionally, regardless of user intent or allow exceptions (v2.1.136).classifyAllShell routes all Bash/PowerShell commands through the classifier, not only arbitrary-code-execution patterns (v2.1.193).autoMode from ~/.claude/settings.json, not from repo-resident .claude/settings.local.json (v2.1.207).claude auto-mode reset restores the default configuration (v2.1.212).git reset --hard, git checkout -- ., git clean -fd, git stash drop) are blocked unless you asked to discard local work; git commit --amend is blocked when the commit wasn't made by the agent this session; terraform/pulumi/cdk destroy require you to name the stack (v2.1.183).PreToolUse hook returning ask floors the decision at a prompt — auto mode cannot override it (v2.1.211)./permissions → Recent, where r retries.{
"hooks": {
"PermissionDenied": [
{
"hooks": [
{ "type": "command", "command": ".claude/hooks/on-denied.sh" }
]
}
]
}
}
PermissionDenied fires after an auto mode classifier denial. Returning {"retry": true} tells the model it may try again.
Plugins bundle Skills, Hooks, and MCP servers for easy sharing.
Plugins are packages that extend Claude Code:
# A plugin can contain:
- Skills (capabilities and workflow templates)
- Hooks (automation)
- MCP Servers (external integrations)
- Sub-Agent definitions
# Interactive plugin management
> /plugin
# Options:
- Browse marketplace
- Install plugins
- Enable/disable plugins
- Remove plugins
- Add custom marketplaces
- Search installed plugins [v2.1.14]
Plugin Pinning [NEW v2.1.14]: Plugins can now be pinned to specific git commit SHAs for version stability:
{
"plugins": {
"enabledPlugins": {
"security-toolkit@official#abc123def": true
}
}
}
my-plugin/
├── .claude-plugin/
│ └── plugin.json # Metadata
├── commands/ # Legacy commands (treated as skills)
│ └── my-command.md
├── skills/ # Skills
│ └── my-skill/
│ └── SKILL.md
├── hooks.json # Hook definitions
└── agents/ # MCP servers & sub-agents
└── mcp.json
plugin.json:
{
"name": "my-plugin",
"version": "1.0.0",
"description": "My awesome plugin",
"author": "Your Name",
"homepage": "https://github.com/user/plugin",
"keywords": ["productivity", "testing"]
}
# From marketplace
> /plugin
# Select "Browse marketplace"
# Choose and install
# Team Configuration
# .claude/settings.json
{
"plugins": {
"enabledPlugins": {
"security-toolkit@official": true,
"custom-workflows@team": true
}
}
}
{
"extraKnownMarketplaces": [
{
"name": "company-internal",
"type": "github",
"url": "https://github.com/company/claude-plugins"
},
{
"name": "local-dev",
"type": "directory",
"path": "/path/to/plugins"
}
]
}
Configure in .claude/settings.json (committed to git):
{
"plugins": {
"enabledPlugins": {
"team-workflows@company": true
}
},
"extraKnownMarketplaces": [
{
"name": "company",
"type": "github",
"url": "https://github.com/company/claude-plugins"
}
]
}
When team members trust the repository, plugins install automatically.
When using Claude Code in VSCode:
/usage command [v2.1.14]: Display current plan usage directly in VSCodepython and pip use the correct interpreter (configure via claudeCode.usePythonEnvironment setting)Source: Plugins
The Claude desktop app provides a native interface for running Claude Code sessions locally and integrating with Claude Code on the web.
Key Features:
.worktreeinclude file: Automatically copy gitignored files (like .env) to new worktreesDiff View:
+12 -1) to open the diff viewerGit Worktrees:
Create a .worktreeinclude file in your repository root:
.env
.env.local
**/.claude/settings.local.json
Files matching these patterns that are also in .gitignore will be copied to new worktrees.
Installation:
Source: Desktop Documentation
Phase 1: Understand
# Start by understanding the codebase
> "Read the project structure and explain the architecture"
> "What testing framework is used?"
> "Show me the authentication flow"
# Claude will:
- Read README, package.json, etc.
- Analyze project structure
- Identify key patterns
Phase 2: Plan
# For complex features, plan first
> "I need to add user roles and permissions. Create a plan"
# Claude will:
- Break down the feature
- Identify affected files
- Consider edge cases
- Create TodoWrite tasks
Phase 3: Implement
# Implement incrementally
> "Implement step 1: Add roles to user model"
# Then verify
> "Run the tests"
# Continue
> "Implement step 2: Add permission checks to API"
Phase 4: Verify
# Always verify changes
> "Run all tests"
> "Check for TypeScript errors"
> "Review the changes we made"
# Create commit
> "Create a git commit for these changes"
For complex multi-step work:
> "Add user authentication system"
# Claude creates todos:
TodoWrite todos=[
{"content": "Create User model with password hashing", "status": "in_progress", ...},
{"content": "Implement JWT token generation", "status": "pending", ...},
{"content": "Add login/register endpoints", "status": "pending", ...},
{"content": "Add authentication middleware", "status": "pending", ...},
{"content": "Write integration tests", "status": "pending", ...}
]
# As work progresses, todos update:
# ✅ "Create User model..." - completed
# ⏳ "Implement JWT tokens..." - in_progress
# ⏸️ "Add login/register..." - pending
Parallel (Independent Tasks):
> "Create these three independent components"
# Claude can work on all simultaneously:
- Component A (no dependencies)
- Component B (no dependencies)
- Component C (no dependencies)
Sequential (Dependencies):
> "Set up database, then add user model, then create API"
# Must be done in order:
1. Database setup (others depend on this)
2. User model (API depends on this)
3. API endpoints (depends on model)
Automated Validation:
# After changes, verify automatically
> "Run the following checks:
- TypeScript compilation
- Linting
- All tests
- Build process"
# Or create a skill:
/verify-changes
Multi-Perspective Review:
# Use sub-agents for thorough review
> "Review these changes from multiple perspectives:
- Security issues
- Performance implications
- Code quality
- Test coverage"
# Launches specialized review agents
Claude Code's features form a layered automation stack. Understanding how they combine unlocks powerful workflows.
| # | Synergy | Use Case |
|---|---|---|
| 1 | Explore → Plan → Code → Commit | Standard development workflow |
| 2 | Test-Driven Development | Quality-first coding |
| 3 | MCP + Skills | External tool integrations |
| 4 | Skills + Hooks | Auto-apply expertise + enforce rules |
| 5 | Sub-agents + Background | Parallel isolated work |
| 6 | Multi-Claude Workflows | Git worktrees for parallelism |
| 7 | Context Preservation | Session continuity |
| 8 | Quality Pipeline | Automated quality enforcement |
| 9 | Visual-Driven Development | Screenshots/mockups → code |
| 10 | Log Analysis Pipeline | Unix pipes + Claude |
| 11 | Schema-Driven Development | DB schema → types/API/tests |
| 12 | Dependency Management | Update + test + fix cycle |
| 13 | Documentation Generation | Codebase → living docs |
| 14 | Refactoring with Safety | Large changes without breaking |
| 15 | Incident Response | Production debugging workflow |
Each feature serves a distinct purpose and they build on each other:
| Layer | Feature | Purpose | Invocation |
|---|---|---|---|
| Connection | MCP | External tools (GitHub, Jira, DBs) | Automatic when configured |
| Capability | Skills | Domain expertise + workflows | Auto-activated or via /skill-name |
| Enforcement | Hooks | Quality gates, auto-actions | Lifecycle events |
| Isolation | Sub-agents | Parallel specialized work | Task delegation |
| Bundling | Plugins | Package all of the above | Install once |
Key insight: MCP connects external systems. Skills provide expertise and workflows (both auto-activated and user-invoked). Hooks enforce standards. Sub-agents isolate heavy work.
The recommended workflow from Anthropic's best practices:
# Step 1: Explore - understand what exists
"Read src/auth/ and explain the current authentication flow.
List all files involved and their responsibilities."
# Step 2: Plan - use extended thinking
"Think hard about how to add OAuth2 support. Create a detailed plan
covering: files to modify, new files needed, dependencies, and test strategy."
# Step 3: Code - implement with explicit files
"Implement the OAuth2 changes following the plan. Start with
src/auth/oauth.ts, then update src/auth/index.ts to export it."
# Step 4: Commit - structured message
"Create a commit with message: 'feat(auth): add OAuth2 provider support'"
Why it works: Each step builds context. Exploring first prevents wrong assumptions. Planning with "think hard" engages extended reasoning. Explicit file names reduce ambiguity.
Write tests first, then implement:
# 1. Write failing tests first
"Write tests for a new validateEmail function in src/utils/validation.ts.
Cover: valid emails, invalid formats, empty input, null input.
Use Jest. The function doesn't exist yet - tests should fail."
# 2. Confirm tests fail
"Run npm test -- --testPathPattern=validation"
# 3. Commit the failing tests
"Commit with message: 'test(validation): add email validation tests (red)'"
# 4. Implement to pass
"Now implement validateEmail in src/utils/validation.ts to pass all tests.
Use a standard regex pattern. No external dependencies."
# 5. Verify and commit
"Run the tests again. If passing, commit: 'feat(validation): implement email validation (green)'"
Why it works: Tests define the contract before implementation. Claude iterates against concrete targets. Git history shows the TDD discipline.
MCP servers expose prompts that become skills:
# Add MCP server
claude mcp add github -- gh-mcp
# Now available as commands:
/github-pr-review # Review current PR
/github-issues # List open issues
/github-create-pr # Create PR from current branch
# Example workflow - complete ticket
/github-issues # "Show me issue #42"
# Claude fetches issue details via MCP
"Implement the feature described in issue #42.
Follow our patterns in src/features/."
/github-create-pr # Creates PR linked to issue
Real MCP integrations: GitHub, Jira, Linear, Notion, PostgreSQL, Slack, Figma, Google Drive. Each adds domain-specific commands.
Skills activate automatically; hooks enforce at lifecycle events:
.claude/
├── skills/
│ └── security-review/
│ └── SKILL.md # Auto-activates on security-related tasks
└── settings.json # Hook: block commits if security issues found
Skill definition (.claude/skills/security-review/SKILL.md):
---
name: security-review
description: Analyzes code for security vulnerabilities. Activates when
reviewing auth code, API endpoints, or user input handling.
allowed-tools: [Read, Grep, Glob]
---
When activated, check for:
- SQL injection (string concatenation in queries)
- XSS (unescaped user input in HTML)
- Exposed secrets (API keys, passwords in code)
- Broken auth (missing token validation)
Report findings with file:line references and severity.
Hook definition (in settings.json):
{
"hooks": {
"PreToolUse": [{
"tool": "Bash",
"command": "git commit",
"script": ".claude/hooks/security-check.sh"
}]
}
}
Workflow:
"Review the authentication code in src/auth/ for security issues"
# Skill auto-activates, finds issues
"Fix the SQL injection vulnerability in src/auth/login.ts:45"
# You fix it
"Commit the security fix"
# Hook runs security-check.sh before allowing commit
# Blocks if issues remain, allows if clean
Isolate work and run in parallel:
# Start services in background (Ctrl+B or explicit)
"Run npm run dev in background"
"Run npm test -- --watch in background"
# Check running tasks
/tasks
# Main session: Use explorer agent for research
"Use the explorer agent to find all API endpoints and their handlers"
# Parallel work happening:
# - Background: Dev server on port 3000
# - Background: Test watcher re-running on changes
# - Sub-agent: Scanning codebase for endpoints
# - Main session: Available for next task
# Later, retrieve agent results
"What did the explorer agent find?"
Sub-agent types: Explore (codebase search), Plan (architecture), custom agents defined in .claude/agents/.
Run multiple Claude instances for independent work:
# Terminal 1: Feature development
cd feature-branch-worktree
claude
"Implement the user dashboard feature"
# Terminal 2: Code review (same repo, different worktree)
cd review-worktree
claude
"Review the changes in the user-dashboard branch for security and performance"
# Terminal 3: Documentation
cd docs-worktree
claude
"Update API documentation based on recent changes"
Advanced: Claude reviewing Claude:
# Claude 1 writes code
"Implement rate limiting for the API endpoints in src/api/"
# Claude 2 reviews (different session)
"Review the rate limiting implementation. Check for:
- Edge cases (what happens at exactly the limit?)
- Race conditions (concurrent requests)
- Configuration flexibility (can limits be changed without deploy?)"
Combine CLAUDE.md + skills for continuity:
Project CLAUDE.md:
# Project: E-commerce API
## Current Sprint
- [ ] Implement payment webhooks
- [ ] Add inventory tracking
- [x] User authentication (completed Jan 10)
## Key Decisions
- Using Stripe for payments (see docs/adr/001-payment-provider.md)
- PostgreSQL for inventory (see src/db/schema.sql)
## Commands
npm run dev # Start on port 3000
npm test # Run Jest tests
npm run db:seed # Seed test data
Skill for context loading (.claude/skills/resume/SKILL.md):
---
name: resume
description: Resume work on current sprint
---
Read CLAUDE.md and the current sprint tasks.
Check git log for recent commits.
Summarize: what's done, what's in progress, what's next.
Ask what I want to work on.
Usage:
claude
/resume
# Claude reads context, summarizes state, ready to continue
Automated quality enforcement:
Hook configuration:
{
"hooks": {
"PostToolUse": [{
"tool": "Write",
"script": "npm run lint:fix -- $FILE"
}, {
"tool": "Edit",
"script": "npm run lint:fix -- $FILE"
}],
"PreToolUse": [{
"tool": "Bash",
"command": "git commit",
"script": ".claude/hooks/pre-commit.sh"
}]
}
}
Pre-commit hook script:
#!/bin/bash
npm run lint || exit 1
npm test || exit 1
echo "All checks passed"
Result: Every file edit auto-lints. Every commit requires passing tests. Quality enforced without manual intervention.
Use screenshots and mockups as implementation targets:
# Share a design mockup
"Here's the Figma mockup for the new dashboard @mockups/dashboard.png
Implement this in src/components/Dashboard.tsx using our existing
Button, Card, and Chart components. Match the layout exactly."
# Iterate on visual feedback
"Here's a screenshot of the current result @screenshots/current.png
Compare to the mockup. Fix: the spacing between cards is wrong,
and the chart colors don't match."
# Debug visual issues
"This screenshot shows a layout bug on mobile @bugs/mobile-layout.png
The sidebar overlaps the content. Fix the responsive styles in
src/styles/layout.css"
Why it works: Claude can see images. Concrete visual targets reduce ambiguity. Iteration is fast.
Unix pipes + Claude for real-time analysis:
# Monitor logs for anomalies
tail -f /var/log/app.log | claude -p "Alert me if you see errors or unusual patterns"
# Analyze crash dumps
cat crash.log | claude -p "Analyze this crash. Identify root cause and suggest fix."
# Parse and summarize
grep "ERROR" app.log | claude -p "Categorize these errors by type and frequency. Which is most critical?"
# CI/CD integration
npm test 2>&1 | claude -p "If tests failed, explain why and suggest fixes"
Why it works: Claude integrates with Unix pipelines. Composable with existing tools.
Database schema as source of truth:
# Generate types from schema
"Read prisma/schema.prisma and generate TypeScript interfaces
in src/types/database.ts. Include JSDoc comments explaining each field."
# Create API endpoints from schema
"Based on the User model in schema.prisma, create CRUD endpoints
in src/api/users.ts. Include validation using zod."
# Generate test fixtures
"Read the schema and create realistic test fixtures in
tests/fixtures/users.ts. Cover edge cases: empty strings,
max lengths, special characters."
# Migration safety check
"Compare prisma/schema.prisma with the current database.
Identify breaking changes. Suggest migration strategy."
Why it works: Schema is the contract. Generate everything from it. Single source of truth.
Update, test, and fix in one flow:
# Check for updates
"Run npm outdated. For each major update, explain breaking changes
and effort to upgrade."
# Upgrade with safety net
"Upgrade lodash to v5. Run tests. If anything breaks, fix it.
Commit only when tests pass."
# Security audit flow
"Run npm audit. For each vulnerability:
1. Check if we actually use the affected code path
2. If yes, upgrade or find alternative
3. If no, document why it's acceptable"
# License compliance
"Check licenses of all dependencies. Flag any GPL or unknown
licenses. We need MIT/Apache/BSD only."
Why it works: Dependency management is tedious. Claude handles the research and fixes.
Codebase exploration → living documentation:
# API documentation
"Explore src/api/ and generate OpenAPI spec in docs/api.yaml.
Include request/response examples from actual code."
# Architecture documentation
"Analyze the codebase structure. Create docs/ARCHITECTURE.md
explaining: folder structure, data flow, key patterns used."
# Onboarding guide
"Create docs/ONBOARDING.md for new developers. Include:
setup steps, key files to understand first, common tasks,
gotchas you found in the code."
# Changelog from commits
"Read git log for the last month. Generate CHANGELOG.md
grouped by: Features, Fixes, Breaking Changes."
Why it works: Documentation stays in sync with code. Generated from source, not memory.
Large refactors without breaking things:
# Rename with confidence
"Rename the User class to Account across the entire codebase.
Update all imports, types, and documentation. Run tests after."
# Extract component
"The Dashboard component is 500 lines. Extract the chart logic
into src/components/DashboardChart.tsx. Keep all behavior identical.
Tests must still pass."
# Change data structure
"Migrate from storing user.fullName to user.firstName + user.lastName.
Update: database schema, API responses, frontend display, tests.
Create migration script for existing data."
# Upgrade patterns
"Replace all callback-style async code in src/services/ with
async/await. One file at a time. Test after each file."
Why it works: TodoWrite tracks progress. Tests verify correctness. Safe incremental changes.
Debug production issues systematically:
# Initial triage
"Production is returning 500 errors. Here's the error log:
[paste log]
Identify the most likely cause. List files to investigate."
# Root cause analysis
"Read the files identified. Trace the code path from
API endpoint to error. Explain exactly where and why it fails."
# Fix with minimal blast radius
"Implement the smallest possible fix. Don't refactor.
Just stop the bleeding. Add a TODO for proper fix later."
# Post-mortem documentation
"Create docs/incidents/2024-01-15-500-errors.md documenting:
what happened, root cause, fix applied, prevention measures."
Why it works: Structured approach prevents panic. Documentation prevents recurrence.
Based on Anthropic's guidance:
| Instead of... | Write... |
|---|---|
| "Add tests" | "Write Jest tests for src/utils/date.ts covering: formatDate with valid dates, invalid inputs, and timezone handling" |
| "Fix the bug" | "The login fails when email contains '+'. Fix src/auth/validate.ts:23 to handle plus signs in email addresses" |
| "Review this" | "Review src/api/users.ts for: N+1 queries, missing error handling, and SQL injection risks" |
| "Make it faster" | "Profile the /api/products endpoint. Identify the slowest operation and optimize it. Target: <100ms response" |
Thinking modes (escalating reasoning depth):
"think" - Standard extended thinking"think hard" - More thorough analysis"think harder" - Deep exploration of options"ultrathink" - Maximum reasoning budgetFile references:
# Use tab-completion or explicit paths
"Read @src/auth/login.ts and explain the authentication flow"
# Multiple files
"Compare @src/api/v1/users.ts and @src/api/v2/users.ts - what changed?"
1. Understand the "when" of each feature:
| Feature | Activates When... |
|---|---|
| MCP | External data/action needed |
| Skills | Context matches description (automatic) |
| Commands | User types /command (manual) |
| Hooks | Lifecycle event fires (PreToolUse, PostToolUse, etc.) |
| Sub-agents | Task delegated for isolated work |
2. Combinations multiply value:
MCP alone = 1x (fetch data)
MCP + Skill = 3x (fetch + auto-expertise)
MCP + Skill + Hook = 9x (fetch + expertise + enforce)
Each layer multiplies the previous. Invest in setup.
3. Prompting is the foundation: All synergies fail with vague prompts. Master specificity first:
4. We showed 15 synergies. There are many more. These patterns are starting points. Combine them, adapt them, discover your own. The best workflows are the ones tailored to your project.
5. Setup cost amortizes:
One hour configuring .claude/ saves hundreds of hours across future sessions. Treat it as infrastructure.
# Understanding current system
> "Analyze the current user management system"
# Planning
> "Create a plan to add JWT-based authentication"
# Implementation
> "Implement the authentication system following the plan"
# (Claude creates TodoWrite tasks and works through them)
# Testing
> "Create comprehensive tests for authentication"
# Security review
> "Review the authentication implementation for security issues"
# Documentation
> "Update the API documentation with authentication endpoints"
# Commit
> "Create a git commit for the authentication feature"
# Identify issues
> "Analyze the codebase for performance bottlenecks"
# Create optimization plan
> "Create a plan to optimize the most critical issues found"
# Implement optimizations
> "Implement the database query optimizations"
# Benchmark
> "Create benchmarks to measure the improvements"
# Verify
> "Run the benchmarks and compare before/after"
# Provide context
> "Users report login fails intermittently. Here's the error log: [paste log]"
# Investigation with Debug agent
> "Use the debugger agent to investigate this issue"
# Root cause analysis
> "Explain what's causing this and why it's intermittent"
# Fix
> "Implement a fix for this issue"
# Prevention
> "Add tests and logging to prevent this in the future"
# Documentation
> "Update CLAUDE.md with what we learned about this issue"
# Analyze current API
> "Document all endpoints in the v1 API"
# Plan migration
> "Create a migration plan from v1 to v2 with these changes: [list changes]"
# Implement new version
> "Implement the v2 API alongside v1"
# Ensure backward compatibility
> "Create a compatibility layer so v1 clients still work"
# Testing
> "Create tests ensuring both v1 and v2 work correctly"
# Documentation
> "Generate migration guide for API consumers"
# Research
> "Research GitHub Actions best practices for Node.js projects"
# Create workflow
> "Create a GitHub Actions workflow that:
- Runs on pull requests
- Checks TypeScript compilation
- Runs linting
- Runs all tests
- Reports coverage"
# Security scanning
> "Add security scanning to the workflow"
# Deployment
> "Add automatic deployment to staging on merge to main"
# Documentation
> "Document the CI/CD setup in README.md"
# Add directories
> "Add the frontend and backend directories to the workspace"
# Synchronized changes
> "Update the User type definition in backend and propagate to frontend"
# Cross-project validation
> "Ensure the frontend API calls match the backend endpoints"
# Parallel testing
> "Run backend tests and frontend tests in parallel in background"
# Monitor both
> "Start both dev servers and monitor for errors"
# Start all development services in background
> "Start the frontend dev server in background"
> "Start the backend API server in background"
> "Run tests in watch mode in background"
# Configure status line to track all services
/statusline
# Monitor all services simultaneously
> "Monitor all background processes for errors"
# Claude watches logs from all background tasks
# Identifies issues across services
# Suggests fixes without stopping services
# Fix issues dynamically
> "I see an API timeout error"
# Claude checks backend logs, identifies cause, suggests solution
# Check all background tasks
/bashes
# Stop specific service if needed
/kill <id>
# Start major feature development
> "Build a complete user authentication system with JWT, refresh tokens, and password reset"
# Work progresses, context accumulates...
# After reading many files and multiple operations
# Context is getting large
# Use microcompact for intelligent cleanup
/compact "focus"
# Keeps: Current auth work, recent changes, patterns learned
# Removes: Old file reads, completed searches, stale context
# Continue seamlessly with clean context
> "Add two-factor authentication to the system"
# Full context available for current authentication work
# Major context switch to new feature
/compact
# Complete reset for fresh start
> "Implement Stripe payment integration"
# Clean slate for payment feature
# Plan with security considerations
> "Design a user input handling system for our forms. Focus on security best practices"
# Implement with immediate security review
> "Implement the form validation system"
> "Review the form validation code for security vulnerabilities"
# Fix identified issues
> "Fix the XSS vulnerability in the email field validation"
> "Verify the fix addresses all injection vectors"
# Document security patterns
> "Update CLAUDE.md with our input validation security patterns"
# Set up continuous security monitoring
> "Create a GitHub Action that runs security scans on every PR"
# Initialize multi-repo workspace
/add-dir ~/projects/backend
/add-dir ~/projects/frontend
/add-dir ~/projects/shared-types
# Synchronize type definitions across projects
> "Update the User type in shared-types and ensure backend and frontend are consistent"
# Parallel type checking
> "Run TypeScript type checking in all three projects simultaneously in background"
# Monitor and fix type errors
> "Check background tasks for any type errors"
> "Fix type mismatches found in frontend"
# Cross-repo validation
> "Verify that all API types in backend match the frontend client expectations"
# Start all dev servers
> "Start backend server, frontend server, and type watching in background"
# Unified development experience
> "Build the checkout flow, coordinating changes across backend API and frontend UI"
# Claude makes coordinated changes across all repos
1. Set Up CLAUDE.md First
- Document your project structure
- List important commands
- Note conventions and patterns
- Add known gotchas
- Update it as you learn
2. Use Descriptive Requests
# Good
> "Add input validation to the login endpoint, checking email format and password length"
# Less effective
> "Fix login"
3. Verify Changes
# Always review before committing
> "Show me all the changes made"
> "Run tests to verify the changes"
4. Incremental Development
# Break large features into steps
> "First, let's add the database model"
> "Now add the API endpoint"
> "Finally, add the frontend form"
5. Leverage Tools Intelligently
# Use Grep for finding patterns
> "Find all database queries using raw SQL"
# Use Glob for file discovery
> "Find all test files"
# Use sub-agents for exploration
> "Have an Explore agent map out the authentication flow"
Quick decision trees for common scenarios:
Something's not working:
→ Can you reproduce it?
→ Yes: Debug systematically
→ No: Gather more info first
→ Did it work before?
→ Yes: Check recent changes (git diff)
→ No: Check assumptions
→ Is error message clear?
→ Yes: Address directly
→ No: Trace execution with logging
Adding a new feature:
→ Similar feature exists?
→ Yes: Follow that pattern
→ No: Research best practices
→ Touches existing code?
→ Yes: Understand it first (read, analyze)
→ No: Design in isolation
→ Has complex logic?
→ Yes: Break down first (use TodoWrite)
→ No: Implement directly
Code seems slow:
→ Measured it? → No: Profile first
→ Know the bottleneck? → No: Find it (use ultrathink)
→ Have solution? → No: Research, then implement and measure again
Recovery When Things Go Wrong:
# Establish facts
> "What's the current state of the codebase?"
# Find smallest step forward
> "What's the simplest fix that would work?"
# Question assumptions
> "Let me re-read the relevant code"
# Find solid ground
> "Let's revert to the last working state with /rewind"
Complexity-Driven Approach:
| Task Type | Approach |
|---|---|
| Trivial (typo fix) | Just fix it |
| Simple (add button) | Quick implementation |
| Medium (new feature) | Plan → Implement → Test |
| Complex (architecture) | Research → Design → Prototype → Implement → Migrate |
| Unknown | Explore to assess, then choose approach |
1. Share Configuration
# Commit to git:
.claude/
├── settings.json # Shared permissions and config
├── commands/ # Team workflows
├── skills/ # Team Skills
└── agents/ # MCP servers & sub-agents
# Git-ignore:
.claude/settings.local.json # Personal overrides
2. Document Patterns in CLAUDE.md
## Team Conventions
- All API routes follow RESTful patterns
- Database migrations use Prisma
- Tests use the AAA pattern (Arrange, Act, Assert)
- Never commit directly to main
3. Create Workflow Skills
# .claude/skills/
├── code-review/
│ └── SKILL.md
├── deploy-staging/
│ └── SKILL.md
├── run-checks/
│ └── SKILL.md
└── security-audit/
└── SKILL.md
4. Use Hooks for Standards
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{"type": "command", "command": "eslint-check.sh"}
]
}
]
}
}
1. Protect Sensitive Files
{
"permissions": {
"deny": [
"Read(*.env)",
"Read(.env.*)",
"Read(*.key)",
"Read(*.pem)",
"Edit(*.env)",
"Edit(.env.*)",
"Edit(*.key)",
"Edit(*.pem)",
"Edit(.git/**)"
]
}
}
Deny Read as well as Edit — a rule that only blocks edits still lets Claude read the secret into context. Edit rules cover all file-editing tools, so no separate Write rule is needed.
2. Review Before Execution
{
"permissions": {
"defaultMode": "default",
"ask": ["Bash", "Edit"]
}
}
There is no "ask" permission mode. Stay in "default" mode and add ask rules for the tools you want to confirm every time.
3. Use Hooks for Auditing
{
"hooks": {
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "echo \"$(date): $TOOL_NAME\" >> .claude/audit.log"
}
]
}
]
}
}
4. Regular Security Reviews
# Use security review Skill or command
> "Perform a security audit of the authentication system"
Issue: "Context too large" error
# Solution 1: Compact context
> /compact
# Solution 2: Smart cleanup
> /compact "focus"
# Prevention: Regular compaction in long sessions
Issue: Edit tool fails with "string not found"
# Solution: Read the file first to see exact content
> Read the file to see the exact string
# Ensure exact match including:
- Whitespace and indentation
- Line breaks
- Special characters
# Use larger context if string appears multiple times
Issue: Permission denied
# Solution 1: Grant permission when asked
# Solution 2: Pre-configure in settings.json
# (allow/ask/deny are arrays of "Tool(specifier)" strings)
{
"permissions": {
"allow": ["Bash(npm test)", "Edit"]
}
}
# Check current permissions
> /hooks # Shows hook configuration
Issue: Claude doesn't see recent file changes
# Solution: Explicitly ask to re-read
> "Read the app.ts file again"
# Or provide the changes
> "I just updated the config, here's what changed: [paste]"
Issue: Background task not responding
# Check status
> /bashes
# Kill if stuck
> /kill <id>
# Restart
> "Start the dev server again in background"
Issue: Git operations fail
# Check git status
> "Run git status"
# Common fixes:
- Unstaged changes: "git add the files first"
- Merge conflicts: "Show me the conflicts and help resolve"
- Branch issues: "Switch to the correct branch"
Issue: MCP server not working
# Check configuration
> "Show me the MCP configuration"
# Verify server is running
> "Check if the MCP server started correctly"
# Check logs
~/.claude/logs/mcp-<server-name>.log
# Reinstall
> "Reinstall the MCP server package"
Systematic approaches to common error scenarios.
# If session disconnects mid-task:
1. Check recent history:
> "What was I working on?"
2. Review file changes:
git diff
3. Reconstruct state:
> "Based on recent changes, continue where we left off"
# If hook blocks unexpectedly:
1. Check hook output:
claude --debug
2. Test hook manually:
echo '{"tool_name":"Edit","tool_input":{...}}' | ~/.claude/hooks/script.sh
3. Temporarily disable:
mv ~/.claude/settings.json ~/.claude/settings.json.bak
4. Fix and restore:
# Fix the hook script, then restore settings
# When "context too large" appears during complex work:
# Quick recovery:
> /compact "focus"
> "Continue with [brief task summary]"
# Full reset if needed:
> /compact
> "Let me brief you: [key context]"
# Prevention:
- Use /compact "focus" every ~50 operations
- Start fresh sessions for new features
# When permissions repeatedly requested:
# Grant permanently (a bare tool name allows every use of that tool;
# "Edit" already covers all file-editing tools, including Write):
{
"permissions": {
"allow": ["Bash", "Edit"]
}
}
# Or specific patterns:
{
"permissions": {
"allow": ["Bash(npm test)", "Bash(npm run build)"]
}
}
# If operations timeout:
# Retry with backoff:
1st attempt → fails
Wait 2s → retry
Wait 4s → retry
Wait 8s → retry
# Switch model if persistent:
> "Use a different model to try this"
# Check network:
ping anthropic.com
curl -v https://api.anthropic.com
# If changes weren't saved:
1. Check git:
git status
git diff
2. Check file backups:
ls -la ~/.claude/backups/
3. Review session transcript:
# Transcripts saved in ~/.claude/transcripts/
4. Reconstruct from memory:
> "Based on our conversation, recreate the [feature]"
# Enable comprehensive debugging:
claude --debug --log-level trace
# Follow logs in real-time:
tail -f ~/.claude/logs/claude.log
# Filter for specific issues:
grep -i error ~/.claude/logs/claude.log
grep -i "mcp" ~/.claude/logs/claude.log
Claude Code operates with:
1. Permission System
2. Sandboxing (macOS/Linux)
{
"sandbox": {
"enabled": true,
"allowUnsandboxedCommands": false
}
}
3. File Access Control
{
"permissions": {
"additionalDirectories": ["/allowed/path"],
"deny": [
"Read(*.key)",
"Read(*.pem)",
"Read(*.env)",
"Edit(*.key)",
"Edit(*.pem)",
"Edit(*.env)",
"Edit(.git/**)"
]
}
}
1. Never Commit Secrets
# Block in settings
{
"permissions": {
"deny": [
"Read(*.env)",
"Read(*.key)",
"Read(*.pem)",
"Read(*secret*)",
"Edit(*.env)",
"Edit(*.key)",
"Edit(*.pem)",
"Edit(*secret*)"
]
}
}
# Use hooks to scan for secrets
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{"type": "command", "command": "detect-secrets-hook.sh"}
]
}
]
}
}
2. Review AI-Generated Code
# Always review before deploying
> "Explain the security implications of this code"
> "Review this for potential vulnerabilities"
3. Limit Tool Access
// For sub-agents doing analysis
{
"allowedTools": ["Read", "Grep", "Glob"] // No modifications
}
// For implementation agents
{
"allowedTools": ["Read", "Write", "Edit", "Bash"] // Can modify
}
4. Audit Trails
{
"hooks": {
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "logger.sh" // Log all operations
}
]
}
]
}
}
5. Network Restrictions
{
"sandbox": {
"network": {
"allowUnixSockets": ["/var/run/docker.sock"],
"allowLocalBinding": true,
"httpProxyPort": 8080
}
}
}
Source: Settings, Sandboxing
Claude Code can be used programmatically via TypeScript/Python SDKs.
import { ClaudeCodeSDK } from '@anthropic-ai/claude-code';
const sdk = new ClaudeCodeSDK({
apiKey: process.env.ANTHROPIC_API_KEY
});
// Start a session
const session = await sdk.startSession({
projectDir: '/path/to/project',
systemPrompt: 'You are a code reviewer'
});
// Send a task
const response = await session.chat({
message: 'Review this codebase for security issues'
});
console.log(response.content);
// End session
await session.end();
from anthropic_sdk import ClaudeCodeSDK
sdk = ClaudeCodeSDK(api_key=os.environ["ANTHROPIC_API_KEY"])
# Start session
session = sdk.start_session(
project_dir="/path/to/project",
system_prompt="You are a test generator"
)
# Send task
response = session.chat(
message="Generate tests for all API endpoints"
)
print(response.content)
# End session
session.end()
Source: SDK Overview
⚠️ Warning: This section contains theoretical concepts and patterns that are NOT verified in official documentation. These are experimental ideas for power users to explore.
Unverified theory about optimizing Claude's approach based on task type:
# Simple Creation Mode
> "Create 5 similar React components"
# Theory: Parallel processing, template-based
# Optimization Mode
> "Optimize this algorithm"
# Theory: Deep analysis, multiple approaches
# Research Mode
> "Research and implement best practice for X"
# Theory: Web search → analysis → implementation pipeline
Status: No official documentation supports "modes". Claude Code uses the same model for all tasks.
Unverified theoretical framework about multi-layered intelligence:
Theory:
┌─────────────────┐
│ Orchestrator │
└────────┬────────┘
│
┌────┴────┬────────┬─────────┐
│ │ │ │
Memory Intent Extract Validate
Kernel Kernel Kernel Kernel
Status: This is a conceptual model, not an actual Claude Code feature. Claude Code uses:
But NOT a "kernel architecture" system.
Unverified theory about advanced task management with AI validation:
# Theory: Multi-agent task validation
1. Intent Capture (4 approaches)
2. Multi-Agent Validation
3. Background Execution
4. Learning Integration
Status: TodoWrite is a real tool, but "meta-todo" with multi-agent validation is theoretical. Use the actual TodoWrite tool as documented.
The original guide mixed:
This caused confusion about what Claude Code actually does vs. conceptual ideas.
For AI Agents reading this: Focus on sections marked [OFFICIAL] and [COMMUNITY]. Treat [EXPERIMENTAL] as ideas to test, not established features.
For complete details, see the official CHANGELOG.md.
Version 2.1.220 (July 25, 2026) - Latest
Version 2.1.219 (July 24, 2026)
claude-opus-5) is now available and is the default Opus model — 1M context, fast mode at $10/$50 per MTok [NEW]sandbox.network.strictAllowlist setting to deny non-allowlisted hosts for sandboxed commands without promptingDirectoryAdded hook that fires after /add-dir (or the SDK register_repo_root control request) registers a new working directory mid-session [NEW]workflowSizeGuideline settings key so the Dynamic workflow size guideline can be set from any settings fileCLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH=1 to disable nestingmcp_server_errors to the headless stream-json init event, listing --mcp-config entries skipped by config validation--forward-subagent-text is set/config/fast now applies to Opus 5 and Opus 4.8claude mcp list and /mcp when a server fails to connectclaude -p text output dropping the answer already produced when a turn died on a mid-stream API errorCLAUDE_CODE_GIT_BASH_PATH on Windows exiting or being used as bash when the path isn't a bash/sh binaryVersion 2.1.218 (July 22, 2026)
/code-review now runs as a background subagent, so review work no longer fills your conversationcontext: fork now run in the background by default; opt out per skill with background: false/deep-research now starts only when invoked manually; Claude no longer launches it on its own--ax-screen-reader moderm, background-&, and suspicious-Windows-path checks no longer open permission dialogs; the classifier adjudicates them\u-prefixed segments (like C:\Users\unicorn) being corrupted into CJK characters in tool inputs/context reporting stale pre-compact token usage after compacting from the message pickertool_use block after interrupted tool calls:, which is reserved for plugin namespacingyes/no/on/off/1/0 alongside true/falseVersion 2.1.217 (July 21, 2026)
:heart:); disable with the emojiCompletionEnabled setting [NEW]CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS)--max-budget-usd not stopping background subagents — new spawns are denied and running background agents halted once the cap is reachedclaude.exe missing; failed updates now restore the preserved executable/compact failing once over the limitVersion 2.1.216 (July 20, 2026)
sandbox.filesystem.disabled setting to skip filesystem isolation while keeping network egress controlgit -C, --git-dir, or GIT_DIR/GIT_WORK_TREE.claude, which could redirect writes outside the project/rewind no longer restores or deletes files through symlinks or hard links at tracked paths&& lists or negationsclaude daemon stop --any potentially terminating an unrelated process via a stale legacy daemon lockfileVersion 2.1.215 (July 19, 2026)
/verify and /code-review skills on its own; invoke them explicitly when you want themVersion 2.1.214 (July 18, 2026)
dir/** allow rules like Edit(src/**) auto-approving writes to nested dir/ directories anywhere in the tree[[ ]]docker commands carrying daemon-redirect flags (--url, --connection, --identity, Podman remote mode)message.uuid, client_request_id, and tool_source attributes to OpenTelemetry log eventsCLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH to configure the 60 KB truncation limit on OpenTelemetry content attributesmodified timestamp to memory file frontmatterdir/** hook if: conditions now match only <cwd>/dir; write **/dir/** for any-depth matchingSessionStart hooks now report source "fork" when a session begins as a fork instead of "resume"UnicodeDecodeError/UnicodeEncodeError on non-UTF-8 data, and UTF-16LE redirect outputVersion 2.1.212 (July 17, 2026)
/fork now copies your conversation into a new background session (its own row in claude agents); the in-session subagent it used to launch is now /subtaskclaude auto-mode reset to restore the default auto-mode configuration (--yes skips the confirmation)CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION) to stop runaway search loopsCLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION); /clear resets the budgetCLAUDE_CODE_MCP_AUTO_BACKGROUND_MS)touch, rm) without a permission prompt or SDK canUseTool callback.claude/worktreescontinue:false hook's halt being dropped when the tool fails or completes mid-streammode parameter (now ignored); subagents inherit the parent session's permission mode by defaultforceLoginMethod is now enforced for VS Code, SDK, setup-token, and install-github-app logins, not just the terminal/background and claude --bg failing with uv_spawn errors on Windows when Group Policy blocks PowerShell 5.1SendMessage bodies are no longer duplicated into replayed historyVersion 2.1.211 (July 15, 2026)
--forward-subagent-text flag and CLAUDE_CODE_FORWARD_SUBAGENT_TEXT env var to include subagent text and thinking in stream-json output [NEW]PreToolUse hook's ask decision for unsandboxed Bash — a hook ask now floors the decision at a prompt/clear not resetting the session cost counter1e6 and 64_000 spellingsVersion 2.1.210 (July 14, 2026)
isolation: 'worktree' subagents being able to run git-mutating commands against the main repo checkoutWrite(path), NotebookEdit(path), and Glob(path) permission rules — use Edit(path) or Read(path) instead$1/$2 positional placeholders in skills and commands being silently stripped — they are now preserved verbatimVersion 2.1.209 (July 14, 2026)
/model and other dialogs being blocked in claude agents background sessionsVersion 2.1.208 (July 14, 2026)
claude --ax-screen-reader, CLAUDE_AX_SCREEN_READER=1, or "axScreenReader": true in settings [NEW]vimInsertModeRemaps setting to map two-key insert-mode sequences like jj to Escape in vim modeCLAUDE_CODE_PROCESS_WRAPPER so corporate launchers can wrap every Claude Code self-spawnclaude -pCLAUDE_CODE_MAX_OUTPUT_TOKENS and similar env vars silently using the mantissa of scientific-notation values (1e6 became 1)/release-notes adding the viewed notes to the model's context$(…)/backticks/<(…) now prompt in --dangerously-skip-permissions and auto modeVersion 2.1.207 (July 11, 2026)
CLAUDE_CODE_ENABLE_AUTO_MODE opt-in on Bedrock, Vertex AI, and Foundry; disable via disableAutoModeheadersHelper: ${user_config.*} in shell-form commands is now rejected (shell-injection fix)pluginConfigs) are no longer read from project-level .claude/settings.jsonautoMode from .claude/settings.local.json; use ~/.claude/settings.json instead~/.local/bin/claude on every releaseVersion 2.1.206 (July 10, 2026)
/cd, matching /add-dir behavior/doctor check that proposes trimming checked-in CLAUDE.md filesEnterWorktree now asks for confirmation before entering a git worktree outside .claude/worktrees//commit-push-pr now auto-allows git push to the repo's configured push remote (remote.pushDefault) in addition to origin--mcp-config or .mcp.json ignoring a per-server request_timeout_msCLAUDE_CODE_EXTRA_BODY being silently ignored by claude agents / --bg background workersclaude --resume and --continue not responding to keyboard input on startupVersion 2.1.205 (July 8, 2026)
/doctor is now a full setup checkup that can diagnose and fix issues; /checkup is an alias--json-schema silently producing unstructured output when the schema was invalid, and schemas using format being rejected--max-turns limitrm -rf on a variable it can't resolve from contextVersion 2.1.204 (July 8, 2026)
SessionStart hooks in headless sessions, which could cause remote workers to be idle-reaped mid-hookVersion 2.1.203 (July 7, 2026)
roots/list, with notifications/roots/list_changed on changeclaude agents silently stopping running subagents and re-running the prompt from scratchPATH from the daemon instead of the dispatching shellANTHROPIC_BASE_URLTaskStop and TaskOutput failing to find background agents spawned by another agentVersion 2.1.202 (July 6, 2026)
/config controlling how large Claude generally makes dynamic workflows (advisory, not an enforced cap)workflow.run_id and workflow.name OpenTelemetry attributes to telemetry emitted by workflow-spawned agents/review <pr> is back to a fast single-pass review; use /code-review <level> <pr#> for the multi-agent review/rename on background sessions being reverted when the job restartsVersion 2.1.201 (July 3, 2026)
Version 2.1.200 (July 3, 2026)
AskUserQuestion dialogs no longer auto-continue by default; opt into an idle timeout via /config--help, VS Code, and JetBrains; --permission-mode manual and "defaultMode": "manual" are accepted alongside defaultdisabledMcpServers or enabledMcpServers in .claude.json is set to a non-array valuedaemon.lock whose PID the OS reusedHeader: value. linesVersion 2.1.199 (July 2, 2026)
/skill-a /skill-b do XYZ now load all leading skills (up to 5), not just the firTruncated — view the full README on GitHub.
688 followers · starred Sep 2025
165 followers · starred Nov 2025
244 followers · starred Aug 2025
25 followers · starred Sep 2025