Back to Blog

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 CLI: The Definitive Technical Reference

Updated December 12, 2025

December 2025 Update: Claude Code now powers enterprise engineering workflows with agentic multi-file editing, MCP protocol integration with 300+ external services, specialized subagents for complex tasks, and hooks system for CI/CD automation. Permission system enables fine-grained security controls. Model switching between Haiku (fast/cheap) and Opus (powerful) optimizes cost-performance tradeoffs.

I've 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. It covers everything from first installation to advanced patterns that most users never discover.

Claude Code isn't a chat interface that happens to know about programming. It's an agentic system that reads your codebase, executes commands, modifies files, manages git workflows, connects to external services, and delegates complex tasks to specialized subagents—all through a command-line interface that integrates into how developers actually work.

The difference between using Claude Code casually and using it effectively is understanding its architecture: the configuration hierarchy that controls behavior, the permission system that gates operations, the hook system that enables deterministic automation, the MCP protocol that extends capabilities, and the subagent system that handles complex multi-step tasks. Master these systems and Claude Code becomes a force multiplier. Miss them and you're leaving most of the value on the table.

This guide assumes you're comfortable with command-line tools and want the complete picture. Every feature is documented with actual syntax, real configuration examples, and the edge cases that trip up experienced users. Whether you're setting up your first project or deploying across an enterprise engineering organization, the information is here.


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

  1. Installation and Authentication
  2. Core Interaction Modes
  3. Configuration System Deep Dive
  4. Model Selection and Switching
  5. Permission System and Security
  6. Hooks System
  7. MCP (Model Context Protocol)
  8. Subagents and Task Delegation
  9. Extended Thinking Mode
  10. Output Styles
  11. Slash Commands
  12. Skills
  13. Plugin System
  14. Memory and Context Management
  15. Image and Multimodal Input
  16. Git Integration and Workflows
  17. IDE Integration
  18. Advanced Usage Patterns
  19. Claude Code Remote
  20. Background Agents
  21. Cost Management and Billing
  22. Performance Optimization
  23. Troubleshooting and Debugging
  24. Enterprise Deployment
  25. Keyboard Shortcuts Reference
  26. Best Practices

Installation and Authentication

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

For environments where npm is preferred:

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 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.


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"
}

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

Debugging:

ANTHROPIC_LOG=debug                             # Enable API request logging

Model Selection and Switching

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.

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.


Permission System and Security

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

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

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"
  ],
  "deny": [
    "mcp__dangerous_server"
  ]
}

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.


Hooks System

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
SubagentStop Subagent completes No Task tracking
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"
    }
  }
}

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)


MCP (Model Context Protocol)

MCP extends Claude Code with access to external tools, databases, APIs, and services through a standardized protocol. The ecosystem has grown from 100,000 total downloads in November 2024 to over 8 million by April 2025—80x growth in five months.3 Over 300 integrations exist, from GitHub and Slack to PostgreSQL and custom internal systems. 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.

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
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

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.


Subagents and Task Delegation

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:

  1. Starts with a clean context (no pollution from main conversation)
  2. Has access to specified tools
  3. Operates with a specific model (often cheaper/faster)
  4. 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

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.

Supported Models

  • Claude Opus 4.5
  • Claude Sonnet 4.5
  • Claude Haiku 4.5

Enabling Extended Thinking

Quick toggle during session:

Press Tab to toggle thinking on/off

Via prompts:

> think deeply about the architecture for this feature
> think hard about what's causing this bug

Environment variable (permanent):

export MAX_THINKING_TOKENS=10000
claude

Thinking Token Budgets

Budget Use Case
1,024 (minimum) Simple reasoning tasks
4,000-8,000 Most complex coding tasks
16,000+ Very complex architecture, deep debugging
32,000+ Exhaustive analysis (consider batch processing)

Expert tip: Start with the minimum budget and increase only if Claude's responses seem rushed. Higher budgets cost more and aren't always better—they can lead to overthinking simple problems.

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 Use Extended Thinking

Enable for: - Architectural decisions - Complex debugging - Security analysis - Performance optimization - Understanding unfamiliar codebases

Skip for: - Simple file edits - Routine refactoring - Quick questions - Code formatting

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
/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 Shift+Enter setup
/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)

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).


Skills

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

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 logic
  • src/payments/refunds.ts - Refund handling
  • src/compliance/aml.ts - AML checks
  • src/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:

  1. 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...

  2. Verify file location: ```bash # Personal ls ~/.claude/skills/my-skill/SKILL.md

# Project ls .claude/skills/my-skill/SKILL.md ```

  1. Validate YAML frontmatter:
  2. First line must be exactly ---
  3. Closing --- before markdown content
  4. No tabs in YAML (use spaces)
  5. Name field is lowercase with hyphens only

  6. 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.

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 /agents list
  • Skills: Auto-load based on skill config
  • Hooks: Merged with user/project hooks, run in parallel
  • MCP Servers: Auto-start when plugin enabled

Memory and Context Management

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

  1. Use specific file references instead of asking Claude to search
  2. Clear unrelated conversations with /clear between tasks
  3. Compact proactively during long sessions
  4. Use subagents to isolate exploratory work
  5. Break complex tasks into focused interactions
  6. 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

  1. Drag and drop: Drag image files into the Claude Code window
  2. Paste: Ctrl+V (not Cmd+V on Mac) to paste from clipboard
  3. Path reference: "Analyze this image: /path/to/screenshot.png"

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.


Git Integration and Workflows

Claude Code has deep git integration with built-in safety protocols.

Safety Protocols

  • Respects .gitignore automatically
  • 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'

IDE Integration

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

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"

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 requires a Claude Max subscription. 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.

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—represents where agentic coding is headed: AI that works for you around the clock, not just when you're at your keyboard.


Background Agents (December 2025)

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.


Cost Management and Billing

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

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 Billed separately from tokens
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

  1. Use Haiku for subagents: Most exploration doesn't need Sonnet
  2. Enable prompt caching: Default, but verify it's not disabled
  3. Set max turns: claude --max-turns 5 prevents runaway conversations
  4. Use plan mode for exploration: No execution = no accidental expensive operations
  5. Compact proactively: Smaller context = fewer tokens
  6. Limit output: export CLAUDE_CODE_MAX_OUTPUT_TOKENS=2000
  7. Batch API for non-urgent work: 50% off both input and output tokens

Monitoring Usage

  • Claude Console: console.anthropic.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.


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.ts instead of "find the auth file"
  • Targeted searches: "search in src/api" not "search everywhere"
  • Fresh sessions: /clear between unrelated tasks
  • Custom compaction: Add instructions to CLAUDE.md for what to preserve

Troubleshooting and Debugging

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

  1. Start with documentation: Get CLAUDE.md right before deploying
  2. Pilot group: Begin with 5-10 developers
  3. Q&A phase: Let pilots use Claude for code exploration
  4. Guided development: Progress to small bug fixes
  5. Full deployment: Roll out with managed settings
  6. 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

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
Esc Esc Rewind last change
Tab Accept prompt suggestion / Toggle extended thinking
Shift+Tab Cycle permission modes
Alt+P / Option+P Switch models while typing prompt
Up/Down Navigate command history
? Show shortcuts

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
After setup Shift+Enter (run /terminal-setup)
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

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 /cost regularly
  • Use Haiku for simple tasks and subagents
  • Set MAX_THINKING_TOKENS only when needed
  • Use --max-turns for automated scripts
  • Compact proactively in long sessions

Security

  • Configure .claude/settings.json deny rules for sensitive files
  • Use sandbox mode for untrusted projects
  • Never allow Bash(rm -rf:*) or Bash(sudo:*)
  • Use hooks to block access to secrets
  • Deploy managed settings for enterprise

Enterprise teams deploying Claude Code at scale benefit from standardized configuration, managed policies, and integrated tooling. Teams at Introl help organizations implement AI development infrastructure across distributed engineering teams, from initial architecture through production deployment.


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

  1. Stop copying code. Claude Code writes to files directly.
  2. Stop context-switching. MCP brings external tools into the session.
  3. Delegate aggressively. Subagents handle exploration without bloating your context.
  4. Automate with hooks. Formatting, linting, logging happen automatically.
  5. 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
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


For enterprise AI development infrastructure and Claude Code deployment support, contact Introl.


  1. Anthropic Pricing. "Claude API Pricing." December 2025. 

  2. Claude Code Subagents. "Subagents Documentation." December 2025. 

  3. MCPcat. "MCP Server Downloads Growth Statistics." December 2025. 

  4. Anthropic. "Claude Code Documentation." December 2025. 

  5. Anthropic. "CLI Reference." December 2025. 

  6. Anthropic. "Settings Documentation." December 2025. 

  7. Anthropic. "Hooks Guide." December 2025. 

  8. Anthropic. "MCP Documentation." December 2025. 

  9. Anthropic. "Claude Code Best Practices." December 2025. 

  10. Anthropic. "Remote MCP Support." December 2025. 

  11. Anthropic. "Building Agents with Claude Agent SDK." December 2025. 

  12. GitHub. "Claude Code GitHub Action." December 2025. 

  13. Anthropic. "Claude Code Announcement." December 2025. 

  14. Anthropic. "Claude Slack Integration." December 2025. 

  15. Anthropic. "Interactive MCP Setup." December 2025. 

  16. Northflank. "Claude Code Hidden Tool Fees." December 2025. 

  17. Anthropic. "Background Agents." December 2025. 

  18. Claude Code Docs. "Memory Rules Directory." December 2025. 

  19. GitHub. "Output Styles Release." December 2025. 

Request a Quote_

Tell us about your project and we'll respond within 72 hours.

> TRANSMISSION_COMPLETE

Request Received_

Thank you for your inquiry. Our team will review your request and respond within 72 hours.

QUEUED FOR PROCESSING