Claude Code CLI: The Definitive Technical Reference
# Complete Claude Code CLI guide: installation, configuration, subagents, MCP integrations, hooks, skills, remote execution, IDE integration, and enterprise deployment patterns.
Claude Code CLI: The Definitive Technical Reference
Claude Code operates as an agentic system, not a chat interface with programming knowledge. The CLI reads your codebase, executes commands, modifies files, manages git workflows, connects to external services via MCP, and delegates complex tasks to specialized subagents. Everything flows through a command-line interface that integrates into how developers actually work.
The difference between casual and effective Claude Code usage comes down to five core systems. Master these and Claude Code becomes a force multiplier:
- Configuration hierarchy — controls behavior
- Permission system — gates operations
- Hook system — enables deterministic automation
- MCP protocol — extends capabilities
- Subagent system — handles complex multi-step tasks
I spent months pushing Claude Code to its limits across production codebases, CI/CD pipelines, and enterprise deployments. This guide distills that experience into the comprehensive reference I wish existed when I started. Every feature includes actual syntax, real configuration examples, and the edge cases that trip up experienced users.
How Claude Code Works: The Mental Model
Before diving into features, understand how Claude Code’s architecture shapes everything you do with it. The system operates in three layers:
┌─────────────────────────────────────────────────────────┐
│ CLAUDE CODE LAYERS │
├─────────────────────────────────────────────────────────┤
│ EXTENSION LAYER │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ MCP │ │ Hooks │ │ Skills │ │ Plugins │ │
│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │
│ External tools, deterministic automation, domain │
│ expertise, packaged extensions │
├─────────────────────────────────────────────────────────┤
│ DELEGATION LAYER │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Subagents (up to 10 parallel) │ │
│ │ Explore | Plan | General-purpose | Custom │ │
│ └─────────────────────────────────────────────────┘ │
│ Isolated contexts for focused work, returns summaries │
├─────────────────────────────────────────────────────────┤
│ CORE LAYER │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Main Conversation Context │ │
│ │ Tools: Read, Edit, Bash, Glob, Grep, etc. │ │
│ └─────────────────────────────────────────────────┘ │
│ Your primary interaction; limited context; costs money │
└─────────────────────────────────────────────────────────┘
Core Layer: Your main conversation. Every message, file read, and tool output consumes context from a shared 200K token window (1M with premium). When context fills, Claude loses track of earlier decisions and quality degrades. This layer costs money per token.
Delegation Layer: Subagents spawn with clean contexts, do focused work, and return summaries. The exploration results don’t bloat your main conversation—only the conclusions return. Use Haiku subagents for exploration (cheap, fast) and Sonnet for implementation.
Extension Layer: MCP connects external services (databases, GitHub, Sentry). Hooks guarantee execution of shell commands regardless of model behavior. Skills encode domain expertise that Claude applies automatically. Plugins package all of these for distribution.
The key insight: Most users work entirely in the Core Layer, watching context bloat and costs climb. Power users push exploration and specialized work to the Delegation Layer, keep the Extension Layer configured for their workflow, and use the Core Layer only for orchestration and final decisions.
Table of Contents
- How Do I Install Claude Code?
- Core Interaction Modes
- Configuration System Deep Dive
- Which Model Should I Choose?
- How Does the Permission System Work?
- How Do Hooks Work?
- What Is MCP (Model Context Protocol)?
- What Are Subagents?
- What Is Extended Thinking Mode?
- Output Styles
- Slash Commands
- How Do Skills Work?
- Plugin System
- How Does Memory Work?
- Image and Multimodal Input
- How Does Git Integration Work?
- How Do I Use Claude Code in My IDE?
- Advanced Usage Patterns
- What Is Claude Code Remote?
- What Are Background Agents?
- Claude in Chrome
- Claude Code in Slack
- What Does Claude Code Cost?
- Performance Optimization
- How Do I Debug Issues?
- Enterprise Deployment
- Keyboard Shortcuts Reference
- Best Practices
How Do I Install Claude Code?
System Requirements
Claude Code runs on macOS 10.15+, Ubuntu 20.04+/Debian 10+, and Windows 10+ through WSL or Git Bash. The system requires 4 GB RAM minimum and an active internet connection. Shell compatibility works best with Bash, Zsh, or Fish.
For Windows, both WSL 1 and WSL 2 work. Git Bash also works if you prefer native Windows. Alpine Linux and other musl-based systems require additional packages:
apk add libgcc libstdc++ ripgrep
export USE_BUILTIN_RIPGREP=0
Installation Methods
Native installation (recommended)
The native binary provides the cleanest experience with no Node.js dependency:
# macOS and Linux
curl -fsSL https://claude.ai/install.sh | bash
# Homebrew alternative
brew install --cask claude-code
# 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
For version-specific installation:
# Install specific version
curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58
# Install latest explicitly
curl -fsSL https://claude.ai/install.sh | bash -s latest
# Windows PowerShell - specific version
& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 1.0.58
NPM installation (deprecated)
Note: As of v2.1.15, npm installations show a deprecation notice. The native binary is now the recommended installation method. Migrate with
claude install.
For legacy environments where npm is still needed:
npm install -g @anthropic-ai/claude-code
Never use sudo with npm installation—it creates permission issues that complicate everything downstream.
Migration from existing installation
If you have an older npm-based installation, migrate to the native binary:
claude install
Authentication Options
Claude Code supports three authentication paths, each with different tradeoffs:
Claude Console (API billing)
Connect to Anthropic’s API directly through platform.claude.com (previously console.anthropic.com). Create an account, set up billing, and authenticate through the CLI. This provides usage-based billing with full API access. A dedicated “Claude Code” workspace is created automatically—you cannot create API keys for this workspace, but you can monitor usage.
Claude Pro or Max subscription
Use your claude.ai account credentials. The subscription covers both the web interface and CLI usage under a single monthly plan. This simplifies billing for individual users who want predictable costs.
Enterprise platforms
AWS Bedrock, Google Vertex AI, and Microsoft Foundry each provide enterprise-grade access with existing cloud billing relationships:
# AWS Bedrock
export CLAUDE_CODE_USE_BEDROCK=1
export AWS_REGION=us-east-1
export AWS_PROFILE=your-profile
# Google Vertex AI
export CLAUDE_CODE_USE_VERTEX=1
export CLOUD_ML_REGION=us-east5
export ANTHROPIC_VERTEX_PROJECT_ID=your-project
# Microsoft Foundry
export CLAUDE_CODE_USE_FOUNDRY=1
export ANTHROPIC_FOUNDRY_RESOURCE=your-resource-name
# Optional: API key auth (otherwise uses Entra ID)
export ANTHROPIC_FOUNDRY_API_KEY=your-key
For enterprise deployments behind proxies or through LLM gateways:
# Corporate proxy
export HTTPS_PROXY='https://proxy.example.com:8080'
# LLM gateway (skip native auth)
export CLAUDE_CODE_USE_BEDROCK=1
export ANTHROPIC_BEDROCK_BASE_URL='https://your-gateway.com/bedrock'
export CLAUDE_CODE_SKIP_BEDROCK_AUTH=1
Verification
claude doctor
This reports installation type, version, system configuration, and any detected issues.
Updates
Claude Code auto-updates by default, checking at startup and periodically during sessions. Updates download in the background and apply on next launch.
Disable auto-updates:
export DISABLE_AUTOUPDATER=1
Or in settings.json:
{
"env": {
"DISABLE_AUTOUPDATER": "1"
}
}
Manual update:
claude update
Uninstallation
Native installation (macOS/Linux/WSL):
rm -f ~/.local/bin/claude
rm -rf ~/.claude-code
Native installation (Windows PowerShell):
Remove-Item -Path "$env:LOCALAPPDATA\Programs\claude-code" -Recurse -Force
Remove-Item -Path "$env:LOCALAPPDATA\Microsoft\WindowsApps\claude.exe" -Force
Clean configuration (removes all settings):
rm -rf ~/.claude
rm ~/.claude.json
rm -rf .claude
rm -f .mcp.json
Core Interaction Modes
Interactive REPL
Launch Claude Code without arguments to enter the interactive read-eval-print loop:
cd your-project
claude
The REPL maintains conversation context across turns. Type queries directly, receive responses, and continue until you exit with /exit or Ctrl+D.
Start with an initial prompt to focus the session:
claude "explain the authentication flow in this project"
Expert tip: The REPL persists state across compaction events. When context grows too large, Claude automatically summarizes older conversation while preserving key decisions and code snippets. You can trigger this manually with /compact or add custom instructions for what to preserve.
Non-Interactive Mode
Print mode (-p) executes a single query and exits:
# Direct query
claude -p "list all TODO comments in this project"
# Process piped input
cat error.log | claude -p "identify the root cause of these failures"
# Chain with other tools
claude -p "generate a README" > README.md
For structured output suitable for parsing in scripts:
claude -p "count lines by file type" --output-format json
The JSON output includes everything you need for automation:
{
"type": "result",
"subtype": "success",
"total_cost_usd": 0.0034,
"is_error": false,
"duration_ms": 2847,
"duration_api_ms": 1923,
"num_turns": 4,
"result": "Response text here...",
"session_id": "abc-123-def"
}
For real-time processing of streaming output:
claude -p "build the application" --output-format stream-json | while read line; do
echo "$line" | jq -r '.result // empty'
done
Session Management
Sessions persist conversation history for continuation. This is essential for complex multi-session work:
# Continue most recent session
claude -c
# Continue with additional prompt
claude -c -p "now add error handling"
# Resume specific session by ID
claude -r "abc123" "implement the remaining tests"
# Fork a session for parallel exploration
claude -r "base-session" --fork-session "try a different approach"
Create reproducible sessions with explicit IDs:
claude --session-id "feature-auth-$(date +%s)"
Expert tip: Use session IDs that encode context: feature-${branch}-${timestamp} or bug-JIRA-123. When you come back days later, the ID tells you what the session was about. View available sessions within the REPL using /resume.
Sessions are stored as JSONL transcripts. Agent execution gets assigned unique agentId values with transcripts stored as agent-{agentId}.jsonl. Resume preserves full context from previous conversations.
Named sessions (Dec 2025): Name and manage sessions more easily:
# Name current session
> /rename my-feature-work
# Resume by name or number
> /resume 1 # Resume first session
> /resume my-feature-work # Resume by name
claude --resume 3 # Resume from terminal
# Fork with custom session ID
claude --session-id "new-exploration" --resume "base-session" --fork-session
Configuration System Deep Dive
Claude Code uses a layered configuration system. Understanding the hierarchy is essential because higher levels override lower ones, and enterprise settings cannot be bypassed at all.
Configuration Hierarchy
| Level | Location | Scope | Can Override |
|---|---|---|---|
| Enterprise | /etc/claude-code/managed-settings.json (Linux) |
All users | No |
/Library/Application Support/ClaudeCode/managed-settings.json (macOS) |
|||
C:\Program Files\ClaudeCode\managed-settings.json (Windows) |
|||
| CLI flags | Command-line arguments | Current session | Yes |
| Local project | .claude/settings.local.json |
Personal, current project | Yes |
| Shared project | .claude/settings.json |
Team via git | Yes |
| User | ~/.claude/settings.json |
All your projects | Yes |
| State | ~/.claude.json |
Runtime state, OAuth, MCP | N/A |
Expert tip: Use .claude/settings.local.json for personal preferences in shared projects—it should be in .gitignore. Use .claude/settings.json for team-wide configuration that gets checked into version control.
Complete settings.json Reference
A comprehensive configuration demonstrating all major options:
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"model": "claude-sonnet-4-5-20250929",
"permissions": {
"allow": [
"Read",
"Glob",
"Grep",
"Bash(npm run:*)",
"Bash(git:*)",
"Bash(make:*)",
"Edit(src/**)",
"Write(src/**)",
"mcp__github"
],
"deny": [
"Read(.env*)",
"Read(secrets/**)",
"Bash(rm -rf:*)",
"Bash(sudo:*)",
"Edit(package-lock.json)",
"Edit(.git/**)"
],
"ask": [
"WebFetch",
"Bash(curl:*)",
"Bash(docker:*)"
],
"additionalDirectories": [
"../shared-lib",
"../docs"
],
"defaultMode": "acceptEdits"
},
"env": {
"NODE_ENV": "development",
"DEBUG": "app:*"
},
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npx prettier --write \"$FILE_PATH\""
}
]
}
]
},
"sandbox": {
"enabled": false,
"autoAllowBashIfSandboxed": true,
"excludedCommands": ["git", "docker"]
},
"statusLine": {
"type": "command",
"command": "~/.claude/statusline.sh"
},
"includeCoAuthoredBy": true,
"cleanupPeriodDays": 30,
"outputStyle": "Explanatory",
"language": "en",
"respectGitignore": true,
"showTurnDuration": true,
"plansDirectory": ".claude/plans",
"spinnerVerbs": ["Thinking", "Processing", "Analyzing"]
}
Environment Variables Reference
Authentication and API:
ANTHROPIC_API_KEY=sk-ant-... # Direct API authentication
ANTHROPIC_AUTH_TOKEN=token # Custom authorization header
ANTHROPIC_CUSTOM_HEADERS="X-Key: val" # Additional request headers
Model configuration:
ANTHROPIC_MODEL=claude-opus-4-5 # Override default model
ANTHROPIC_DEFAULT_OPUS_MODEL=claude-opus-4-5-20251101
ANTHROPIC_DEFAULT_SONNET_MODEL=claude-sonnet-4-5-20250929-v1:0
ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-haiku-4-5-20251001
CLAUDE_CODE_SUBAGENT_MODEL=sonnet # Model for subagents
MAX_THINKING_TOKENS=10000 # Enable extended thinking
CLAUDE_CODE_MAX_OUTPUT_TOKENS=4000 # Limit output length
Cloud provider configuration:
CLAUDE_CODE_USE_BEDROCK=1 # Use AWS Bedrock
CLAUDE_CODE_USE_VERTEX=1 # Use Google Vertex AI
CLAUDE_CODE_USE_FOUNDRY=1 # Use Microsoft Foundry
ANTHROPIC_BEDROCK_BASE_URL=https://... # Custom Bedrock endpoint
CLAUDE_CODE_SKIP_BEDROCK_AUTH=1 # Skip Bedrock auth (for gateways)
CLAUDE_CODE_SKIP_VERTEX_AUTH=1 # Skip Vertex auth
AWS_BEARER_TOKEN_BEDROCK=token # Bedrock bearer token
VERTEX_REGION_CLAUDE_3_7_SONNET=us-west1 # Override Vertex region
Behavior control:
DISABLE_AUTOUPDATER=1 # Prevent automatic updates
DISABLE_TELEMETRY=1 # Opt out of usage telemetry
DISABLE_ERROR_REPORTING=1 # Disable Sentry
DISABLE_BUG_COMMAND=1 # Disable /bug command
DISABLE_COST_WARNINGS=1 # Hide cost warnings
DISABLE_PROMPT_CACHING=1 # Disable prompt caching globally
DISABLE_PROMPT_CACHING_SONNET=1 # Disable for Sonnet only
DISABLE_PROMPT_CACHING_OPUS=1 # Disable for Opus only
DISABLE_NON_ESSENTIAL_MODEL_CALLS=1 # Skip non-critical API calls
Tool configuration:
BASH_DEFAULT_TIMEOUT_MS=30000 # Bash command timeout (30s)
BASH_MAX_TIMEOUT_MS=600000 # Maximum bash timeout (10min)
BASH_MAX_OUTPUT_LENGTH=50000 # Bash output limit
CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1 # Reset CWD after each bash
MCP_TIMEOUT=5000 # MCP server startup timeout
MCP_TOOL_TIMEOUT=30000 # MCP tool execution timeout
MAX_MCP_OUTPUT_TOKENS=25000 # MCP output limit
SLASH_COMMAND_TOOL_CHAR_BUDGET=15000 # Slash command context limit
Network and proxy:
HTTP_PROXY=http://proxy:8080 # HTTP proxy
HTTPS_PROXY=https://proxy:8080 # HTTPS proxy
NO_PROXY=localhost,example.com # Bypass proxy for domains
CLAUDE_CODE_CLIENT_CERT=/path/to/cert # mTLS certificate
CLAUDE_CODE_CLIENT_KEY=/path/to/key # mTLS private key
CLAUDE_CODE_CLIENT_KEY_PASSPHRASE=pass # mTLS passphrase
UI and terminal:
CLAUDE_CODE_DISABLE_TERMINAL_TITLE=1 # Don't update terminal title
CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL=1 # Skip IDE extension install
CLAUDE_CODE_SHELL=/bin/zsh # Override shell detection
USE_BUILTIN_RIPGREP=1 # Use included ripgrep (default)
CLAUDE_CONFIG_DIR=~/.myconfig # Custom config directory
IS_DEMO=1 # Hide sensitive UI elements[^37]
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1 # Disable background tasks and Ctrl+B[^46]
CLAUDE_CODE_TMPDIR=/path/to/tmp # Override temp directory[^50]
Debugging:
ANTHROPIC_LOG=debug # Enable API request logging
Which Model Should I Choose?
Choosing the right model for each task significantly impacts both cost and quality. Claude Code provides flexible model switching at multiple levels.
Available Models
| Alias | Model | Best For | Input/1M | Output/1M |
|---|---|---|---|---|
sonnet |
Claude Sonnet 4.5 | Daily coding, balanced performance | $3.00 | $15.00 |
opus |
Claude Opus 4.5 | Complex reasoning, architecture | $5.00 | $25.00 |
haiku |
Claude Haiku 4.5 | Simple tasks, fast operations | $1.00 | $5.00 |
default |
Account-dependent | General purpose | Varies | Varies |
sonnet[1m] |
Sonnet with 1M context | Large codebases | $6.00 | $22.50 |
opusplan |
Opus (plan) + Sonnet (execute) | Complex refactoring | Hybrid | Hybrid |
Why these price differences matter: A typical coding session consumes 50K-200K input tokens and 10K-50K output tokens. With Haiku, that’s $0.10-$0.45 per session. With Opus, the same session costs $0.50-$2.25—5x more. Reserve Opus for genuinely hard problems.1
When to Use Each Model
Haiku: Use for subagents doing exploration, simple file searches, quick questions. It’s 10-20x cheaper than Opus and responds faster. Perfect for background tasks where you don’t need deep reasoning.
Sonnet: The workhorse for daily development. Handles most coding tasks well: implementing features, fixing bugs, writing tests, code review. Use this as your default.
Opus: Reserve for genuinely complex reasoning: architectural decisions, tricky debugging, understanding complex systems, security analysis. The quality difference is real for hard problems, but so is the cost. Opus 4.5 achieves 80.9% on SWE-bench Verified while cutting token usage in half compared to predecessors.45 Note: Pro subscription users now have access to Opus 4.5 as part of their subscription.20
Opusplan: A hybrid mode that uses Opus for planning (where reasoning quality matters most) and Sonnet for execution (where speed matters). Excellent for complex refactoring where you want the best plan but don’t need Opus-level reasoning for each individual edit.
Switching Models
During session:
> /model opus
> /model sonnet
> /model haiku
At startup:
claude --model opus
Via environment:
export ANTHROPIC_MODEL=opus
In settings.json:
{
"model": "claude-sonnet-4-5-20250929"
}
For subagents specifically:
export CLAUDE_CODE_SUBAGENT_MODEL=haiku
Extended Context
For large codebases or long sessions, enable 1M token context:
claude --model sonnet[1m]
Or within a session:
> /model anthropic.claude-sonnet-4-5-20250929-v1:0[1m]
Extended context costs more per token. Use it when you actually need it, not as a default.
Checking Current Model
> /status
This shows current model, account info, applied settings, and other session state.
Decision Frameworks
Knowing features exists isn’t enough—you need to know when to use each. These decision trees transform knowledge into action.
Which Model Should I Use?
START → Is the task simple? (file search, quick question, formatting)
│
├── YES → Use Haiku
│ Cost: ~$0.03/task
│ Speed: Fastest
│
└── NO → Does it require deep reasoning?
(architecture, complex debugging, security analysis)
│
├── YES → Use Opus
│ Cost: ~$2.00/task
│ Quality: Highest
│
└── NO → Use Sonnet (default)
Cost: ~$0.75/task
Balance: Best overall
Rule of thumb: Start with Sonnet. Drop to Haiku for subagents. Escalate to Opus only when Sonnet’s answer feels shallow.
Command vs Skill vs Subagent?
Do you want explicit control over when it runs?
│
├── YES → Use Slash Command
│ Example: /deploy, /test, /security-review
│ You invoke it. You control timing.
│
└── NO → Should the expertise apply automatically based on context?
│
├── YES → Use Skill
│ Example: Security patterns, domain rules, code standards
│ Claude recognizes context and applies expertise.
│
└── NO → Does the work need isolated context?
│
├── YES → Use Subagent
│ Example: Deep exploration, parallel analysis
│ Prevents context bloat in main conversation.
│
└── NO → Just prompt directly
Not everything needs abstraction.
Hook vs Prompt?
Must the action ALWAYS happen, regardless of Claude's judgment?
│
├── YES → Use Hook (deterministic)
│ Examples:
│ - Format code after every edit
│ - Log all bash commands
│ - Block access to .env files
│ Claude cannot skip, forget, or decide otherwise.
│
└── NO → Use Prompt (probabilistic)
Examples:
- "Consider adding tests"
- "Think about edge cases"
- "Review for security if relevant"
Claude decides based on context.
When to Use Extended Thinking?
Is this a genuinely hard problem?
│
├── Architectural decision with many tradeoffs → YES, use thinking
├── Complex debugging with unclear root cause → YES, use thinking
├── Security analysis requiring careful reasoning → YES, use thinking
├── Understanding unfamiliar codebase → YES, use thinking
│
├── Routine bug fix → NO, skip thinking
├── Simple refactoring → NO, skip thinking
├── Code formatting → NO, skip thinking
└── Quick questions → NO, skip thinking
Toggle with Tab during session. Higher thinking budgets cost more—start with minimum and increase only if responses feel rushed.
How Does the Permission System Work?
Claude Code’s permission system provides fine-grained control over what operations can execute. Understanding it is essential for both security and workflow efficiency.
Permission Tiers
Read-only tools (auto-approved):
- Read - Read file contents
- Glob - Find files by pattern
- Grep - Search file contents
- WebSearch - Search the web
- LSP - Code intelligence (go-to-definition, find references, hover docs)25
LSP Tool capabilities (v2.0.74+): The LSP tool provides IDE-like code intelligence: - Go-to-definition: Jump to where a symbol is defined - Find references: List all usages of a symbol across the codebase - Hover docs: Get type information and documentation for any symbol - Works with TypeScript, Python, Go, Rust, and other languages with LSP support - Requires language server to be available (typically installed with your toolchain)
Modification tools (require approval):
- Edit - Modify existing files
- Write - Create new files
- Bash - Execute shell commands
- WebFetch - Fetch URL contents
- NotebookEdit - Modify Jupyter notebooks
The first time a modification tool runs, Claude Code prompts for approval. Approvals persist for the session unless explicitly configured otherwise.
Permission Modes
| Mode | Behavior | Use Case |
|---|---|---|
default |
Prompt on first use of each tool | Normal development |
acceptEdits |
Auto-approve file edits, prompt for bash | Trusted projects |
plan |
No execution or editing allowed | Analysis only |
bypassPermissions |
Skip all prompts | CI/CD automation |
YOLO Mode (v2.0.68+): For fully autonomous operation, use the --dangerously-skip-permissions flag. This says yes to everything—file edits, bash commands, all tool calls. The word “dangerous” is intentional. Use in sandboxed environments or when you fully trust the codebase.61
claude --dangerously-skip-permissions
Set mode via CLI:
claude --permission-mode acceptEdits
Toggle during session:
Shift+Tab # Cycles through modes
In settings.json:
{
"permissions": {
"defaultMode": "acceptEdits"
}
}
Permission Rules Syntax
Fine-grained rules control specific operations. Rules are evaluated in order: first match wins.
Bash command patterns:
{
"allow": [
"Bash(npm run build)",
"Bash(npm run test:*)",
"Bash(git commit:*)",
"Bash(make:*)"
],
"deny": [
"Bash(rm -rf:*)",
"Bash(sudo:*)",
"Bash(curl|wget:*)"
]
}
The asterisk provides prefix matching: Bash(npm run test:*) allows npm run test, npm run test:unit, and npm run test:integration.
Important limitation: Bash patterns match prefixes only, not regex. A pattern like Bash(curl http:*) won’t match curl -X GET http://... because the options come before the URL. For robust blocking, deny the command entirely: Bash(curl:*).
File operation patterns:
{
"allow": [
"Edit(src/**)",
"Write(src/**)",
"Read(docs/**)"
],
"deny": [
"Read(.env*)",
"Read(secrets/**)",
"Edit(.git/**)",
"Edit(node_modules/**)"
]
}
Path syntax:
- Relative paths: Edit(src/**) - relative to working directory
- Absolute from settings file: Edit(/build/**) - relative to settings file location
- True absolute: Edit(//tmp/**) - starts with //
- Home directory: Read(~/.zshrc)
MCP tool patterns:
{
"allow": [
"mcp__github",
"mcp__database__query",
"mcp__myserver__*"
],
"deny": [
"mcp__dangerous_server",
"mcp__untrusted__*"
]
}
Use wildcard syntax mcp__server__* to allow or deny all tools from a specific MCP server.39 This is useful for quickly enabling all tools from trusted servers or blocking entire servers from untrusted sources.
WebFetch patterns:
{
"allow": [
"WebFetch(domain:github.com)",
"WebFetch(domain:api.example.com)"
]
}
Additional Directories
Extend Claude’s access beyond the current project:
{
"permissions": {
"additionalDirectories": [
"../shared-lib",
"../docs",
"~/reference-projects/design-system"
]
}
}
This is essential for monorepos or when Claude needs to reference code in sibling directories.
Sandbox Mode
Enable filesystem and network isolation:
> /sandbox
Or configure in settings:
{
"sandbox": {
"enabled": true,
"autoAllowBashIfSandboxed": true,
"excludedCommands": ["git", "docker"],
"network": {
"allowUnixSockets": ["~/.ssh/agent-socket"],
"allowLocalBinding": true
}
}
}
When sandboxed:
- Filesystem access restricted to project directory
- Network access controlled
- Certain commands excluded from sandbox restrictions
- Bash commands auto-allowed if autoAllowBashIfSandboxed is true
Expert tip: Sandbox mode is excellent for running Claude on untrusted codebases. Enable it when exploring unfamiliar projects or when you want an extra layer of protection. Internal Anthropic testing found sandboxing reduces permission prompts by 84%.45
How Do Hooks Work?
Hooks execute deterministic shell commands at specific points in Claude Code’s workflow. Unlike prompting Claude to perform actions, hooks guarantee execution regardless of model behavior. They’re essential for enforcing team standards and automating repetitive tasks.
Why hooks instead of prompts: Telling Claude “always run Prettier after editing files” works sometimes. But Claude might forget, prioritize speed, or decide the change is “too small.” Hooks guarantee execution—every Edit or Write triggers your formatter, every time, no exceptions. For compliance, security, and team standards, deterministic beats probabilistic.7
Available Events
| Event | Timing | Can Block | Purpose |
|---|---|---|---|
PreToolUse |
Before tool executes | Yes | Validate, log, or block operations |
PostToolUse |
After tool completes | No | Format output, run linters, trigger builds |
UserPromptSubmit |
User sends prompt | Yes | Add context, validate input, inject data |
Notification |
Alert triggered | No | Custom notification handling |
Stop |
Claude finishes response | No | Cleanup, logging, metrics |
SubagentStart |
Subagent spawns | No | Log agent type, inject context via additionalContext |
SubagentStop |
Subagent completes | No | Task tracking, capture agent_transcript_path |
Setup |
Init/maintenance run | No | Environment setup via --init, --init-only, --maintenance |
SessionStart |
Session begins | Yes | Environment setup, validation |
SessionEnd |
Session closes | No | Cleanup, final logging |
PreCompact |
Before context compaction | No | Validation, logging |
PermissionRequest |
Permission dialog shown | Yes | Custom approval logic |
Hook Configuration
Define hooks in settings.json or a dedicated hooks.json:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npx prettier --write \"$FILE_PATH\""
}
]
}
],
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": ".claude/hooks/validate-bash.sh"
}
]
}
],
"UserPromptSubmit": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": ".claude/hooks/inject-context.sh"
}
]
}
]
}
}
Matchers
The matcher field determines which tools trigger a hook:
{"matcher": "*"} // Match all tools
{"matcher": "Bash"} // Match Bash only
{"matcher": "Edit|Write"} // Match Edit or Write
{"matcher": "mcp__github"} // Match MCP server tools
{"matcher": ""} // Match for events without tools (like UserPromptSubmit)
Hook Input/Output Protocol
Hooks receive JSON on stdin:
{
"tool_name": "Bash",
"tool_input": {
"command": "npm test",
"description": "Run test suite"
},
"session_id": "abc-123"
}
Exit codes control behavior:
- 0: Success—operation proceeds. Stdout shown in verbose mode (Ctrl+O). For UserPromptSubmit and SessionStart, stdout is added to context.
- 2: Blocking error—operation stops. Stderr becomes the error message fed back to Claude.
- 1, 3, etc.: Non-blocking error—operation continues. Stderr shown as warning in verbose mode.
For advanced control, hooks can output JSON:
{
"decision": "allow",
"message": "Command validated and modified",
"modifications": {
"tool_input": {
"command": "npm test -- --coverage"
}
}
}
PreToolUse hooks with ask permission (v2.1.0+): PreToolUse hooks can now return updatedInput when using the “ask” permission decision, enabling hooks to act as middleware while still requesting user consent.39
{
"decision": "ask",
"message": "Modified command requires approval",
"updatedInput": {
"command": "npm test -- --coverage --ci"
}
}
PreToolUse hooks with additionalContext (v2.1.9+): Hooks can inject context into the model by returning additionalContext. This is useful for providing dynamic information (API docs, database schemas, environment state) that the model should consider.51
{
"decision": "allow",
"additionalContext": "Note: This database has a 5-second query timeout. Complex joins may need optimization."
}
The additionalContext string is appended to the model’s context for that turn, making it available for reasoning without permanently modifying the conversation.
Practical Hook Examples
Auto-format TypeScript files after editing:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "bash -c '[[ \"$FILE_PATH\" == *.ts ]] && npx prettier --write \"$FILE_PATH\" || true'"
}
]
}
]
}
}
Log all bash commands:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.command' >> ~/.claude/bash-history.log"
}
]
}
]
}
}
Block access to sensitive files:
#!/bin/bash
# .claude/hooks/protect-files.sh
data=$(cat)
path=$(echo "$data" | jq -r '.tool_input.file_path // empty')
if [[ "$path" == *".env"* ]] || [[ "$path" == *"secrets/"* ]] || [[ "$path" == *".pem"* ]]; then
echo "Blocked: Cannot access sensitive file $path" >&2
exit 1
fi
exit 0
Run tests after code changes:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit",
"hooks": [
{
"type": "command",
"command": "bash -c '[[ \"$FILE_PATH\" == *.test.ts ]] || npm run test:affected'"
}
]
}
]
}
}
Custom notification system:
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "notify-send 'Claude Code' 'Waiting for your input'"
}
]
}
]
}
}
Inject dynamic context into prompts:
#!/bin/bash
# .claude/hooks/inject-context.sh
# Add current git branch and recent commits to every prompt
branch=$(git branch --show-current 2>/dev/null)
commits=$(git log --oneline -3 2>/dev/null | tr '\n' ' ')
if [ -n "$branch" ]; then
echo "[Context: Branch '$branch', Recent: $commits]"
fi
exit 0
Hook Debugging
Enable debug mode to troubleshoot hooks:
claude --debug
This logs: - Hook execution times - Input/output data - Error messages and stack traces - Decision results (allow/reject/ask)
Component-Scoped Hooks (v2.1.0+)
Hooks can be defined directly in Skills, subagents, and slash commands using frontmatter. These hooks are scoped to the component’s lifecycle and only run when that component is active.41
Skill with embedded hooks:
---
name: secure-deployment
description: Deployment skill with security validation
hooks:
PreToolUse:
- matcher: Bash
command: ".claude/hooks/validate-deploy.sh"
PostToolUse:
- matcher: Bash
command: ".claude/hooks/log-deploy.sh"
Stop:
- command: ".claude/hooks/cleanup.sh"
once: true # Run only once per session
---
Supported events: PreToolUse, PostToolUse, Stop
The once option (skills and slash commands only) ensures the hook runs only once per session—useful for cleanup or finalization tasks.
Long-Running Sessions Strategy
For overnight or unattended Claude Code sessions, configure hooks to keep Claude on track without manual intervention. The key insight: use linting and testing hooks as guardrails that force Claude to fix issues before continuing.64
The “Don’t Stop Until Tests Pass” Pattern:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit",
"hooks": [
{
"type": "command",
"command": "npm run lint && npm run typecheck",
"timeout": 60000
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "npm test || echo 'Tests failing - Claude should fix before stopping'"
}
]
}
]
}
}
Strategy for overnight sessions:
- Pre-flight check: Use a Setup hook to verify environment is ready
- Continuous validation: PostToolUse hooks run tests after each change
- Gate completion: Stop hooks verify all acceptance criteria before Claude declares “done”
- Notification: Stop hooks can notify you via Slack/Pushover when Claude finishes or gets stuck
Combine with --dangerously-skip-permissions in a sandboxed container for fully autonomous overnight runs. Claude will keep iterating until tests pass or it exhausts its options.
What Is MCP (Model Context Protocol)?
MCP extends Claude Code with access to external tools, databases, APIs, and services through a standardized protocol. The ecosystem has exploded: MCP now has 100 million monthly downloads and 3,000+ servers indexed on MCP.so (January 2026), cementing its position as the industry standard for connecting AI to tools and data.354 Understanding MCP is essential for integrating Claude into your existing toolchain.
Why MCP matters for developers: Without MCP, Claude Code can only read files and run bash commands. With MCP, Claude can query your production database, create Jira tickets, review GitHub PRs, check Sentry errors, and interact with any API your team uses—all from natural language requests. The protocol standardizes how AI tools connect to external services, preventing vendor lock-in.
Remote MCP Support (June 2025)
Claude Code now supports remote MCP servers with native OAuth authentication.28 Connect to tools and data sources without managing local servers—just authenticate once and Claude Code handles token refresh automatically.
# Connect to remote MCP server with OAuth
claude mcp add --transport http linear https://mcp.linear.app/sse
# Browser opens for OAuth flow, tokens stored securely
MCP Tool Search (v2.1.7+)
As MCP servers grew in capability (some exposing 50+ tools), tool descriptions began consuming excessive context. MCP Tool Search solves this by dynamically loading tool descriptions only when needed—a form of lazy loading for AI tools.54
Performance impact: Internal benchmarks show dramatic accuracy improvements: - Opus 4: 49% → 74% on MCP evaluations - Opus 4.5: 79.5% → 88.1% on MCP evaluations - Token overhead reduction: 85%
How it works: When MCP tool descriptions exceed 10% of context window (default threshold), Claude Code defers loading full descriptions until they’re actually needed. Claude sees tool names but fetches descriptions on-demand.
Configuration:
{
"mcpToolSearchAutoEnable": "auto:15" // Enable when tools exceed 15% of context
}
Values:
- true - Always enable tool search
- false - Always disable (load all tool descriptions upfront)
- auto:N - Enable when tools exceed N% of context (0-100)
Expert tip: With Tool Search enabled, you can connect to many more MCP servers without worrying about context limits. The 95% context reduction means servers that previously competed for context now coexist peacefully.
Interactive MCP Setup Wizard
Run claude mcp add without arguments to launch a step-by-step interface for adding MCP servers. The wizard walks through transport type selection, authentication, and configuration.15
Transport Types
HTTP (recommended for remote servers):
claude mcp add --transport http github https://api.githubcopilot.com/mcp/
# With authentication
claude mcp add --transport http api https://api.example.com/mcp \
--header "Authorization: Bearer $API_TOKEN"
SSE (deprecated but functional):
claude mcp add --transport sse asana https://mcp.asana.com/sse \
--header "X-API-Key: your-key"
Stdio (local servers):
# PostgreSQL
claude mcp add --transport stdio postgres \
--env "DATABASE_URL=postgresql://user:pass@localhost/db" \
-- npx -y @anthropic-ai/mcp-server-postgres
# Custom server
claude mcp add --transport stdio custom -- python /path/to/server.py --port 8000
Windows requires a cmd wrapper for stdio:
claude mcp add --transport stdio my-server -- cmd /c npx -y @some/package
Scope Management
MCP servers exist at three scopes with clear precedence (local overrides project overrides user):
| Scope | Storage | Visibility | Use Case |
|---|---|---|---|
| Local | ~/.claude.json (project path) |
Just you, this project | Personal API keys |
| Project | .mcp.json |
Entire team via git | Shared integrations |
| User | ~/.claude.json (root) |
You, all projects | Personal tools |
Specify scope during installation:
claude mcp add --scope project --transport http github https://...
claude mcp add --scope user --transport stdio personal-tool -- ./my-tool
Configuration File Format
The .mcp.json file defines project-level servers:
{
"mcpServers": {
"github": {
"type": "http",
"url": "https://api.githubcopilot.com/mcp/"
},
"database": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@anthropic-ai/mcp-server-postgres"],
"env": {
"DATABASE_URL": "${DATABASE_URL}"
}
},
"sentry": {
"type": "http",
"url": "https://mcp.sentry.dev/mcp",
"headers": {
"Authorization": "Bearer ${SENTRY_API_KEY}"
}
},
"internal-api": {
"type": "http",
"url": "${API_BASE_URL:-https://api.example.com}/mcp",
"headers": {
"X-API-Key": "${INTERNAL_API_KEY}"
}
}
}
}
Environment variables expand using ${VAR} syntax with optional defaults: ${VAR:-default}.
MCP Management Commands
claude mcp list # View all configured servers
claude mcp get github # Get specific server details
claude mcp remove github # Remove a server
claude mcp reset-project-choices # Reset project-scoped approvals
claude mcp add-from-claude-desktop # Import from Claude Desktop
claude mcp add-json weather '{"type":"http","url":"..."}' # Add from JSON
# Within Claude Code REPL
> /mcp # Interactive MCP management
OAuth Authentication
For servers requiring OAuth:
> /mcp
# Follow browser-based OAuth flow
# Tokens stored securely and auto-refreshed
# Use "Clear authentication" to revoke access
Using MCP Resources and Prompts
Reference resources:
@github:issue://123
@postgres:schema://users
@docs:file://api/authentication
MCP prompts as slash commands:
/mcp__github__list_prs
/mcp__github__pr_review 456
/mcp__jira__create_issue "Bug title" high
Output Limits
MCP output is limited to prevent context overflow: - Warning threshold: 10,000 tokens - Default maximum: 25,000 tokens
Increase if needed:
export MAX_MCP_OUTPUT_TOKENS=50000
Popular MCP Servers
| Server | Purpose | Key Capabilities |
|---|---|---|
| GitHub | Repository management | PRs, issues, CI/CD, code review |
| PostgreSQL | Database access | Query, schema inspection, data analysis |
| Sentry | Error monitoring | Error lookup, stack traces, deployment correlation |
| Linear | Project management | Issues, projects, sprints |
| Jira/Atlassian | Enterprise PM | Tickets, boards, workflows |
| Playwright | Web automation | E2E testing, accessibility trees |
| Stripe | Payments | Transaction lookup, customer data |
| Cloudflare | Infrastructure | DNS, workers, analytics |
| Supabase | Backend-as-service | Database, auth, storage |
| Context7 | Documentation | Real-time, version-specific library docs |
| Figma Dev Mode | Design-to-code | Layer hierarchy, auto-layout, tokens42 |
| Sequential Thinking | Problem solving | Structured reasoning, reflective process43 |
| Magic UI | Components | React + Tailwind marketing components |
Practical MCP Patterns
GitHub workflow:
> Review PR #456
> List all open issues assigned to me
> Create a bug issue for the authentication failure we found
Database queries:
> What's our total revenue this quarter?
> Show the schema for the users table
> Find customers with no purchases in 90 days
Error monitoring:
> What errors occurred in production today?
> Show the stack trace for error ABC123
> Which deployment introduced these errors?
Enterprise MCP Configuration
System administrators can enforce MCP policies via managed-mcp.json:
{
"allowedMcpServers": [
{ "serverName": "github" },
{ "serverName": "sentry" },
{ "serverCommand": ["npx", "-y", "@approved/server"] }
],
"deniedMcpServers": [
{ "serverName": "dangerous-server" }
]
}
Location:
- macOS: /Library/Application Support/ClaudeCode/managed-mcp.json
- Linux: /etc/claude-code/managed-mcp.json
- Windows: C:\ProgramData\ClaudeCode\managed-mcp.json
Denylist takes absolute precedence. Commands must match exactly including argument order.
MCP Apps (January 2026)
Anthropic launched MCP Apps, an extension to the Model Context Protocol that enables interactive tool UIs directly inside the Claude interface.78 MCP Apps let users view, edit, and interact with content from external services without leaving Claude—including Asana, Box, Canva, Figma, Hex, monday.com, and Slack. Any MCP server can supply an interactive UI that renders inside Claude. While MCP Apps currently appear in the claude.ai web interface, the underlying MCP protocol extensions are relevant to Claude Code’s MCP ecosystem as servers adopt the new interactive capabilities.
API Platform: Code Execution Tool v2 (January 2026)
Anthropic launched v2 of the Code Execution Tool in public beta, replacing the original Python-only sandbox with Bash command execution and direct file manipulation.79 Key changes: - Execute Bash commands (not just Python) in sandboxed containers - Write and run code in any language - Programmatic tool calling (also public beta): Claude can call tools from within code execution, reducing latency and token usage in multi-tool workflows
This primarily affects API users but signals the direction for Claude Code’s cloud execution capabilities.
What Are Subagents?
Subagents are specialized Claude instances that handle complex tasks independently. They’re one of the most powerful features in Claude Code and one of the least understood. Mastering subagents dramatically expands what you can accomplish.
Why subagents exist: Claude Code’s main conversation has a single context window. Everything you discuss, every file Claude reads, every tool output—all consume that context. In long sessions, context fills up, Claude loses track of earlier decisions, and performance degrades. Subagents solve this by isolating work: exploration results don’t bloat your main conversation, only the summary returns. Claude can also run up to 10 subagents in parallel, enabling concurrent work that would be impossible sequentially.2
How Subagents Work
When Claude encounters a task that benefits from focused attention—deep exploration, multi-step analysis, specialized work—it can spawn a subagent. The subagent:
- Starts with a clean context (no pollution from main conversation)
- Has access to specified tools
- Operates with a specific model (often cheaper/faster)
- Returns results to the main conversation
This architecture prevents context overflow while enabling complex workflows.
Built-In Subagent Types
Explore (fast, read-only):
- Model: Haiku (ultra-fast)
- Mode: Strictly read-only
- Tools: Glob, Grep, Read, and safe bash commands (ls, git status, git log, git diff, find, cat, head, tail)
- Thoroughness levels: Quick, Medium, Very thorough
- Use for: Codebase exploration, finding files, understanding structure
General-purpose: - Model: Sonnet - Mode: Full read/write - Tools: All available tools - Use for: Complex research + modification tasks
Plan:
- Model: Sonnet (or Opus with opusplan)
- Mode: Read-only
- Tools: Read, Glob, Grep, Bash
- Use for: Planning complex implementations before execution
Triggering Subagents
Claude automatically delegates to subagents based on task type. You can also explicitly request them:
> Use the explore agent to find all authentication-related files
> Have a subagent analyze the database schema thoroughly
> Spawn an agent to research how error handling works in this codebase
Expert tip: For complex tasks, explicitly request subagent delegation. “Use an explore agent to find…” prevents context bloat in your main conversation.
Creating Custom Subagents
Define subagents in .claude/agents/ (project) or ~/.claude/agents/ (personal):
---
name: security-reviewer
description: Expert security code reviewer. Use PROACTIVELY after any code changes to authentication, authorization, or data handling.
tools: Read, Grep, Glob, Bash
model: opus
permissionMode: plan
---
You are a senior security engineer reviewing code for vulnerabilities.
When invoked:
1. Identify the files that were recently changed
2. Analyze for OWASP Top 10 vulnerabilities
3. Check for secrets, hardcoded credentials, SQL injection
4. Report findings with severity levels and remediation steps
Focus on actionable security findings, not style issues.
Configuration fields:
| Field | Required | Options | Purpose |
|---|---|---|---|
name |
Yes | Lowercase + hyphens | Unique identifier |
description |
Yes | Natural language | When to invoke (include “PROACTIVELY” to encourage auto-delegation) |
tools |
No | Comma-separated | Inherits all tools if omitted |
model |
No | sonnet, opus, haiku, inherit |
Defaults to sonnet |
permissionMode |
No | default, acceptEdits, bypassPermissions, plan, ignore |
Permission handling |
skills |
No | Comma-separated | Auto-load skills when subagent starts |
Managing Subagents
> /agents # Interactive management
> /agents create # Create new subagent
> /agents edit # Modify existing
> /agents delete # Remove subagent
> /agents list # View all
Running Agents in Background
For long-running tasks:
> Run a thorough security review in the background
> /agents # Check status of running agents
Retrieve results later with the agent ID.
Advanced Patterns
Chained subagents:
> First use the code-analyzer subagent to find performance issues, then use the optimizer subagent to fix them
Parallel exploration:
> Have three explore agents search in parallel:
> 1. Authentication code
> 2. Database models
> 3. API routes
Resumable agents: Agents can be resumed with their ID to continue previous work:
> Resume agent abc123 and continue the analysis
Async Subagents (December 2025)
Asynchronous subagents enable multitasking and parallel execution for large-scale projects:
> Run security review in the background while I continue frontend work
> /tasks # Check status of running agents
Async agents return results via the unified TaskOutputTool, enabling efficient pipeline-style workflows.
Permission Denial Resilience (v2.1.0+)
Starting in v2.1.0, subagents continue working after permission denials instead of stopping entirely. When a subagent hits a permissions wall, it tries alternative approaches automatically. This makes autonomous workflows more resilient and reduces the need for human intervention.47
Agent Skills (December 2025)
Agent Skills are organized folders of instructions, scripts, and resources that agents discover and load dynamically.31 They provide composable, portable domain expertise:
.claude/skills/
├── security-review/
│ ├── skill.md # Instructions and prompts
│ ├── checklist.md # Security checklist
│ └── common-vulns.sh # Detection scripts
└── performance-audit/
├── skill.md
└── profiling-guide.md
Skills differ from commands: commands are explicitly invoked, while skills auto-activate based on task context. The Claude Agent SDK (renamed from Claude Code SDK) provides the harness for building custom agents with skill support.32
What Is Extended Thinking Mode?
Extended thinking gives Claude more time to reason through complex problems before responding. It’s particularly valuable for architectural decisions, debugging tricky issues, and tasks requiring careful analysis.
Current State (January 2026)
Extended thinking is now enabled by default with a budget of 31,999 tokens—the maximum budget that was previously triggered by “ultrathink.”70 This change was made because extended thinking significantly improves performance on complex planning and reasoning tasks.
Important: Natural language triggers like “think”, “think hard”, “think harder”, and “ultrathink” no longer work. These keywords are now interpreted as regular prompt instructions and don’t allocate thinking tokens. The thinking budget is controlled exclusively by the
MAX_THINKING_TOKENSenvironment variable or via/config.70
Supported Models
- Claude Opus 4.5
- Claude Sonnet 4.5
- Claude Haiku 4.5
Controlling Extended Thinking
Quick toggle during session:
Press Alt+T to toggle thinking on/off
Note: The thinking toggle was changed from Tab to Alt+T to avoid accidental triggers.39
Via /config:
Navigate to /config → Extended Thinking to enable/disable or adjust budget.
Environment variable (permanent):
# Set custom budget (default is 31,999)
export MAX_THINKING_TOKENS=8000
claude
# Double the default for complex tasks
export MAX_THINKING_TOKENS=63999
claude
Disable for cost savings:
For simpler tasks where deep reasoning isn’t needed, you can reduce costs by disabling thinking in /config or lowering the budget:
export MAX_THINKING_TOKENS=8000 # Reduce from default 31,999
Thinking Token Budgets
| Budget | Use Case |
|---|---|
| 1,024 (minimum) | Simple reasoning tasks |
| 8,000 | Most coding tasks (cost-efficient) |
| 31,999 (default) | Complex reasoning, architecture decisions |
| 63,999 (2× default) | Exhaustive analysis (requires explicit setting) |
Cost consideration: Thinking tokens are billed as output tokens. The default 31,999 budget works well for most tasks, but for simple operations you can save costs by reducing the budget or disabling thinking entirely.
How It Works
When thinking is enabled, Claude’s response includes internal reasoning that’s not shown in the output but influences the answer. The thinking is encrypted and returned in a signature field for verification.
In multi-turn conversations with tool use, thinking blocks must be passed back to the API to preserve reasoning continuity. Claude Code handles this automatically.
When to Consider Disabling/Reducing
Extended thinking is now the default, but consider reducing the budget or disabling for: - Simple file edits - Routine refactoring - Quick questions - Code formatting - High-volume operations where costs add up
Cache Behavior
System prompt caching is preserved when thinking parameters change. Message caching is invalidated when thinking budget or enabled status changes between turns.
Output Styles
Output styles customize how Claude presents information—useful for learning, documentation, or specific team preferences.19
Built-In Styles
| Style | Purpose |
|---|---|
Explanatory |
Detailed explanations with reasoning |
Learning |
Educational format with concepts explained |
Concise |
Minimal output, just essentials |
Setting Output Style
> /output-style Explanatory
> /output-style Learning
Or via settings:
{
"outputStyle": "Explanatory"
}
Custom Output Styles
Create in .claude/styles/:
# my-style
## Instructions
- Always explain the WHY behind each decision
- Include relevant documentation links
- Format code examples with comments
- End with a "What to do next" section
## Format
Use markdown headers for organization.
Keep explanations under 200 words per section.
Invoke with /output-style my-style.
Slash Commands
Slash commands provide quick access to Claude Code features and enable custom workflows. They’re faster than typing out full prompts for common operations.
Built-In Command Reference
| Command | Purpose | Notes |
|---|---|---|
/init |
Initialize project with CLAUDE.md | Creates memory file with project structure |
/memory |
Edit memory files | Opens CLAUDE.md editor |
/context |
View context window usage | Shows visual breakdown |
/compact |
Condense conversation history | Add focus: /compact focus on tests |
/cost |
Display token usage and cost | Session breakdown |
/usage |
Display current plan usage | VSCode only (v2.1.14+) |
/stats |
Usage statistics | Favorite model, usage graph, streak |
/permissions |
Manage permission settings | Interactive interface |
/mcp |
Configure MCP servers | Also /mcp enable, /mcp disable |
/hooks |
View hook configuration | Debug hooks |
/config |
Open settings interface | Full configuration |
/resume |
Resume named session | /resume <n> or /resume session-name |
/rename |
Name current session | /rename feature-auth |
/fork |
Branch conversation | Explore alternatives without losing context |
/clear |
Clear conversation history | Fresh start |
/vim |
Enable vim editing mode | Modal editing |
/ide |
Connect to IDE | VS Code/JetBrains integration |
/sandbox |
Enable sandbox mode | Isolation |
/status |
View session status | Model, settings, etc. |
/statusline |
Customize status line | Configure display |
/model |
Change AI model | /model opus |
/output-style |
Set output style | Explanatory, Learning, custom |
/agents |
Manage subagents | Create, edit, delete |
/bashes |
List background tasks | Long-running commands |
/tasks |
List background agents | Monitor async tasks |
/export |
Export conversation | Save transcript |
/add-dir |
Add working directories | Expand access |
/terminal-setup |
Configure terminal | Kitty, Alacritty, Zed, Warp support25 |
/doctor |
Check installation | Health check |
/bug |
Report bugs | File issue with Anthropic |
/release-notes |
View release notes | Check what’s new |
/rewind |
Return to checkpoint | Undo changes (or Esc×2) |
/theme |
Manage themes | Ctrl+T toggles syntax highlighting |
/plugin |
Manage plugins | Install, update, remove plugins |
/passes |
Guest passes (Max only) | Share 3 Claude Code Pro trial passes62 |
Custom Command Creation
Create reusable commands in .claude/commands/ (project) or ~/.claude/commands/ (personal):
---
description: Security-focused code review
allowed-tools: Read, Grep, Glob
model: claude-sonnet-4-5
---
Review this code for security vulnerabilities:
1. Injection attacks (SQL, command, XSS)
2. Authentication and authorization flaws
3. Sensitive data exposure
4. Insecure dependencies
Focus on actionable findings with specific line references.
Save as .claude/commands/security-review.md, invoke with /security-review.
Command Frontmatter Options
---
description: Brief description for /help
allowed-tools: Read, Edit, Bash(npm:*)
model: opus
argument-hint: [arg1] [arg2]
disable-model-invocation: false
---
| Option | Purpose |
|---|---|
description |
Help text and auto-delegation matching |
allowed-tools |
Restrict available tools |
model |
Override model for this command |
argument-hint |
Document expected arguments |
disable-model-invocation |
Prevent SlashCommand tool usage |
Argument Interpolation
All arguments as single string:
---
description: Fix GitHub issue
argument-hint: [issue-number]
---
Fix GitHub issue #$ARGUMENTS following our coding standards.
Usage: /fix-issue 123
Numbered arguments:
---
description: Create component
argument-hint: [name] [type]
---
Create a new $2 component named $1 in src/components/.
Usage: /create-component Button functional
Inline Bash Execution
Execute bash commands within command prompts:
---
description: Git status summary
allowed-tools: Bash(git:*)
---
Current branch: !`git branch --show-current`
Recent commits: !`git log --oneline -5`
Changed files: !`git status --short`
Summarize the current state of this repository.
File References
Include file contents in commands:
---
description: Compare implementations
---
Compare these files:
@src/v1/handler.ts
@src/v2/handler.ts
Which implementation is more maintainable?
Command Namespacing
Organize commands in subdirectories:
.claude/commands/
├── backend/
│ ├── test.md
│ └── deploy.md
├── frontend/
│ ├── test.md
│ └── build.md
└── review.md
Commands with the same name show their namespace in help: /test (project:backend) vs /test (project:frontend).
How Do Skills Work?
Skills represent a fundamentally different approach to extending Claude Code. Unlike slash commands that you invoke explicitly, skills are model-invoked—Claude automatically discovers and uses them based on context. You embed domain expertise into a skill, and Claude draws on that expertise whenever the situation calls for it, without you needing to remember to ask.
Why skills change everything: Consider domain expertise—the payment processing rules, the compliance requirements, the architectural patterns your team has refined over years. Without skills, you either re-explain this context every session or hope Claude infers it from code comments. With skills, you encode it once. Claude reads the skill definition and applies that expertise automatically whenever relevant. Your junior developers get senior-level guidance without asking. Your security patterns get enforced without remembering to invoke them.
This distinction matters. A slash command is a shortcut you remember to use. A skill is knowledge Claude always has available. When you create a security review skill with your team’s specific vulnerability patterns and compliance requirements, Claude applies that expertise whenever it encounters relevant code—during PR reviews, refactoring, or any task where security matters. You don’t invoke /security-review; Claude recognizes the context and applies the skill automatically.
Skills vs Commands vs Subagents
Understanding when to use each extension mechanism prevents duplication and maximizes effectiveness:
| Aspect | Slash Commands | Skills | Subagents |
|---|---|---|---|
| Invocation | User-invoked (/command) |
Model-invoked (automatic) | Explicit or auto-delegated |
| Trigger | You remember to use it | Claude recognizes context | Task requires delegation |
| Structure | Single markdown file | Directory with resources | Markdown with frontmatter |
| Context | Main conversation | Main conversation | Separate context window |
| Complexity | Simple prompts | Multi-file capabilities | Full agent personality |
| Best for | Explicit actions | Domain expertise | Complex task delegation |
Use slash commands when you want explicit control: /deploy, /test, /review PR 456. You decide when to run them.
Use skills when expertise should be automatically available: security patterns, code style enforcement, domain-specific knowledge. Claude decides when to apply them.
Use subagents when tasks need isolation: background exploration, parallel analysis, specialized reasoning that shouldn’t pollute your main conversation.
Skill Structure and Location
Skills live in dedicated directories containing a required SKILL.md file plus optional supporting resources:
Personal skills (available across all your projects):
~/.claude/skills/
├── code-reviewer/
│ ├── SKILL.md
│ ├── SECURITY_PATTERNS.md
│ └── PERFORMANCE_CHECKLIST.md
├── sql-analyst/
│ ├── SKILL.md
│ └── QUERY_PATTERNS.md
└── api-designer/
└── SKILL.md
Project skills (shared with team via git):
.claude/skills/
├── domain-expert/
│ ├── SKILL.md
│ ├── BUSINESS_RULES.md
│ └── DATA_MODELS.md
└── deployment/
├── SKILL.md
└── RUNBOOKS.md
Project skills commit to version control. When teammates pull, they get your skills automatically—no installation, no configuration. This is how you standardize expertise across a team.
SKILL.md Format
Every skill requires a SKILL.md file with YAML frontmatter:
---
name: code-reviewer
description: Review code for security vulnerabilities, performance issues, and best practice violations. Use when examining code changes, reviewing PRs, analyzing code quality, or when asked to review or audit code.
allowed-tools: Read, Grep, Glob
---
# Code Review Expertise
## Security Analysis
When reviewing code, check for:
### Input Validation
- All user input sanitized before use
- Parameterized queries for database operations
- Output encoding for rendered content
### Authentication & Authorization
- Session tokens properly validated
- Permission checks before sensitive operations
- No hardcoded credentials or API keys
### Data Exposure
- Sensitive data not logged
- PII properly masked in error messages
- API responses don't leak internal details
## Performance Patterns
### Database
- N+1 query detection
- Missing indexes on filtered columns
- Unbounded result sets
### Memory
- Large object lifecycle management
- Stream processing for big files
- Connection pool exhaustion risks
## Review Output Format
For each finding:
- **File**: path/to/file.ts:123
- **Severity**: Critical | High | Medium | Low
- **Category**: Security | Performance | Maintainability
- **Issue**: Clear description of the problem
- **Recommendation**: Specific fix with code example
- **Rationale**: Why this matters
See [SECURITY_PATTERNS.md](SECURITY_PATTERNS.md) for detailed vulnerability patterns.
See [PERFORMANCE_CHECKLIST.md](PERFORMANCE_CHECKLIST.md) for optimization guidelines.
Frontmatter Reference
| Field | Required | Constraints | Purpose |
|---|---|---|---|
name |
Yes | Lowercase, numbers, hyphens; max 64 chars | Unique identifier |
description |
Yes | Max 1024 chars | Discovery trigger—Claude uses this to decide when to apply the skill |
allowed-tools |
No | Comma-separated tool names | Restrict Claude’s capabilities when using this skill |
context |
No | fork |
Run skill in isolated context (v2.1.0+). Prevents side effects on main agent state.47 |
String Substitutions (v2.1.9+): Skills can access session context using ${CLAUDE_SESSION_ID} substitution. Useful for logging, tracking, or generating session-specific outputs.51
The description field is critical. Claude discovers skills by matching your requests against skill descriptions. A vague description means Claude won’t recognize when to use the skill. A specific description with clear trigger conditions means reliable activation.
Poor description:
description: Helps with code
Effective description:
description: Review code for security vulnerabilities, performance issues, and best practice violations. Use when examining code changes, reviewing PRs, analyzing code quality, or when asked to review, audit, or check code.
The effective description includes: - What the skill does (review code for specific issues) - When to use it (examining changes, PRs, quality analysis) - Trigger phrases (review, audit, check)
Tool Restrictions
The allowed-tools field limits what Claude can do when a skill is active. This is essential for skills that should be read-only or limited in scope:
---
name: security-auditor
description: Audit code for security vulnerabilities without making changes
allowed-tools: Read, Grep, Glob
---
With this configuration, Claude can analyze code but cannot edit files, run bash commands, or make modifications. The skill enforces read-only behavior.
Common restriction patterns:
| Pattern | Tools | Use Case |
|---|---|---|
| Read-only analysis | Read, Grep, Glob |
Security audits, code review |
| Safe exploration | Read, Grep, Glob, Bash(git log:*), Bash(git diff:*) |
Historical analysis |
| Documentation | Read, Grep, Glob, Write |
Generate docs without editing source |
| Full access | (omit field) | Skill inherits all available tools |
Supporting Files
Skills can include multiple files. Claude reads the main SKILL.md on activation, then accesses supporting files as needed—progressive disclosure that manages context efficiently.
Structure pattern:
my-skill/
├── SKILL.md # Required: overview + quick reference
├── DETAILED_GUIDE.md # Deep documentation
├── EXAMPLES.md # Concrete examples
├── PATTERNS.md # Reference patterns
├── templates/ # Reusable templates
│ └── component.tsx
└── scripts/ # Helper utilities
└── validate.py
Reference supporting files from SKILL.md:
For detailed security patterns, see [SECURITY_PATTERNS.md](SECURITY_PATTERNS.md).
Use this template for new components:
@templates/component.tsx
Validate configurations with:
```bash
python scripts/validate.py config.json
**Expert tip:** Put essential information in SKILL.md directly. Reserve supporting files for deep reference material. Claude reads SKILL.md immediately but only accesses supporting files when needed. If critical information is buried in a supporting file, Claude might not find it.
### Complete Example: Domain Expert Skill
Here's a production-quality skill for a fintech application:
**Directory structure:**
.claude/skills/payments-domain/ ├── SKILL.md ├── BUSINESS_RULES.md ├── COMPLIANCE.md └── DATA_MODELS.md
**SKILL.md:**
```markdown
---
name: payments-domain
description: Expert knowledge of payment processing domain including transaction flows, compliance requirements, and business rules. Use when working with payment code, transaction handling, refunds, disputes, or financial calculations.
---
# Payments Domain Expertise
## Core Concepts
### Transaction States
PENDING → AUTHORIZED → CAPTURED → SETTLED ↘ VOIDED AUTHORIZED → DECLINED CAPTURED → REFUNDED (partial or full) SETTLED → CHARGEBACK → REPRESENTED
### Money Handling Rules
- ALL monetary values stored as integers (cents, not dollars)
- Currency always explicitly tracked (never assume USD)
- Rounding: HALF_EVEN for calculations, HALF_UP for display
- Never use floating point for money
### Idempotency Requirements
Every payment operation MUST be idempotent:
```typescript
// Required pattern
async function processPayment(idempotencyKey: string, amount: number) {
const existing = await findByIdempotencyKey(idempotencyKey);
if (existing) return existing; // Return cached result
const result = await executePayment(amount);
await storeWithIdempotencyKey(idempotencyKey, result);
return result;
}
Quick Reference
Fee Calculations
- Interchange: 1.5% + $0.10 (debit), 2.1% + $0.10 (credit)
- Platform fee: 2.9% + $0.30 (standard), 2.2% + $0.30 (enterprise)
- International: +1% cross-border fee
- Currency conversion: mid-market rate + 1%
Compliance Thresholds
- $3,000: Enhanced due diligence trigger
- $10,000: CTR filing required
- $25,000: Additional verification required
Refund Windows
- Full refund: 120 days from capture
- Partial refund: 180 days from capture
- Chargeback window: 120 days (Visa), 180 days (Mastercard)
Key Files
src/payments/processor.ts- Core payment logicsrc/payments/refunds.ts- Refund handlingsrc/compliance/aml.ts- AML checkssrc/models/transaction.ts- Transaction model
See BUSINESS_RULES.md for detailed business logic. See COMPLIANCE.md for regulatory requirements. See DATA_MODELS.md for schema documentation.
With this skill in place, Claude automatically applies payments domain expertise when you work on transaction code, ask about refund logic, or debug payment flows. You don't invoke anything—the expertise is just there.
### Creating Effective Skills
**Start with the description.** Write the description first, then build the skill content to match. The description determines when Claude uses the skill, so get it right:
1. State what the skill provides
2. List specific trigger conditions
3. Include relevant keywords and phrases
**Keep skills focused.** One skill should cover one domain or capability:
| Good (focused) | Bad (too broad) |
|----------------|-----------------|
| `security-auditor` | `code-helper` |
| `react-patterns` | `frontend-stuff` |
| `postgres-optimization` | `database-expert` |
| `api-documentation` | `docs-generator` |
If a skill tries to cover too much, its description becomes vague, and Claude won't reliably recognize when to use it.
**Use progressive disclosure.** Put the most important information in SKILL.md directly. Reference supporting files for depth:
```markdown
## Quick Reference
[Essential patterns here - Claude sees this immediately]
## Deep Dive
For comprehensive coverage, see [DETAILED_GUIDE.md](DETAILED_GUIDE.md).
Include concrete examples. Abstract descriptions are less useful than concrete patterns:
## Input Validation
### Pattern
```typescript
// Good: Explicit validation with typed errors
const validated = PaymentSchema.safeParse(input);
if (!validated.success) {
throw new ValidationError(validated.error.issues);
}
// Bad: Implicit coercion
const amount = Number(input.amount); // Silent NaN on invalid input
**Test with realistic requests.** After creating a skill, test whether Claude activates it:
Review this payment processing code for issues
Should activate payments-domain skill
How should I handle refunds?
Should activate payments-domain skill
What’s the weather like?
Should NOT activate payments-domain skill
If Claude doesn't activate the skill when expected, revise the description to include the trigger phrases you're using.
### Team Sharing Strategies
**Git-based sharing (recommended for project skills):**
```bash
# Add skill to project
mkdir -p .claude/skills/team-standard
# Create SKILL.md and supporting files
# Commit
git add .claude/skills/
git commit -m "Add team coding standards skill"
git push
# Teammates get it automatically
git pull
claude # Skill now available
Cross-project sharing via symlinks:
# Create canonical skill location
mkdir -p ~/shared-skills/security-reviewer
# Create SKILL.md
# Symlink into projects
ln -s ~/shared-skills/security-reviewer ~/.claude/skills/security-reviewer
# Now available in all your projects
Plugin distribution: For broader distribution, package skills into plugins:
my-plugin/
├── .claude-plugin/
│ └── plugin.json
└── skills/
└── my-skill/
└── SKILL.md
Skills bundled in plugins become available when users install the plugin.
Debugging Skills
Skill not activating:
-
Check the description matches your request:
yaml # If you're saying "check this code" but description says "review" description: Review OR check code for issues... -
Verify file location: ```bash # Personal ls ~/.claude/skills/my-skill/SKILL.md
# Project ls .claude/skills/my-skill/SKILL.md ```
- Validate YAML frontmatter:
- First line must be exactly
--- - Closing
---before markdown content - No tabs in YAML (use spaces)
-
Name field is lowercase with hyphens only
-
Run in debug mode:
bash claude --debug # Watch for skill loading messages
Skill activating unexpectedly:
Narrow the description. If your skill activates when it shouldn’t, the description is too broad:
# Too broad - activates on any "code" mention
description: Help with code
# Specific - activates only for security contexts
description: Audit code for security vulnerabilities including injection attacks, authentication flaws, and data exposure. Use when specifically asked about security, vulnerabilities, or when reviewing code for security issues.
Supporting files not found:
- Use relative paths from SKILL.md location
- Forward slashes only (even on Windows)
- Check file actually exists:
ls .claude/skills/my-skill/REFERENCED.md
When to Create a Skill
Create a skill when: - Domain expertise should be automatically available - Multiple team members need the same knowledge - You’re repeatedly explaining the same patterns or rules - Context should be injected without explicit invocation - Knowledge spans multiple files and needs organization
Don’t create a skill when: - You want explicit control over invocation (use slash command) - The task needs separate context (use subagent) - It’s a one-off prompt (just type it) - The “skill” is really just a single template (use slash command)
Expert tip: If you find yourself repeatedly typing /security-review before working on auth code, convert it to a skill. The expertise should be ambient, not explicitly invoked. If you want explicit invocation, keep it as a command.
Plugin System
Plugins package Claude Code extensions for distribution. A plugin can include custom commands, subagents, skills, hooks, and MCP servers. Anthropic officially launched the plugin marketplace in December 2025 with 36 curated plugins.47
Plugin Structure
my-plugin/
├── .claude-plugin/
│ └── plugin.json # Required: metadata
├── commands/ # Slash commands
│ └── hello.md
├── agents/ # Subagents
│ └── helper.md
├── skills/ # Skills
│ └── my-skill/
│ └── SKILL.md
├── hooks/ # Event handlers
│ └── hooks.json
└── .mcp.json # MCP servers
Plugin Manifest
Minimal plugin.json:
{
"name": "my-plugin",
"description": "What this plugin does",
"version": "1.0.0",
"author": {
"name": "Your Name"
}
}
Plugin Management
> /plugin # Interactive interface
> /plugin install name@marketplace # Install
> /plugin enable name@marketplace # Enable
> /plugin disable name@marketplace # Disable
> /plugin uninstall name@marketplace # Remove
> /plugin marketplace add ./local # Add local marketplace
> /plugin marketplace list # View marketplaces
Local Development
Create a local marketplace for testing:
mkdir dev-marketplace && cd dev-marketplace
mkdir my-plugin
# Create plugin structure
cd ..
claude
> /plugin marketplace add ./dev-marketplace
> /plugin install my-plugin@dev-marketplace
Plugin Components
- Commands: Available as slash commands (
/plugin-command) - Agents: Appear in
/agentslist - Skills: Auto-load based on skill config
- Hooks: Merged with user/project hooks, run in parallel
- MCP Servers: Auto-start when plugin enabled
How Does Memory Work?
Claude Code’s memory system enables persistent context across sessions. Effective memory management is the difference between Claude understanding your project deeply and treating every session as a fresh start.
CLAUDE.md Hierarchy
| Location | Scope | Shared | Use Case |
|---|---|---|---|
/Library/Application Support/ClaudeCode/CLAUDE.md (macOS) |
Enterprise | All users | Company standards |
./CLAUDE.md or ./.claude/CLAUDE.md |
Project | Via git | Team context |
~/.claude/CLAUDE.md |
User | All projects | Personal preferences |
./CLAUDE.local.md |
Project-local | Never | Personal project notes |
Effective CLAUDE.md Structure
# Project Context
## Architecture
- Monorepo with packages in /packages
- React frontend in /packages/ui
- Node.js API in /packages/api
- Shared types in /packages/types
- PostgreSQL database via Prisma
## Code Standards
- TypeScript strict mode everywhere
- ESLint + Prettier enforced (pre-commit hooks)
- No default exports
- JSDoc on all public APIs
- Tests required for all new code
## Commands
- `npm test` - Run all tests
- `npm run test:watch` - Watch mode
- `npm run lint` - Check linting
- `npm run lint:fix` - Auto-fix lint issues
- `npm run build` - Production build
- `npm run dev` - Start dev servers
- `npm run db:migrate` - Run migrations
- `npm run db:seed` - Seed database
## Patterns
### API Endpoints
Create in packages/api/src/routes/
Use Zod for request/response validation
All endpoints need OpenAPI documentation
### React Components
Create in packages/ui/src/components/
Use React Query for server state
Prefer composition over inheritance
### Database
Prisma schema in packages/api/prisma/
Always create migration for schema changes
Use transactions for multi-table operations
## Important Notes
- NEVER commit .env files
- API runs on :3000, UI on :3001
- Local DB: postgres://localhost:5432/myapp
- Feature flags in packages/api/src/flags.ts
## Recent Decisions
- 2025-12-01: Migrated to React Query v5
- 2025-11-15: Adopted Zod for all validation
- 2025-11-01: Moved to ESM modules
# Summary Instructions
When using compact, focus on:
- Recent code changes
- Test results
- Architecture decisions made this session
File Imports
Reference other files within CLAUDE.md:
See @README.md for project overview
Coding standards: @docs/STYLE_GUIDE.md
API documentation: @docs/API.md
Personal preferences: @~/.claude/preferences.md
Import syntax:
- Relative: @docs/file.md
- Absolute from project: @/absolute/path.md
- Home directory: @~/.claude/file.md
- Maximum depth: 5 levels of imports
Memory Rules Directory
For more organized memory, use .claude/rules/ to store categorized rule files:18
.claude/rules/
├── testing.md # Testing conventions
├── security.md # Security requirements
├── api-patterns.md # API design patterns
└── deployments.md # Deployment procedures
Rules load automatically and provide structured context without cluttering CLAUDE.md.
Quick Memory Addition
Use the # prefix to add notes during a session:
# Always run tests before committing
# The payment module is especially fragile
# Use the new logger from packages/api/src/logger.ts
You’ll be prompted to select which memory file to store the note in.
Context Management Commands
View context usage:
> /context
Shows a visual grid of context allocation across system prompt, conversation, tools, and file contents.
Compact conversation:
> /compact
> /compact focus on the authentication changes
> /compact preserve test output and error messages
Intelligently summarizes older conversation while preserving key information.
Custom compaction instructions (in CLAUDE.md):
# Summary Instructions
When using compact, focus on:
- Test output and failures
- Code changes made this session
- Architecture decisions
Extended thinking for context:
export MAX_THINKING_TOKENS=10000
More thinking tokens means more reasoning capacity but higher costs.
Context Optimization Strategies
- Use specific file references instead of asking Claude to search
- Clear unrelated conversations with
/clearbetween tasks - Compact proactively during long sessions
- Use subagents to isolate exploratory work
- Break complex tasks into focused interactions
- Resume sessions for ongoing work rather than re-explaining
Image and Multimodal Input
Claude Code can analyze images—screenshots, diagrams, mockups, error messages, database schemas.
Input Methods
- Drag and drop: Drag image files into the Claude Code window
- Paste:
Ctrl+V(not Cmd+V on Mac) to paste from clipboard - Path reference: “Analyze this image: /path/to/screenshot.png”
Viewing Attached Images
When Claude references an image in its response, clickable image links allow direct viewing:34
[Image #1] # Click to open in default image viewer
[Image #2] # Navigate attached screenshots
This is useful when reviewing screenshots or debugging visual issues—click the reference to see exactly what Claude analyzed.
Use Cases
- Debug UI issues: “Here’s a screenshot of the bug, what’s causing it?”
- Implement designs: “Build this component based on the mockup”
- Analyze diagrams: “Explain this architecture diagram”
- Database schemas: “Create Prisma models matching this ERD”
- Error analysis: “What does this error screenshot mean?”
Expert tip: When implementing from mockups, include multiple screenshots showing different states (default, hover, loading, error). The more visual context, the better the implementation.
How Does Git Integration Work?
Claude Code has deep git integration with built-in safety protocols.
Safety Protocols
- Respects
.gitignoreautomatically - Won’t modify branches without permission
- Shows diffs before commits
- Follows project’s commit conventions
- Never force pushes without explicit request
- Checks authorship before amending commits
Common Workflows
Create commits:
> commit these changes
> create a commit with a meaningful message
Claude will:
1. Run git status and git diff
2. Analyze changes
3. Generate a conventional commit message
4. Wait for approval before committing
Create pull requests:
> create a PR for this feature
> summarize the changes and create a PR
Review code:
> review the changes in this PR
> what could go wrong with these changes?
GitHub Actions Integration
Automate Claude in CI/CD with the official action:
Quick setup:
> /install-github-app
Manual workflow file:
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize]
issue_comment:
types: [created]
jobs:
claude-review:
runs-on: ubuntu-latest
steps:
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
prompt: "Review this PR for bugs, security issues, and performance problems"
claude_args: "--max-turns 5"
For Bedrock (with OIDC):
- name: Configure AWS
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }}
aws-region: us-west-2
- uses: anthropics/claude-code-action@v1
with:
use_bedrock: "true"
claude_args: '--model us.anthropic.claude-sonnet-4-5-20250929-v1:0'
How Do I Use Claude Code in My IDE?
VS Code Extension
Requirements: VS Code 1.98.0+
Installation: Search “Claude Code” in Extensions marketplace
Features: - Sidebar panel (Spark icon) - Plan mode with diff preview - Auto-accept edits toggle - Extended thinking toggle - File attachment and image pasting - Conversation history - Multiple simultaneous sessions
Security Note: A WebSocket authentication bypass vulnerability (CVE-2025-52882) was patched in IDE extensions v1.0.24+. Ensure your extension is updated—all vulnerable versions have been removed from extension stores.38
Third-party provider configuration (in .claude/settings.json):
{
"env": {
"CLAUDE_CODE_USE_BEDROCK": "1",
"AWS_REGION": "us-east-1",
"AWS_PROFILE": "your-profile"
}
}
JetBrains Plugin
Supported: IntelliJ IDEA, PyCharm, WebStorm, GoLand, PhpStorm, DataGrip
Installation: Settings → Plugins → Search “Claude Code” → Install → Restart
Key shortcuts:
- Cmd+Esc (Mac) / Ctrl+Esc (Windows): Quick launch
- Cmd+Option+K (Mac) / Alt+Ctrl+K (Windows): Add file reference
Features: - Diff viewing in IDE diff viewer - Selection context auto-sharing - Diagnostic integration - Multiple sessions
WSL2 configuration: Set Claude command to:
wsl -d Ubuntu -- bash -lic "claude"
Terminal Integration
Connect an external terminal to your IDE:
> /ide
Claude Code auto-detects VS Code, Cursor, Windsurf, and JetBrains IDEs.
Slack Integration (December 2025)
Claude Code now integrates directly with Slack, enabling developers to delegate coding tasks from chat threads.14
How it works:
1. Mention @Claude in a Slack channel or thread
2. Claude reviews the message to determine if it’s a coding task
3. A Claude Code session automatically starts on Anthropic infrastructure
4. Claude gathers context from recent channel/thread messages
5. Progress updates post back to your Slack thread
6. Links to review changes and open PRs provided on completion
Use cases: - Bug investigation from bug reports posted in Slack - Quick code reviews based on team feedback - Small feature implementations from feature requests
Requirements: - Claude app installed via Slack App Marketplace - Paid Slack plan - Access to Claude Code on the web
Privacy: Claude respects Slack’s existing permission structure. It cannot access conversations or repositories you aren’t authorized to see. Conversations are not used for model training.
Advanced Usage Patterns
Headless and CI Mode
Run Claude Code in scripts and CI pipelines:
#!/bin/bash
# Automated code review
result=$(claude -p "Review this code for quality issues" \
--output-format json \
--allowedTools "Read,Grep,Glob" \
--permission-mode plan \
--disable-slash-commands \
--max-turns 5)
if echo "$result" | jq -e '.result | test("critical|high severity")' > /dev/null; then
echo "Issues found:"
echo "$result" | jq -r '.result'
exit 1
fi
echo "Review passed"
exit 0
Piping and Chaining
# Analyze logs
cat production.log | claude -p "summarize errors" > error-summary.md
# Process multiple files
find . -name "*.ts" -exec cat {} \; | claude -p "find security issues"
# Chain with jq
claude -p "generate config" --output-format json | jq -r '.result' > config.json
Background Tasks
Run long operations without blocking:
> start the build in the background
Or press Ctrl+B during command execution.
Manage background tasks:
> /bashes # List running tasks
> get output from task xyz # Retrieve output
Parallel Sessions with Git Worktrees
# Create worktrees for parallel work
git worktree add ../project-feature-a -b feature-a
git worktree add ../project-bugfix bugfix-123
# Run Claude in each
cd ../project-feature-a && claude --session-id "feature-a"
cd ../project-bugfix && claude --session-id "bugfix-123"
Each worktree is an independent project directory with its own session.
JSON Output Parsing
result=$(claude -p "analyze this code" --output-format json)
# Extract fields
echo "Result: $(echo $result | jq -r '.result')"
echo "Cost: $(echo $result | jq -r '.total_cost_usd')"
echo "Session: $(echo $result | jq -r '.session_id')"
echo "Duration: $(echo $result | jq -r '.duration_ms')ms"
Programmatic Session Management
# Named sessions for tracking
claude --session-id "feature-$(git branch --show-current)-$(date +%s)"
# Continue previous work
claude -c "continue implementing the tests"
# Fork for parallel exploration
claude -r "main-session" --fork-session "try alternative approach"
What Is Claude Code Remote?
Claude Code Remote bridges the gap between web and terminal, letting you start tasks in the cloud and continue them locally—or vice versa. This feature transforms how you work across devices.
The Core Concept
The web interface at claude.ai/code runs Claude Code in the cloud. Tasks execute in the background while you’re away from your terminal. When you’re ready to continue, teleport the session to your local machine and pick up exactly where Claude left off.
This enables workflows that weren’t possible before: - Start a complex refactoring task from your phone, let it run while you commute, then finish on your workstation - Queue up multiple tasks on the web interface, review results when you return to your desk - Hand off long-running operations to the cloud when you need to close your laptop
The & Prefix
Send a task to run on Claude Code web in the background:
& Build a comprehensive REST API for user management with authentication, CRUD operations, and proper error handling
The & prefix dispatches your prompt to the cloud. Claude works on it asynchronously—you can close your terminal, switch devices, or continue with other work. The web interface at claude.ai/code shows your running and completed sessions.
The --teleport Flag
Pull a cloud session into your local terminal:
claude --teleport session_abc123
This retrieves the session state from the web and resumes it locally. You get the full conversation history, any files Claude modified, and can continue the interaction as if you’d been there the whole time.
The session ID appears in the web interface. Click on any session to see its ID and current status.
Requirements
Claude Code Remote is available for Pro, Max, Team (premium seats), and Enterprise (premium seats) subscribers.73 The web interface runs on Anthropic’s infrastructure, executing the same Claude Code capabilities you have locally—file operations, bash commands, MCP integrations—but in a managed cloud environment. Team and Enterprise access was expanded in January 2026—account admins can toggle access in Claude settings.
iOS App (November 2025): Claude Code is also available on the Claude iOS app, allowing you to kick off coding tasks on the go and monitor agent progress from your phone.22 You can start tasks while away from your desk and later teleport them to your terminal when you’re ready to review.
Practical Workflow
Morning commute:
& Review all PRs assigned to me and prepare summaries with recommendations
At your desk:
# Check what completed
# Visit claude.ai/code to see session list
# Pull the session locally to review and act on recommendations
claude --teleport pr-review-session-xyz
Before leaving work:
& Run the full test suite, fix any failures, and prepare a summary of what was changed
Next morning:
claude --teleport test-fixes-session-abc
# Review what Claude did overnight, make final adjustments
Current Status
Claude Code Remote is currently in research preview. Expect the feature to evolve as Anthropic gathers feedback. The core workflow—cloud execution with local teleportation—enables continuous AI development: Claude works while you’re away from your keyboard, and you pick up exactly where it left off.
Current limitation: Session teleportation is currently one-way only—you can pull web sessions into your terminal, but you cannot push an existing terminal session to the web. There’s no way to continue a local session on a remote machine (e.g., an AWS instance via SSH) yet.
What Are Background Agents?
Background agents run while you continue working—no waiting for long-running tasks to complete.17
How Background Agents Work
Instead of blocking your terminal while Claude runs a complex task, background agents: 1. Execute independently in a separate process 2. Continue working even if you close your terminal 3. Report results when complete via notification 4. Can be monitored and managed while running
Starting a Background Agent
Using Ctrl+B:
While Claude is working, press Ctrl+B to send the current task to the background. Your terminal becomes available immediately.
Using the & prefix:
& Run all tests and fix any failures
& Refactor the authentication module to use JWT
& Generate comprehensive API documentation
The & prefix dispatches to Claude Code Remote (cloud execution). For local background execution, use Ctrl+B on an already-running task.
Monitoring Background Tasks
> /tasks # List all running tasks
> /task status abc123 # Check specific task
> /task cancel abc123 # Stop a task
> /task output abc123 # View task output so far
Parallel Background Workflows
Run multiple agents simultaneously:
& Fix all failing tests in src/
& Update documentation for the API module
& Run security scan on the codebase
Each runs independently. Monitor progress with /tasks and pull results as they complete.
Claude in Chrome (December 2025)
Claude Code now integrates with your browser through the Claude in Chrome extension, enabling direct browser control from your terminal.24
Setup
- Install the Chrome extension from https://claude.ai/chrome
- Launch Claude Code and the integration is automatically detected
- Use natural language to control your browser
Capabilities
Browser automation from terminal:
> Navigate to github.com and open my repositories
> Fill out this form with the test user data
> Take a screenshot of the current page
> Click the submit button and wait for the page to load
Web scraping and testing:
> Extract all product prices from this e-commerce page
> Run through the signup flow and report any issues
> Check if the mobile menu works correctly
Use Cases
- E2E testing: Run integration tests directly from Claude Code
- Web scraping: Extract data from pages without writing browser automation code
- Form filling: Automate repetitive web workflows
- Visual verification: Screenshot and analyze page layouts
The Chrome integration runs within your existing browser session, accessing your logged-in state and cookies—useful for testing authenticated flows.
Claude Code in Slack (December 2025)
Anthropic launched Claude Code in Slack, allowing developers to delegate coding tasks directly from chat threads.26
How It Works
- Tag
@Claudein any Slack channel or thread - Describe the coding task with context
- Claude analyzes Slack messages to determine the repository
- Progress updates appear in the thread
- Claude shares links to review work and open PRs
Example Workflow
@Claude The login form validation is broken on mobile devices.
Can you fix it? Check the bug report from earlier in this thread.
Claude will: 1. Read the thread for context 2. Identify the relevant repository 3. Clone and analyze the codebase 4. Post progress updates 5. Create a PR with the fix 6. Share the PR link for review
Benefits
- Context awareness: Claude reads Slack history for bug reports, feature requests, and discussions
- Team visibility: Progress updates in threads keep everyone informed
- Low friction: No terminal or IDE required—start from chat
- GitHub integration: PRs created automatically with proper descriptions
Requirements
- Slack workspace with Claude integration enabled
- GitHub repository connected
- Appropriate permissions for Claude to create branches/PRs
This feature is currently in research preview for Pro, Max, Team, and Enterprise users.
What Does Claude Code Cost?
Understanding and controlling costs is essential for sustainable Claude Code usage.
Viewing Costs
> /cost
Output:
Total cost: $0.55
Total duration (API): 6m 19.7s
Total duration (wall): 6h 33m 10.2s
Total code changes: 247 lines added, 89 lines removed
Subscription Plans
| Plan | Price | Usage | Access |
|---|---|---|---|
| Free | $0 | Limited | No Claude Code access |
| Pro | $20/month | 5x Free | Claude Code + Opus 4.5 access20 |
| Max (5x) | $100/month | 5x Pro | Priority access, enhanced performance |
| Max (20x) | $200/month | 20x Pro | Highest priority, can buy additional usage |
Rate limits (August 2025): Anthropic introduced weekly rate limits for paid subscribers. Max subscribers can purchase additional usage beyond the rate limit at standard API rates.21
API Token Pricing (January 2026)57
For API-billed users, per-million-token pricing:
| Model | Input | Output | Notes |
|---|---|---|---|
| Haiku 4.5 | $1 | $5 | Speed and efficiency |
| Sonnet 4.5 | $3 | $15 | Balanced intelligence/cost |
| Opus 4.5 | $5 | $25 | Flagship performance (66% cheaper than Opus 4/4.1) |
Prompt caching significantly reduces repeated input costs: cache writes cost 1.25× base (5-min cache) or 2× (1-hr cache), but cache reads cost only 0.1×—a 90% savings. For RAG systems and code assistants with repeated context, caching can reduce costs 88-95%.
Batch API offers 50% discounts with 24-hour turnaround for non-urgent tasks like overnight test suites.
Multiple Accounts Policy59
Can you have multiple Claude accounts? Yes, for legitimate use cases. Anthropic explicitly permits multiple accounts when they serve distinct purposes.
What’s allowed:
| Scenario | Example | Status |
|---|---|---|
| Household members | You and spouse each have Max accounts | Allowed |
| Work + Personal | Personal account + employer-managed work account | Allowed |
| Individual + Team | Personal Pro/Max alongside organization account | Allowed |
| Same network | Multiple accounts from same home WiFi | Allowed |
| Same computer | Switching between accounts on one machine | Allowed |
Technical limits: - Up to 3 accounts can be verified with the same phone number - Multiple paid subscriptions from the same IP/network are explicitly supported - Accounts are completely separate—no chat or project transfer between them
What’s prohibited (per the Usage Policy): - Creating accounts to evade bans after being banned - Coordinating malicious activity across accounts to avoid detection - Using multiple accounts to circumvent rate limits or free tier credits
Real-world note: In January 2026, power user Jeffrey Emanuel (@doodlestein) had 22 Max accounts auto-flagged and temporarily banned. Anthropic employee Thariq (@trq212) resolved it within 4 hours after confirming legitimate use. If you’re using Claude Code extensively for both work and personal projects across multiple accounts, that’s exactly what the service is designed for—just don’t try to game the system.
When in doubt: Contact Anthropic Support to confirm your specific setup in writing.
Cost Factors
| Factor | Impact | Optimization |
|---|---|---|
| Model choice | Opus >> Sonnet >> Haiku | Use Haiku for simple tasks |
| Input tokens | More context = more cost | Keep CLAUDE.md focused |
| Output tokens | Longer responses cost more | Set MAX_OUTPUT_TOKENS |
| Thinking tokens | Extended thinking adds cost | Use only when needed |
| Prompt caching | Reduces repeated input costs | Keep enabled (default) |
Real-World Cost Examples
| Task | Model | Input | Output | Cost |
|---|---|---|---|---|
| Quick file search | Haiku | 20K | 2K | $0.03 |
| Bug fix with tests | Sonnet | 100K | 30K | $0.75 |
| Architecture review | Opus | 150K | 50K | $2.00 |
| Full-day session (Sonnet) | Sonnet | 500K | 150K | $3.75 |
| Full-day session (mixed) | Haiku+Sonnet | 500K | 150K | ~$2.00 |
Cost-saving insight: Using Haiku for exploration subagents and Sonnet for implementation typically reduces costs 40-50% compared to using Sonnet for everything.
Team Cost Management
Recommended TPM/RPM by team size:
| Team Size | TPM per User | RPM per User |
|---|---|---|
| 1-5 | 200k-300k | 5-7 |
| 5-20 | 100k-150k | 2.5-3.5 |
| 20-50 | 50k-75k | 1.25-1.75 |
| 50-100 | 25k-35k | 0.62-0.87 |
| 100+ | 10k-20k | 0.25-0.5 |
Hidden Tool Fees
Beyond per-token pricing, some tools incur separate charges:16
| Tool | Fee | Notes |
|---|---|---|
| Code execution | $0.05/session-hour | First 1,550 hrs/org/month free40 |
| Web search | $10/1,000 searches | Token costs still apply |
| Bash tool | +245 input tokens/call | Overhead per invocation |
| Text editor | +~700 input tokens/call | Typical overhead |
These add up in agent loops. A 100-iteration debug cycle with Bash costs ~24,500 extra input tokens in overhead alone.
Cost-Saving Strategies
- Use Haiku for subagents: Most exploration doesn’t need Sonnet
- Enable prompt caching: Default, but verify it’s not disabled
- Set max turns:
claude --max-turns 5prevents runaway conversations - Use plan mode for exploration: No execution = no accidental expensive operations
- Compact proactively: Smaller context = fewer tokens
- Limit output:
export CLAUDE_CODE_MAX_OUTPUT_TOKENS=2000 - Batch API for non-urgent work: 50% off both input and output tokens
Monitoring Usage
- Claude Console: platform.claude.com (requires Admin or Billing role)
- Workspace limits: Set spending limits per workspace
- Bedrock/Vertex: Use native cloud cost monitoring
- LiteLLM: For detailed per-user tracking with third-party providers
Background Token Usage
Some operations consume tokens in the background:
- Conversation summarization for /resume
- /cost and /status commands
- Auto-compaction
Typically under $0.04 per session.
Claude Code Analytics API (Team/Enterprise)53
Programmatically access your organization’s Claude Code usage analytics and productivity metrics via the Admin API.
Endpoint: GET /v1/organizations/usage_report/claude_code
Requirements:
- Admin API key (sk-ant-admin...)
- Team or Enterprise plan
- Admin, Billing, or Developer role
Available Metrics:
| Metric | Description |
|---|---|
num_sessions |
Distinct Claude Code sessions initiated |
lines_of_code.added/removed |
Total lines of code added/removed |
commits_by_claude_code |
Number of git commits created |
pull_requests_by_claude_code |
Number of PRs created |
terminal_type |
Environment (vscode, iTerm.app, tmux, etc.) |
customer_type |
api (API customers) or subscription (Pro/Team) |
Example Request:
curl "https://api.anthropic.com/v1/organizations/usage_report/claude_code?starting_at=2026-01-15" \
-H "x-api-key: sk-ant-admin..." \
-H "anthropic-version: 2023-06-01"
Use Cases: - Developer productivity analysis (sessions, commits, PRs) - Tool usage metrics (acceptance/rejection rates for Edit, Write, etc.) - Cost tracking and allocation across teams - ROI justification for AI coding tools
Note: Data appears within 1 hour of activity completion. Only data older than 1 hour is included in responses for consistency.
Performance Optimization
Reducing Latency
Model selection: - Haiku: Fastest responses, lowest cost - Sonnet: Good balance - Opus: Best quality, highest latency
Streaming: All responses stream by default—you see output as it’s generated.
Prompt caching: Enabled by default. Reduces latency for repeated context (system prompts, tool definitions).
Caching Strategies
System prompts and tool definitions are cached automatically: - Cache duration: 5 minutes (ephemeral) - Cache hit: Reduced input tokens and faster response
Thinking blocks from previous turns are cached in multi-turn conversations.
Disable caching per model if needed:
export DISABLE_PROMPT_CACHING_SONNET=1
export DISABLE_PROMPT_CACHING_OPUS=1
export DISABLE_PROMPT_CACHING_HAIKU=1
Parallel Operations
Subagent parallelization: Multiple subagents can run simultaneously. Each operates independently without polluting main context.
Background bash: Long-running commands don’t block the conversation:
> run the full test suite in the background
Git worktrees: Enable true parallel sessions on separate branches.
Memory Optimization
- Specific file references:
@src/auth.tsinstead of “find the auth file” - Targeted searches: “search in src/api” not “search everywhere”
- Fresh sessions:
/clearbetween unrelated tasks - Custom compaction: Add instructions to CLAUDE.md for what to preserve
How Do I Debug Issues?
Installation Issues
WSL path problems:
npm config set os linux
npm install -g @anthropic-ai/claude-code --force --no-os-check
which npm # Should start with /usr not /mnt/c
Node version conflicts (nvm):
Add to ~/.bashrc or ~/.zshrc:
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
Permission errors: Use native installation instead of npm:
curl -fsSL https://claude.ai/install.sh | bash
Authentication Issues
# Complete reset
/logout
rm -rf ~/.config/claude-code/auth.json
claude # Fresh login
Performance Issues
High CPU/memory:
- Use /compact to reduce context
- Restart between major tasks
- Add large directories to .gitignore
- Run claude doctor
Slow search: Install system ripgrep:
# macOS
brew install ripgrep
# Windows
winget install BurntSushi.ripgrep.MSVC
# Linux
sudo apt install ripgrep
Then:
export USE_BUILTIN_RIPGREP=0
Slow on WSL:
- Move project to Linux filesystem (not /mnt/c/)
- Use specific directory filters in searches
IDE Integration Issues
JetBrains not detected (WSL2):
Option 1 - Windows Firewall:
wsl hostname -I # Get WSL IP
New-NetFirewallRule -DisplayName "Allow WSL2" -Direction Inbound -Protocol TCP -Action Allow -RemoteAddress 172.21.0.0/16
Option 2 - Mirrored networking (add to ~/.wslconfig):
[wsl2]
networkingMode=mirrored
Then: wsl --shutdown
Escape key not working in JetBrains: Settings → Tools → Terminal → Uncheck “Move focus to the editor with Escape”
Debug Mode
claude --debug # Full debug output
ANTHROPIC_LOG=debug claude # API request logging
claude doctor # Health check
Configuration Reset
# Reset user settings
rm ~/.claude.json
rm -rf ~/.claude/
# Reset project settings
rm -rf .claude/
rm .mcp.json
Common Error Messages
| Error | Cause | Solution |
|---|---|---|
| “Rate limit exceeded” | Too many requests | Wait or reduce frequency |
| “Context length exceeded” | Conversation too long | Use /compact or /clear |
| “Authentication failed” | Invalid or expired token | Run /login |
| “Tool not permitted” | Permission denied | Check settings.json permissions |
| “MCP server failed to start” | Server misconfigured | Check claude mcp get <name> |
Enterprise Deployment
Cloud Provider Comparison
| Feature | Anthropic Direct | AWS Bedrock | Google Vertex | Microsoft Foundry |
|---|---|---|---|---|
| Auth | API key | IAM/API key | GCP credentials | Entra ID/API key |
| Cost tracking | Console | AWS Cost Explorer | GCP Billing | Azure Cost Mgmt |
| Audit logging | Limited | CloudTrail | Cloud Audit Logs | Azure Monitor |
| SSO | No | IAM | IAM | Entra ID |
Managed Settings Deployment
Deploy organization-wide policies via managed-settings.json:
Location:
- macOS: /Library/Application Support/ClaudeCode/managed-settings.json
- Linux: /etc/claude-code/managed-settings.json
- Windows: C:\Program Files\ClaudeCode\managed-settings.json
Example policy:
{
"permissions": {
"allow": [
"Read",
"Glob",
"Grep",
"Bash(npm run:*)",
"Bash(git:*)"
],
"deny": [
"Bash(rm -rf:*)",
"Bash(curl:*)",
"Read(.env*)",
"WebFetch"
],
"defaultMode": "default"
},
"model": "claude-sonnet-4-5-20250929",
"disableBypassPermissionsMode": "disable"
}
Users cannot override managed settings.
Enterprise CLAUDE.md
Deploy organization-wide context:
Location:
- macOS: /Library/Application Support/ClaudeCode/CLAUDE.md
- Linux: /etc/claude-code/CLAUDE.md
Content:
# Company Standards
## Security Requirements
- Never commit secrets or credentials
- All external API calls require security review
- Use parameterized queries for all database access
## Code Standards
- Follow company style guide at @docs/STYLE.md
- All PRs require two approvals
- Test coverage minimum: 80%
## Approved Tools
- npm, yarn, pnpm for package management
- Jest for testing
- ESLint + Prettier for formatting
Rollout Strategy
- Start with documentation: Get CLAUDE.md right before deploying
- Pilot group: Begin with 5-10 developers
- Q&A phase: Let pilots use Claude for code exploration
- Guided development: Progress to small bug fixes
- Full deployment: Roll out with managed settings
- Monitor costs: Track per-team usage
Audit and Compliance
- Session transcripts stored locally by default
- Use cloud provider logging for enterprise audit
- Consider LiteLLM for detailed usage tracking
- Managed settings enforce compliance policies
Analytics API (Admin)
Enterprise and Team plans have access to the Claude Code Analytics API for programmatic usage tracking.
Endpoint: GET /v1/organizations/usage_report/claude_code
Authentication: Requires Admin API key (sk-ant-admin...), provisioned in Console by org admins.
Metrics Available:
| Category | Metrics |
|---|---|
| Productivity | Sessions, lines added/removed, commits, PRs per user |
| Tool Usage | Acceptance/rejection rates by tool (Edit, Write, NotebookEdit) |
| Cost | Estimated cost breakdown by user and model |
Request Parameters:
- starting_at - Date for daily aggregation (YYYY-MM-DD)
- Returns user-level data for the specified day
Example:
curl -X GET "https://api.anthropic.com/v1/organizations/usage_report/claude_code?starting_at=2026-01-25" \
-H "x-api-key: sk-ant-admin-..." \
-H "anthropic-version: 2023-06-01"
Limitations: - Daily aggregates only (~1hr delay for consistency) - For real-time monitoring, use OpenTelemetry integration - Only tracks 1st party API usage (not Bedrock/Vertex)
Cost: Free for organizations with Admin API access.
Keyboard Shortcuts Reference
General Controls
| Shortcut | Action |
|---|---|
Ctrl+C |
Cancel current operation |
Ctrl+D |
Exit session (EOF) |
Ctrl+L |
Clear screen (keeps history) |
Ctrl+O |
Toggle verbose output |
Ctrl+R |
Search command history |
Ctrl+V |
Paste image from clipboard |
Ctrl+B |
Background current operation |
Ctrl+Y |
Yank (paste from kill ring) |
Ctrl+S |
Stash prompt draft (saves current input) |
Alt+Y |
Yank-pop (cycle kill ring after Ctrl+Y) |
Esc Esc |
Rewind last change |
Tab |
Accept prompt suggestion / Toggle extended thinking |
! + Tab |
Bash history autocomplete (v2.1.14+) |
Shift+Tab |
Cycle permission modes |
Alt+P / Option+P |
Switch models while typing prompt |
Alt+T |
Toggle thinking mode (safer alternative) |
Ctrl+T |
Toggle syntax highlighting in /theme |
Ctrl+G |
Open external editor (in AskUserQuestion “Other” input) |
Up/Down |
Navigate command history |
? |
Show shortcuts |
Customizable keybindings (v2.1.18+): Run /keybindings to customize keyboard shortcuts. Supports context-specific bindings, chord sequences (multi-key combos), and full personalization. Keybindings are stored in ~/.claude/keybindings.json. See keybindings docs for the full configuration reference.77
Prompt suggestions (Dec 2025): Claude now suggests prompts to speed up your workflow. Press Tab to accept a suggestion or Enter to submit your own prompt.13
Multiline Input
| Method | Keys |
|---|---|
| Escape newline | \ then Enter |
| macOS | Option+Enter |
| Out-of-box (v2.1.0+) | Shift+Enter in iTerm2, WezTerm, Ghostty, Kitty37 |
| Other terminals | Shift+Enter (run /terminal-setup first) |
| Control character | Ctrl+J |
Quick Prefixes
| Prefix | Action | Example |
|---|---|---|
# |
Add to memory | # Always use TypeScript |
/ |
Slash command | /review |
! |
Direct bash | ! git status |
@ |
File reference | @src/index.ts |
& |
Send to cloud | & Build the API |
File reference performance (Jan 2026): @ mentions are now 3x faster in git repos. Claude Code also respects .ignore and .rgignore files when suggesting file completions—useful for excluding build artifacts or generated files from suggestions.35
Vim Mode
Enable with /vim:
Normal mode:
- h/j/k/l - Navigation
- w/e/b - Word movement
- 0/$ - Line start/end
- gg/G - Buffer start/end
- dd - Delete line
- cc/C - Change line/to end
- dw/de/db - Delete word variations
- x - Delete character
- . - Repeat last edit
Insert mode:
- i/I - Insert before/at line start
- a/A - Insert after/at line end
- o/O - Open line below/above
- Esc - Return to normal mode
Best Practices
Session Strategy
Use descriptive session IDs:
claude --session-id "feature-$(git branch --show-current)-$(date +%s)"
claude --session-id "bug-JIRA-456"
claude --session-id "spike-new-architecture"
Resume sessions for ongoing work rather than re-explaining context.
CLAUDE.md Design
Keep it scannable. Claude reads this every session—dense prose wastes context.
Focus on the non-obvious. Document project-specific patterns, unusual conventions, decisions. Skip what Claude can infer from code.
Update continuously. Add notes during development with #. Review and consolidate weekly.
Include command reference. The commands you run constantly should be documented.
Custom Commands
Create commands for repetitive workflows:
---
description: Start new feature
allowed-tools: Bash(git:*), Read, Edit
---
1. Create branch: !`git checkout -b feature/$ARGUMENTS`
2. Pull latest main
3. Set up boilerplate
4. Begin implementation
Effective Prompting
Be specific:
# Good
"Add email validation to LoginForm in src/components/LoginForm.tsx"
# Too vague
"Improve the login"
Reference files directly:
"Review @src/auth/middleware.ts for security issues"
Provide constraints:
"Refactor using the same pattern as @src/repositories/UserRepository.ts"
Use subagents for exploration:
"Have an explore agent find all places where we handle errors"
Cost Control
- Use
/costregularly - Use Haiku for simple tasks and subagents
- Set
MAX_THINKING_TOKENSonly when needed - Use
--max-turnsfor automated scripts - Compact proactively in long sessions
Security
- Configure
.claude/settings.jsondeny rules for sensitive files - Use sandbox mode for untrusted projects
- Never allow
Bash(rm -rf:*)orBash(sudo:*) - Use hooks to block access to secrets
- Deploy managed settings for enterprise
Community Tips and Techniques5658
The Claude Code community has discovered powerful patterns that go beyond official documentation. These tips come from power users including Boris Cherny (Claude Code creator) and the 40+ tips repository.
Use Plan Mode Before Coding
If you remember one tip, make it this one. The more time you spend planning, the more likely Claude will succeed. Press Shift+Tab to cycle to plan mode before starting implementation.
New in January 2026: When you accept a plan, Claude now offers to automatically clear your context, giving the plan a fresh context window. This significantly improves plan adherence—Claude stays on track longer without old context interfering. Options include: “Yes, clear context and auto-accept edits” (Shift+Tab), “Yes, and manually approve edits”, or “Yes, auto-accept edits” (without clearing).
Clear Context Frequently
Use /clear often. Every time you start something new, clear the chat. You don’t need old history consuming tokens or triggering expensive compaction calls. Just clear it and move on.
Use Images and Screenshots
Claude excels with visual input. On macOS: Cmd+Ctrl+Shift+4 captures screenshot to clipboard, then Ctrl+V to paste directly into Claude Code. Use this to share UI mockups, error messages, or design references.
Install the GitHub App for PR Reviews
Run /install-github-app and Claude will automatically review your PRs. This is particularly valuable as AI-assisted development increases PR volume—Claude often catches logic errors and security issues that human reviewers miss.
Container-Based Autonomous Operation
For fully autonomous operation, run Claude Code in a Docker container with tmux as the control layer. Your local Claude Code controls the containerized instance, which can run long-running or experimental tasks without manual approval. If something goes wrong, it’s sandboxed.
# Conceptual pattern (varies by setup)
# Local Claude Code → tmux → Container Claude Code
# Results pulled back when complete
Docker Sandbox Mode (Quick Start): Claude Code supports a simplified Docker sandbox via the docker subcommand. This creates an isolated environment for exploring untrusted codebases or running experimental prompts safely.63
# Run Claude Code in Docker sandbox
docker sandbox run claude
# Or with specific project
docker sandbox run claude /path/to/project
Use sandbox mode when: - Exploring unfamiliar or untrusted codebases - Testing experimental prompts that might modify files - Running autonomous sessions you want completely isolated - Learning Claude Code without risk to your actual files
Gemini CLI as Fallback
Claude Code’s WebFetch tool can’t access certain sites (like Reddit). Create a skill that tells Claude to use Gemini CLI as a fallback—Gemini has web access and can fetch content from sites Claude can’t reach directly.
Meta-Agent Factory Pattern
Instead of creating agents that do tasks, create an agent that creates other agents. This isn’t clever recursion—it’s a genuine productivity multiplier for complex automation workflows.
Claude Squad: Multi-Agent Manager
Claude Squad manages multiple Claude Code instances in parallel, each in its own tmux session with isolated worktrees. Run several agents simultaneously on different tasks, monitor their progress from a single dashboard, and pull results back when complete.65
# Install
npm install -g @smtg-ai/claude-squad
# Start multiple agents
claude-squad start "Implement auth feature" --worktree auth-feature
claude-squad start "Write API tests" --worktree api-tests
claude-squad start "Update documentation" --worktree docs-update
# Monitor all agents
claude-squad status
Use cases: - Parallelize independent features across agents - Run exploratory prompts without blocking your main session - Scale autonomous coding beyond a single context window
Power User Productivity Stats
Boris Cherny demonstrated Claude Code’s potential: in 30 days, he landed 259 PRs with 497 commits—40,000 lines added and 38,000 removed. This showcases what’s possible when Claude Code is fully integrated into the development workflow.
People to Follow
Stay current with Claude Code developments by following these accounts:
Anthropic Team (Primary Sources)
| Who | Platform | Why Follow |
|---|---|---|
| Boris Cherny | @boris_cherny | Claude Code creator. Ships features, announces updates, hosts meetups. Primary source. |
| Cat Wu | @_catwu | Anthropic. Claude Code feature announcements, subagent updates. |
| @adocomplete | X | Advent of Claude series - comprehensive daily tutorials (hooks, plugins, prompt stashing). |
| Thariq | @trq212 | Anthropic engineer on Claude Code team. Resolves issues, posts updates. |
| Anthropic | @AnthropicAI | Official announcements and major releases. |
Top Content Creators
| Who | Focus | Notable |
|---|---|---|
| @dani_avila7 | Tutorials | Hooks comprehensive guide, rules explanation |
| @mattpocockuk | MCP/Tips | 10-lesson MCP tutorial, Docker sandbox, JSON optimization |
| ykdojo | GitHub Tips | 40+ tips repo, status line script, system prompt optimization |
| @ai_for_success | MCP/Workflows | Hyperbrowser MCP, documentation caching patterns |
| @jerryjliu0 | Agents | Step-by-step agent building tutorials |
Key Resources
- GitHub Releases: anthropics/claude-code/releases - Watch for releases only
- Discord: Anthropic community channels
- Full list: See
~/.claude/docs/following-list.mdfor 20+ curated accounts
Boris and the Anthropic team share features as they ship—often the fastest way to learn about new capabilities before documentation catches up.
Common Anti-patterns
Learning what NOT to do often provides more value than best practices. These patterns consistently cause problems:
Cost Anti-patterns
| Anti-pattern | Problem | Solution |
|---|---|---|
| Using Opus for everything | 5x cost, often unnecessary | Default Sonnet, Opus only for architecture |
Never checking /cost |
Surprise bills | Check cost after major tasks |
| Extended thinking on simple tasks | Wasted tokens | Toggle off (Tab) for routine work |
| Running explore in main context | Context bloat | Use Explore subagent instead |
Context Anti-patterns
| Anti-pattern | Problem | Solution |
|---|---|---|
| Ignoring context until it bloats | Degraded reasoning, forgotten decisions | /compact proactively at 50% capacity |
| Reading entire files when you need sections | Wastes context on irrelevant code | Reference specific line ranges |
| Never using subagents | Everything fills main context | Delegate exploration and analysis |
| Giant CLAUDE.md files | Context waste every session | Keep it under 500 lines, use imports |
Workflow Anti-patterns
| Anti-pattern | Problem | Solution |
|---|---|---|
| Creating overlapping skills and commands | Confusion, unpredictable behavior | One mechanism per purpose |
| Prompts for guaranteed actions | Claude may skip or forget | Use hooks for must-run actions |
| No hooks for formatting | Inconsistent code style | Hook every Edit/Write for formatter |
| Allowing all bash by default | Security risk | Explicit allowlist for safe commands |
Configuration Anti-patterns
| Anti-pattern | Problem | Solution |
|---|---|---|
| All config in user settings | Nothing shared with team | Project settings for team standards |
| Committing personal preferences | Overrides teammates | Use settings.local.json for personal |
| No deny rules | Claude can touch sensitive files | Deny .env, credentials, secrets |
| Ignoring managed settings | Enterprise policies bypassed | Managed settings for compliance |
Prompt Anti-patterns
| Anti-pattern | Problem | Solution |
|---|---|---|
| “Make it better” | Vague, poor results | Specify exactly what “better” means |
| Not referencing files | Claude guesses paths | Use @path/to/file.ts syntax |
| Ignoring Claude’s questions | Works on wrong assumptions | Answer before proceeding |
| Providing full docs when snippet suffices | Context waste | Extract relevant sections |
Workflow Recipes
End-to-end patterns for common scenarios.
Recipe 1: Starting a New Project
# 1. Initialize
cd my-project
claude
# 2. Let Claude understand the codebase
> "Explore this codebase and summarize the architecture"
# 3. Set up project configuration
> /init
# 4. Create CLAUDE.md with learned patterns
> "Create CLAUDE.md documenting the patterns you observed"
# 5. Add team commands
> "Create a /test command that runs our test suite"
> "Create a /deploy command for staging deployment"
Recipe 2: Daily Development Flow
# 1. Continue yesterday's session
claude -c
# 2. Quick context recap
> "What did we work on yesterday?"
# 3. Check current state
> /status
# 4. Work on feature (Sonnet handles most tasks)
> "Implement the user profile endpoint"
# 5. Proactive context management
> /compact # Before context exceeds 50%
# 6. Check spending
> /cost
# 7. End session cleanly
> "Summarize what we accomplished today"
Recipe 3: Complex Refactoring
# 1. Use Opus for planning, Sonnet for execution
> /model opusplan
# 2. Plan the refactoring
> "Plan refactoring our authentication from sessions to JWT"
# 3. Review the plan
# (Claude presents approach, you approve or modify)
# 4. Execute with Sonnet
> "Execute the plan"
# 5. Verify nothing broke
> "Have an explore agent verify all auth-related tests pass"
# 6. Review the diff
> !git diff
Recipe 4: PR Review Automation
# In CI/CD (GitHub Actions, etc.)
claude -p "Review this PR for:" \
--input-file pr_diff.txt \
--output-format json \
--permission-mode plan \
--max-turns 5 << EOF
- Security vulnerabilities
- Performance issues
- Code style violations
- Missing test coverage
Provide findings in JSON format.
EOF
Recipe 5: Debugging Production Issues
# 1. Configure Sentry MCP for error access
claude --add-mcp sentry
# 2. Get error context
> "Fetch the last 10 errors from Sentry for the auth service"
# 3. Deep dive with thinking
> Tab # Enable extended thinking
> "Analyze these errors and identify the root cause"
# 4. Fix and verify
> "Implement a fix and add a regression test"
> !npm test
Migration Guide
Coming from other AI coding tools? Here’s how concepts map.
From GitHub Copilot
| Copilot Concept | Claude Code Equivalent |
|---|---|
| Tab completion | Not a focus—Claude Code does agentic editing |
| Chat panel suggestions | REPL conversation with tool execution |
| Inline suggestions | Use @file references + Edit tool |
| No file creation | Creates, edits, deletes files directly |
| No terminal access | Full bash execution (with permissions) |
| Limited context | 200K-1M token window |
| IDE-only | Terminal + IDE extensions |
What you gain: True agentic capability—Claude Code reads your codebase, runs tests, creates PRs, and delegates to subagents. Not just suggestions.
From Cursor
| Cursor Concept | Claude Code Equivalent |
|---|---|
| Composer | Session with full tool access |
| Chat | REPL with subagent delegation |
| Codebase indexing | Real-time file access (Glob, Grep, Read) |
| Tab autocomplete | Not primary focus |
| IDE-integrated | Terminal-native + IDE extensions |
| No MCP | 300+ MCP integrations |
| Cursor rules | CLAUDE.md + Skills |
What you gain: MCP integrations (databases, GitHub, Sentry), subagent delegation, hooks for automation, and terminal-native workflow.
From ChatGPT / Claude Web
| Web Interface | Claude Code |
|---|---|
| Copy-paste code | Direct file access |
| Manual file creation | Writes files directly |
| No execution | Full bash, git, npm, etc. |
| Context resets | Session continuity (-c flag) |
| No codebase awareness | Glob, Grep, Read tools |
| No automation | Hooks, CI/CD integration |
What you gain: Everything. Web interfaces require copy-paste workflows; Claude Code operates directly on your codebase.
Key Mindset Shifts
- Stop copying code. Claude Code writes to files directly.
- Stop context-switching. MCP brings external tools into the session.
- Delegate aggressively. Subagents handle exploration without bloating your context.
- Automate with hooks. Formatting, linting, logging happen automatically.
- Think in sessions. Continue work with
-c, not fresh conversations.
Key Takeaways
For developers:
- Haiku costs 10-20x less than Opus—use for subagents and simple tasks
- Use /compact proactively during long sessions to manage context
- Session IDs encoding context (feature-${branch}-${timestamp}) help navigate back to previous work
- Prefix common prompts with # to add to persistent memory without extra typing
For DevOps and platform teams:
- Headless mode (-p flag) enables CI/CD integration with JSON output for parsing
- Hooks guarantee execution regardless of model behavior—use for linting, formatting, security checks
- MCP extends capabilities to databases, GitHub, Sentry, and 300+ integrations
- Background tasks (& prefix) run on Claude Code Remote for asynchronous execution
For security teams:
- Permission rules evaluated first-match-wins—structure allow/deny lists carefully
- Sandbox mode isolates filesystem and network for untrusted codebases
- Bash patterns match prefixes only—Bash(curl:*) blocks all curl, not just specific URLs
- Enterprise managed settings cannot be overridden by users
For team leads:
- Skills auto-activate based on context—embed domain expertise without explicit invocation
- Project skills commit to git—teammates get standardized expertise automatically
- Cost tracking via /cost shows session breakdown; budget 10k-300k TPM per user based on team size
- Custom commands in .claude/commands/ create reusable workflows
For enterprise architects:
- Managed settings deploy organization-wide policies via /etc/claude-code/managed-settings.json
- AWS Bedrock, Google Vertex AI, and Microsoft Foundry integrate with existing cloud billing
- Extended thinking (Tab to toggle) improves complex reasoning at higher cost
- Start pilot with 5-10 developers before full rollout
Quick Reference Card
Print this. Tape it to your monitor.
╔═══════════════════════════════════════════════════════════════╗
║ CLAUDE CODE QUICK REFERENCE ║
╠═══════════════════════════════════════════════════════════════╣
║ MODELS ║
║ haiku $1/$5/M Exploration, simple tasks ║
║ sonnet $3/$15/M Daily coding (default) ║
║ opus $5/$25/M Architecture, hard problems ║
║ sonnet[1m] $6/$22.50/M Large codebases (1M context) ║
╠═══════════════════════════════════════════════════════════════╣
║ ESSENTIAL COMMANDS ║
║ /compact Reduce context (do at 50% capacity) ║
║ /cost Check session spending ║
║ /model opus Switch to Opus ║
║ /status Show current state ║
║ /init Set up project config ║
║ /mcp Configure integrations ║
╠═══════════════════════════════════════════════════════════════╣
║ KEYBOARD SHORTCUTS ║
║ Tab Toggle extended thinking ║
║ Shift+Tab Cycle permission modes ║
║ Ctrl+C Interrupt current operation ║
║ Esc → Esc Rewind last change ║
║ Ctrl+L Clear screen ║
╠═══════════════════════════════════════════════════════════════╣
║ PREFIXES ║
║ #message Add to persistent memory ║
║ @path/file Reference file in prompt ║
║ !command Execute bash directly ║
║ &task Send to cloud (async) ║
╠═══════════════════════════════════════════════════════════════╣
║ CONFIG FILE HIERARCHY (first found wins) ║
║ .claude/settings.local.json Personal (gitignored) ║
║ .claude/settings.json Project (shared) ║
║ ~/.claude/settings.json User global ║
║ /etc/.../managed-settings.json Enterprise (locked) ║
║ CLAUDE.md Project context ║
╠═══════════════════════════════════════════════════════════════╣
║ DAILY WORKFLOW ║
║ 1. claude -c Continue session ║
║ 2. Work on features Use Sonnet ║
║ 3. /compact Before context bloats ║
║ 4. /cost Check spending ║
║ 5. Summarize Clean exit ║
╠═══════════════════════════════════════════════════════════════╣
║ DECISION RULES ║
║ Simple task? → Haiku ║
║ Hard reasoning? → Opus ║
║ Everything else? → Sonnet ║
║ Must always run? → Hook (not prompt) ║
║ Auto-apply wisdom? → Skill (not command) ║
║ Needs isolation? → Subagent ║
╚═══════════════════════════════════════════════════════════════╝
Changelog
This reference is a living document. Updates are applied as Claude Code evolves.
| Date | Change | Source |
|---|---|---|
| 2026-01-29 | Added: v2.1.25—fixed beta header validation error for Bedrock and Vertex gateway users. Workaround: CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1. |
80 |
| 2026-01-28 | Added: v2.1.23—spinnerVerbs setting for customizable spinner text, mTLS/proxy connectivity fix for corporate environments, per-user temp directory isolation, ripgrep timeout error reporting (was silently returning empty results), merged PR purple status indicator in prompt footer, bash timeout duration display. Fixes: prompt caching race condition, pending async hooks not cancelled in headless mode, tab completion not updating input, Bedrock region display in headless mode. |
76 |
| 2026-01-28 | Added: v2.1.22—fixed structured outputs for non-interactive (-p) mode. |
75 |
| 2026-01-28 | Added: v2.1.21—Python venv auto-activation in VSCode (claudeCode.usePythonEnvironment setting), Japanese IME full-width (zenkaku) number input support, Read/search progress indicators (“Reading…” → “Read”), Claude now prefers file operation tools over bash equivalents. Fixes: shell completion cache truncation on exit, API errors when resuming sessions interrupted during tool execution, auto-compact triggering too early on models with large output limits, task ID reuse after deletion, Windows file search in VSCode. |
74 |
| 2026-01-28 | Added: MCP Apps (interactive tool UIs inside Claude for Asana, Figma, Slack, etc.). Code Execution Tool v2 (Bash execution replacing Python-only, programmatic tool calling). Claude Code on the web expanded to Team/Enterprise premium seats. | 737879 |
| 2026-01-27 | Added: v2.1.20—--add-dir flag for loading CLAUDE.md from additional directories (requires CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1), PR review status indicator in prompt footer (colored dot showing approved/changes requested/pending/draft), task deletion via TaskUpdate tool, vim arrow key history navigation, /copy command available to all users, timestamped config backups (rotated, keeping 5 most recent). Fixes: session compaction loading full history on resume, agents ignoring user messages while working, wide character (emoji/CJK) rendering artifacts, JSON parsing with Unicode in MCP responses. |
72 |
| 2026-01-26 | Enhanced: Analytics API section with detailed endpoint documentation, metrics table, curl example, and limitations. Now includes authentication requirements, available metrics (productivity, tool usage, cost), and real-time monitoring alternatives. | 53 |
| 2026-01-24 | Added: v2.1.19—$0, $1 shorthand for custom command arguments (changed from $ARGUMENTS.0 to $ARGUMENTS[0] bracket syntax), CLAUDE_CODE_ENABLE_TASKS env var to disable new task system, skills without additional permissions/hooks no longer require approval. VSCode: session forking and rewind enabled for all users. SDK: queued_command replay as SDKUserMessageReplay events. Fixes: dangling processes on terminal close, /rename//tag in git worktrees, pasted text lost with prompt stash (Ctrl+S), agent model display, backgrounded hook commands not returning early, file write preview omitting empty lines. |
71 |
| 2026-01-24 | Added: v2.1.17—fixed crashes on processors without AVX instruction support. | 71 |
| 2026-01-24 | Breaking: Extended thinking now enabled by default with 31,999 tokens. Natural language triggers (think, think hard, ultrathink) are deprecated and no longer allocate thinking tokens—use MAX_THINKING_TOKENS env var or /config instead. Updated Extended Thinking section with current behavior. |
70 |
| 2026-01-24 | Added: v2.1.18—customizable keyboard shortcuts with context-specific keybindings, chord sequences, and full personalization via /keybindings command. Configuration stored in ~/.claude/keybindings.json. |
77 |
| 2026-01-24 | Added: v2.1.16—task management system with dependency tracking, VSCode native plugin management support, OAuth users can browse/resume remote sessions from Sessions dialog. Fixes: out-of-memory crashes with subagent resumption, /compact warning visibility, session titles language setting, Windows IDE race condition. |
69 |
| 2026-01-21 | Added: v2.1.15—npm installation deprecation notice (native binary preferred), React Compiler UI performance improvements. Fixes: /compact warning not clearing, MCP stdio server timeout not killing child process (could cause UI freezes). |
68 |
| 2026-01-20 | Added: v2.1.14—history-based autocomplete in bash mode (! + Tab), plugin search in installed list, pin plugins to git commit SHAs, VSCode /usage command. Critical fixes: context window blocking limit (~65%→~98%), memory crashes with parallel subagents, memory leak in long sessions, @ symbol file autocomplete in bash mode, /feedback invalid URLs, /context token count display, slash command autocomplete wrong selection. |
67 |
| 2026-01-20 | Added: v2.1.12 (message rendering bug fix). Corrected Setup hook version to v2.1.10 with full release notes: ‘c’ keyboard shortcut for OAuth URL copy, improved startup keystroke capture, file suggestions as removable attachments, VSCode plugin install counts and trust warnings. Added teleport one-way limitation note. | 66 |
| 2026-01-19 | Documentation refresh: Added SubagentStart hook to events table, expanded additionalContext documentation for PreToolUse hooks (v2.1.9), expanded LSP tool capabilities section, enhanced People to Follow with content creators and official resources. |
— |
| 2026-01-19 | Added: Setup hook event (v2.1.10)—triggered via --init, --init-only, or --maintenance CLI flags for environment setup tasks. |
60 |
| 2026-01-18 | Added: Multiple Accounts Policy section (what’s allowed, technical limits, what’s prohibited). Added Community Tips section (plan mode auto-clear context, /clear, screenshots, container patterns). Added People to Follow (Boris Cherny, Thariq, Jeffrey Emanuel). Added API token pricing table. | 56575859 |
| 2026-01-17 | Added: v2.1.11 release—fixes excessive MCP connection requests for HTTP/SSE transports (stability improvement for heavy MCP users). | 55 |
| 2026-01-16 | Added: MCP Tool Search section with benchmarks (Opus 4: 49%→74%, Opus 4.5: 79.5%→88.1%, 85% token overhead reduction). Updated MCP ecosystem stats (100M monthly downloads, 3,000+ servers). | 54 |
| 2026-01-16 | Added: Claude Code Analytics API section—programmatic access to usage metrics (sessions, commits, PRs, lines of code) for Team/Enterprise via Admin API endpoint /v1/organizations/usage_report/claude_code. Documented ${CLAUDE_SESSION_ID} skill substitution (v2.1.9). |
5153 |
| 2026-01-15 | Added: v2.1.9 auto:N syntax for MCP tool search threshold, plansDirectory setting, external editor (Ctrl+G) in AskUserQuestion, session URL attribution for web session commits/PRs, PreToolUse hooks additionalContext. Fixed parallel tool calls API errors, MCP reconnection hanging, Ctrl+Z in Kitty. Added Cowork (GUI version for non-technical users). |
5152 |
| 2026-01-15 | Added: v2.1.7 permission feedback feature (provide feedback when accepting permission prompts). GitHub Action v1.0 GA release. Minor documentation refresh. | 48 |
| 2026-01-14 | Added: v2.1.7 MCP tool search auto mode enabled by default (defers tools >10% context), showTurnDuration setting, inline agent response in task notifications, security fix for wildcard permissions matching compound commands. v2.1.6: /config search, /doctor Updates section, /stats date range filtering, nested .claude/skills discovery, context_window.used_percentage/remaining_percentage fields, security fix for shell line continuation permission bypass. v2.1.5: CLAUDE_CODE_TMPDIR env var. |
484950 |
| 2026-01-13 | Added: URL change from console.anthropic.com to platform.claude.com (v2.1.4). Added context: fork skill frontmatter option for isolated contexts. Added permission denial resilience for subagents (v2.1.0+). Added plugin marketplace launch info (36 curated plugins Dec 2025). |
47 |
| 2026-01-12 | Added: v2.1.4 CLAUDE_CODE_DISABLE_BACKGROUND_TASKS environment variable to disable all background task functionality including auto-backgrounding and Ctrl+B shortcut. Fixed OAuth token refresh for “Help improve Claude” setting. |
46 |
| 2026-01-10 | Added: Sandboxing reduces permission prompts by 84% (from Anthropic engineering blog), Opus 4.5 SWE-bench performance (80.9%) and token efficiency improvements. Minor documentation refresh. | 45 |
| 2026-01-10 | Added: v2.1.3 merged slash commands and skills (unified mental model), release channel toggle (stable/latest) in /config, /doctor detects unreachable permission rules, hook execution timeout increased from 60s to 10 minutes. Bug fixes: plan files persisting across /clear, skill duplicate detection on ExFAT, background task count mismatch, sub-agents using wrong model during compaction. VSCode: clickable destination selector for permissions. |
44 |
| 2026-01-09 | Added: v2.1.1 (109 CLI refinements), Component-Scoped Hooks (hooks in skill/command frontmatter with once option), new MCP servers (Figma Dev Mode, Sequential Thinking, Magic UI, Context7). Updated MCP ecosystem count to 3,000+ servers. |
414243 |
| 2026-01-08 | Added: language and respectGitignore settings to settings.json reference. Added IS_DEMO env var. Updated multiline input to show Shift+Enter works out-of-box in iTerm2/WezTerm/Ghostty/Kitty. Added 1,550 free code execution hours per org/month. |
3740 |
| 2026-01-08 | Added: v2.1.2 clickable file paths in tool output (OSC 8 for iTerm), Windows Package Manager (winget) support, Shift+Tab for “auto-accept edits” in plan mode, FORCE_AUTOUPDATE_PLUGINS env var, agent_type field in SessionStart hook. Security fixes: command injection in bash processing, memory leak from tree-sitter. Updated thinking toggle to Alt+T. Added MCP wildcard permission syntax (mcp__server__*). Added PreToolUse hooks updatedInput with ask permission. |
39 |
| 2026-01-07 | Added: v2.1.0 automatic skill hot-reload (skills in ~/.claude/skills or .claude/skills immediately available without restart). Security: CVE-2025-52882 WebSocket authentication bypass patched in IDE extensions v1.0.24+ |
3738 |
| 2026-01-06 | Added: v2.0.74 clickable image links ([Image #N]), /context grouped display, file @ mentions 3x faster in git repos, .ignore and .rgignore support, Claude Agent SDK v0.1.74 |
343536 |
| 2025-12-28 | Added: Named sessions (/rename, /resume <n>), plugin discover search filtering, --fork-session with custom session IDs, Agent Skills section, async subagents, Claude Agent SDK (renamed from Claude Code SDK), Alt+Y yank-pop, Alt+T thinking toggle, Ctrl+T syntax highlighting toggle, holiday promotion (2× limits Dec 25-31) |
2930313233 |
| 2025-12-24 | Added: Claude in Chrome section, Claude Code in Slack section, LSP tool, remote MCP OAuth support, ‘ultrathink’ command, /theme and /plugin commands, terminal support for Kitty/Alacritty/Zed/Warp |
232425262728 |
| 2025-12-14 | Added: Pro users Opus 4.5 access, subscription plans table, rate limits (August 2025), iOS app availability | 202122 |
| 2025-12-12 | Added: Background Agents section, Output Styles section, hidden tool fees, /stats, /fork, /rename, /statusline, /tasks commands, .claude/rules/ memory directory, Batch API tip |
16171819 |
| 2025-12-12 | Added: Slack integration, prompt suggestions, Alt+P model switching, /release-notes command, /rewind command, interactive MCP setup wizard |
131415 |
| 2025-12-12 | Initial 10.0 version: Architecture mental model, decision frameworks, anti-patterns, workflow recipes, migration guide, quick reference card | — |
Run /update-cc-guide to scan for and apply the latest Claude Code updates.
References
-
Anthropic Pricing. “Claude API Pricing.” December 2025. ↩
-
Claude Code Subagents. “Subagents Documentation.” December 2025. ↩
-
MCPcat. “MCP Server Downloads Growth Statistics.” December 2025. ↩
-
Anthropic. “Building Agents with Claude Agent SDK.” December 2025. ↩
-
Claude Code CHANGELOG. “Prompt suggestions: Claude now suggests what you might want to do next.” December 16, 2025. See also TechCrunch for December 2025 feature coverage. ↩↩
-
Northflank. “Claude Code Hidden Tool Fees.” July 2025. ↩↩
-
Claude Code Docs. “Memory Rules Directory.” December 2025. ↩↩
-
GitHub CHANGELOG. “Pro users now have access to Opus 4.5 as part of their subscription.” December 2025. ↩↩↩
-
Northflank. “Rate Limit Changes August 2025.” July 2025. ↩↩
-
Claude Blog. “Claude Code on the Web and iOS App.” November 2025. ↩↩
-
Claude Blog. “Claude Code on the Web for Team and Enterprise Users.” November 2025. ↩
-
GitHub Releases. “Claude in Chrome (Beta) feature.” December 2025. ↩↩
-
GitHub Releases. “LSP tool and terminal support updates (v2.0.74).” December 2025. ↩↩↩
-
TechCrunch. “Claude Code in Slack announcement.” December 2025. ↩↩
-
GitHub Releases. “Thinking mode triggers: think, think harder, ultrathink.” December 2025. ↩
-
GitHub Releases. “Named sessions with /rename and /resume.” December 2025. ↩
-
GitHub Releases. “Plugin discover search filtering, custom session IDs with –fork-session (v2.0.73-74).” December 2025. ↩
-
Anthropic Engineering. “Agent Skills: reusable task-specific modules.” December 2025. ↩↩
-
Anthropic Engineering. “Claude Agent SDK (renamed from Claude Code SDK).” December 2025. ↩↩
-
Apidog. “Claude Code 2× usage limits for Pro/Max subscribers Dec 25-31, 2025.” December 2025. ↩
-
GitHub Releases. “v2.0.73-74: Clickable image links,
/contextgrouped display,ctrl+tsyntax highlighting toggle.” January 2026. ↩↩ -
GitHub Releases. “v2.0.72: @ mention file suggestions 3x faster in git repos,
.ignoreand.rgignorefile support.” January 2026. ↩↩ -
GitHub Claude Agent SDK. “Claude Agent SDK v0.1.74 in parity with Claude Code v2.0.74.” January 2026. ↩
-
GitHub Releases. “v2.1.0: Automatic skill hot-reload,
languagesetting for response language,respectGitignorein settings.json,IS_DEMOenv var, Shift+Enter works out-of-box in iTerm2/WezTerm/Ghostty/Kitty.” January 2026. ↩↩↩ -
Datadog Security Labs. “CVE-2025-52882: WebSocket authentication bypass in Claude Code IDE extensions patched in v1.0.24+.” January 2026. ↩↩
-
GitHub Releases. “v2.1.2: Clickable file paths (OSC 8), winget support, Shift+Tab auto-accept in plan mode, FORCE_AUTOUPDATE_PLUGINS, agent_type in SessionStart hook, security fixes (command injection, memory leak), thinking toggle changed to Alt+T, MCP wildcard permissions, PreToolUse updatedInput with ask.” January 2026. ↩↩↩↩
-
Anthropic Pricing. “Each organization receives 1,550 free hours of usage with the code execution tool per month.” January 2026. ↩↩
-
VentureBeat. “Claude Code 2.1.0 introduces infrastructure-level features. Hooks for agents, skills, and slash commands with scoped PreToolUse, PostToolUse, and Stop logic.” January 2026. Medium. “Claude Code 2.1.1 shipped with 109 CLI refinements.” ↩↩
-
Builder.io. “Figma’s official Dev Mode MCP server exposes the live structure of the layer you have selected—hierarchy, auto‑layout, variants, text styles, and token references.” December 2025. ↩↩
-
Apidog. “Sequential Thinking MCP server enables Claude to methodically work through problems with structured, reflective thinking process.” January 2026. MCP.so. “Over 3,000 MCP servers indexed.” ↩↩
-
GitHub Releases. “v2.1.3: Merged slash commands and skills, release channel toggle in /config, /doctor unreachable permission detection, hook timeout increased to 10 minutes.” January 2026. ↩
-
Anthropic. “Sandboxing safely reduces permission prompts by 84%.” January 2026. Anthropic. “Claude Opus 4.5 achieves 80.9% on SWE-bench Verified while cutting token usage in half.” ↩↩↩
-
GitHub Releases. “v2.1.4: Added CLAUDE_CODE_DISABLE_BACKGROUND_TASKS environment variable, fixed OAuth token refresh for ‘Help improve Claude’ setting.” January 2026. ↩
-
VentureBeat. “Claude Code 2.1.0: Forked sub-agent context via
context: forkin skill frontmatter, agents continue after permission denial.” January 2026. GitHub ykdojo/claude-code-tips. “Anthropic officially launched the plugin marketplace in December 2025 with 36 curated plugins.” ↩↩↩↩ -
GitHub Releases. “v2.1.7: MCP tool search auto mode enabled by default, showTurnDuration setting, inline agent response in task notifications, security fix for wildcard permissions.” January 2026. ↩↩
-
GitHub Releases. “v2.1.6: /config search, /doctor Updates section, /stats date range filtering, nested skills discovery, context_window percentage fields, shell line continuation security fix.” January 2026. ↩
-
GitHub Releases. “v2.1.5: CLAUDE_CODE_TMPDIR environment variable to override temp directory.” January 2026. ↩
-
GitHub Releases. “v2.1.9: Added auto:N syntax for MCP tool search threshold, plansDirectory setting, external editor (Ctrl+G) in AskUserQuestion, session URL attribution to commits/PRs, PreToolUse hooks additionalContext. Fixed parallel tool calls API errors, MCP reconnection hanging, Ctrl+Z in Kitty.” January 2026. ↩↩↩↩
-
Wikipedia. “A version called ‘Cowork’ with a graphical user interface, aimed at non-technical users, [launched] in January 2026.” January 2026. ↩
-
Claude Docs. “Programmatically access your organization’s Claude Code usage analytics and productivity metrics with the Claude Code Analytics Admin API.” January 2026. ↩↩↩
-
VentureBeat. “MCP Tool Search: Opus 4 accuracy improved from 49% to 74%, Opus 4.5 from 79.5% to 88.1%. Boris Cherny: ‘Every Claude Code user just got way more context.’” January 2026. Anthropic. “MCP has reached 100M monthly downloads and become the industry standard.” January 2026. ↩↩↩
-
Claude Code v2.1.11 release notes. “Fixed excessive MCP connection requests for HTTP/SSE transports.” January 17, 2026. ↩
-
Medium. “Boris Cherny: 259 PRs, 497 commits, 40k lines added, 38k removed in 30 days using Claude Code.” January 2026. ↩↩
-
Anthropic Pricing. “API Token Pricing: Haiku 4.5 ($1/$5), Sonnet 4/4.5 ($3/$15), Opus 4 ($15/$75), Opus 4.5 ($5/$25).” January 2026. ↩↩
-
GitHub ykdojo/claude-code-tips. “Community tips collection: plan mode, /clear often, screenshots, GitHub app for PRs.” January 2026. ↩↩
-
Anthropic Usage Policy. Multiple accounts policy. Anthropic Support. “You can verify up to three accounts with the same phone number. Multiple paid subscriptions from the same network are supported.” January 2026. ↩↩
-
GitHub Releases. “v2.1.10: Added Setup hook event triggered via –init, –init-only, or –maintenance CLI flags; ‘c’ keyboard shortcut to copy OAuth URL during login; improved startup keystroke capture; file suggestions as removable attachments; VSCode plugin install counts and trust warnings.” January 17, 2026. ↩
-
@adocomplete. “Day 15 of Advent of Claude: –dangerously-skip-permissions flag (YOLO mode) for fully autonomous operation.” January 2026. ↩
-
@adocomplete. “Claude Max subscribers get 3 guest passes to share Claude Code Pro trial with others via /passes command.” January 2026. ↩
-
@mattpocockuk. “Docker sandbox mode for safe exploration of untrusted codebases.” January 2026. ↩
-
Daisy Hollman. “Overnight hooks strategy: use linting and testing hooks as guardrails to keep Claude iterating until tests pass.” January 2026. ↩
-
@moofeez. “Claude Squad: Multi-agent manager for parallel Claude Code instances in isolated worktrees.” January 2026. ↩
-
GitHub Releases. “v2.1.12: Fixed message rendering bug.” January 17, 2026. ↩
-
GitHub Releases. “v2.1.14: History-based autocomplete in bash mode, plugin search, pin plugins to git SHAs, VSCode /usage command. Fixes: context window blocking limit (~65%→~98%), memory crashes with parallel subagents, memory leak in long sessions, @ symbol file autocomplete, /feedback URLs, /context token count, slash command autocomplete.” January 20, 2026. ↩
-
GitHub Releases. “v2.1.15: npm installation deprecation notice, React Compiler UI performance improvements. Fixes: /compact warning persistence, MCP stdio server timeout not killing child process (UI freeze fix).” January 21, 2026. ↩
-
GitHub Releases. “v2.1.16: Task management system with dependency tracking, VSCode native plugin management, OAuth users can browse/resume remote sessions. Fixes: OOM crashes with subagent resumption, /compact warning visibility, session titles language, Windows IDE race condition.” January 22, 2026. ↩
-
GitHub Issues. “Ultrathink is deprecated. Thinking mode is enabled by default with 31,999 tokens. Keywords like ‘think’, ‘think hard’, ‘ultrathink’ no longer allocate thinking tokens—use MAX_THINKING_TOKENS env var instead.” January 2026. Decode Claude. “UltraThink is Dead. Long Live Extended Thinking.” ↩↩↩
-
GitHub Releases. “v2.1.19: $0/$1 shorthand for custom command arguments, CLAUDE_CODE_ENABLE_TASKS env var, VSCode session forking/rewind for all users. v2.1.17: Fixed crashes on processors without AVX instruction support.” January 23-24, 2026. ↩↩
-
Claude Code Docs. “v2.1.20: –add-dir flag for loading CLAUDE.md from additional directories, PR review status indicator, task deletion via TaskUpdate, vim arrow key history navigation, /copy command for all users, timestamped config backups. Fixes: session compaction issues, agents ignoring user messages, wide character rendering, JSON parsing with Unicode.” January 27, 2026. ↩
-
Anthropic. “Claude Code on the web is now available in research preview for Team and Enterprise users with premium seats, in addition to Pro and Max users.” January 26, 2026. ↩↩
-
GitHub Releases. “v2.1.21: Japanese IME full-width number input, Python venv auto-activation in VSCode (claudeCode.usePythonEnvironment), Read/search progress indicators, Claude prefers file tools over bash. Fixes: shell completion cache, session resume API errors, auto-compact timing, task ID reuse, Windows file search.” January 27, 2026. ↩
-
GitHub Releases. “v2.1.22: Fixed structured outputs for non-interactive (-p) mode.” January 27, 2026. ↩
-
GitHub Releases. “v2.1.23: spinnerVerbs setting, mTLS/proxy connectivity fix, per-user temp directory isolation, ripgrep timeout reporting, merged PR purple indicator, bash timeout display. Fixes: prompt caching race condition, async hooks in headless, tab completion, Bedrock region strings.” January 28, 2026. ↩
-
Claude Code Docs. “v2.1.18: Customizable keyboard shortcuts with context-specific keybindings, chord sequences, and personalization. Run /keybindings to configure.” January 22, 2026. ↩↩
-
Help Net Security. “Anthropic added interactive tool support (MCP Apps) to Claude, enabling users to interact with Asana, Box, Canva, Figma, Hex, monday.com, and Slack directly inside the Claude interface.” January 26, 2026. ↩↩
-
Anthropic Developer Platform. “Code Execution Tool v2 public beta: Bash command execution, file manipulation, and programmatic tool calling from within code execution.” January 2026. ↩↩
-
GitHub Releases. “v2.1.25: Fixed beta header validation error for gateway users on Bedrock and Vertex. Workaround: CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1.” January 29, 2026. ↩