Field Manual
Claude Code
DOC-CC-2026 · v2
Practitioner Field Handbook · Updated July 20, 2026

Claude Code
Practitioner's Handbook

A field-tested reference covering every major surface of Claude Code as of mid-2026 — model selection, effort levels and ultracode, the five permission modes, CLAUDE.md authoring, Agent Skills, subagents and dynamic workflows, hooks, MCP, the Agent SDK, and routing to local/open-weight models.

Claude Code v2.1.215 Sonnet 5 · Opus 4.8 · Fable 5 · Haiku 4.5 Ollama · GLM-5.2 · Kimi K2.7 · Qwen3.6 Agent Skills · Dynamic Workflows Auto Mode · /goal
02

What's New in v2

// SUMMARY OF CHANGES SINCE THE MAY 2026 EDITION

This edition replaces the v1 handbook (May 25, 2026). Claude Code shipped roughly 175 releases between then and now — the highlights below are the ones that change how you should actually use the tool day-to-day.

New Model Lineup

Sonnet 5 is now the default for new sessions (native 1M context). Opus 4.8 sits above it; Claude Fable 5 sits above Opus as the most capable model available in Claude Code, for long-horizon autonomous work. Opus 4.7/4.6 and Haiku 4.5 remain available.

Effort Levels Replace Fixed Thinking Budgets

Sonnet 5, Opus 4.8, and Fable 5 use adaptive reasoning (low / medium / high / xhigh / max / ultracode) instead of manually-set thinking-token budgets. "think harder" style keywords still work as prompt-level nudges, but /effort is now the primary control.

Dynamic Workflows & Ultracode

Opus 4.8 introduced background orchestration scripts that fan a task across tens to hundreds of subagents automatically. The ultracode keyword (or /effort ultracode) turns this on — see §19.

Auto Mode, Then Manual-by-Default Again

Auto mode (classifier-gated autonomy) launched in March 2026 as a safer alternative to --dangerously-skip-permissions. As of v2.1.200 (July 3, 2026) Claude Code reverted its default permission mode back to manual approval everywhere — auto mode is still available, just opt-in. See §09.

Agent Skills & Plugin Marketplace

Skills (SKILL.md) are now distributed as installable plugins via /plugin marketplace add and /plugin install, with an official Anthropic marketplace plus dozens of community ones. See §13–14.

/goal — Run-Until-Verified Loops

A native loop-engineering primitive: give Claude a verifiable end condition and a budget, and it iterates — spawning subagents, running tests, re-checking — until a separate evaluator confirms the condition holds or the budget runs out. See §20.

Version pinned in this handbook: Claude Code v2.1.215 (July 19, 2026), release #348. Run claude --version to check yours, and claude update to catch up — Claude Code ships new releases almost daily.
03

Install & Setup

// CLI, AUTH, IDE SURFACES
# Requires Node.js 18+
npm install -g @anthropic-ai/claude-code
claude --version

# Auth — browser OAuth (recommended) or API key
claude                              # opens browser auth on first run
export ANTHROPIC_API_KEY=sk-ant-...
claude --api-key $ANTHROPIC_API_KEY

# Update — Claude Code ships near-daily; update often
claude update                       # or: npm update -g @anthropic-ai/claude-code

# Run diagnostics
claude /doctor

# Fresh troubleshooting session — disables every customization
claude --safe-mode                  # or CLAUDE_CODE_SAFE_MODE=1
💡
Managed / org rollouts: Enterprise and Team admins set an org-wide default model and permission policy via managed settings or MDM policy; it shows as "Org default" in /model (v2.1.196+) and cannot be overridden by users unless the policy allows it.

IDE Integrations

SurfaceHow to activateNotes
VS CodeInstall Claude Code extension, Ctrl+Shift+CInline diffs, native diagnostics panel
JetBrainsPlugin marketplace → "Claude Code"IntelliJ, PyCharm, WebStorm, GoLand
Terminalclaude in any directoryPrimary surface; full feature set first
GitHub Actionsuses: anthropic/claude-code-actionSee §23
Agent View (dashboard)claude agentsResearch preview — monitor running / blocked / completed background sessions; --cwd <path> scopes to a directory
Web / Desktopclaude.ai → Claude Code tabRemote sessions from mobile too
04

Model Selection

// FABLE 5 · OPUS 4.8 · SONNET 5 · HAIKU 4.5

Switch at any time with /model. As of v2.1.197 (June 30, 2026), Sonnet 5 is the default model for new sessions on all surfaces, with native 1M-token context at standard pricing.

ModelBest forSpeedCost
Fable 5 The most capable model available in Claude Code — long-horizon autonomous sessions, investigates before acting, verifies its own work more often than smaller models. Reserve for hard, multi-hour agentic runs. Slowest $$$$
Opus 4.8 Complex architecture, multi-file refactors, security review, dynamic-workflow orchestration. Defaults to high effort; supports xhigh and ultracode. Slow $$$
Sonnet 5 Default daily driver — near-Opus quality on coding/agentic work at Sonnet-tier speed and cost. Introductory pricing $2/$10 per Mtok through Aug 31, 2026. Fast $$
Haiku 4.5 Explore subagents, CI lint checks, quick file scans, cost-sensitive batch/background tasks. ~90% of Opus capability at a fraction of the cost. Fastest $
# Switch models interactively
/model

# Shorthand (recommended)
/model opus
/model sonnet
/model haiku
/model fable

# Full model IDs — CLI flags
claude --model claude-fable-5
claude --model claude-opus-4-8
claude --model claude-opus-4-7
claude --model claude-sonnet-5
claude --model claude-sonnet-4-6
claude --model claude-haiku-4-5-20251001

# Pin explicitly (aliases like `opus` can shift providers/versions over time)
export ANTHROPIC_DEFAULT_OPUS_MODEL=claude-opus-4-8
export ANTHROPIC_DEFAULT_SONNET_MODEL=claude-sonnet-5
ModelModel IDContextMax output
Claude Fable 5claude-fable-51M128K
Claude Opus 4.8claude-opus-4-81M128K
Claude Opus 4.7claude-opus-4-71M128K
Claude Opus 4.6claude-opus-4-61M128K
Claude Sonnet 5claude-sonnet-51M128K
Claude Sonnet 4.6claude-sonnet-4-61M128K
Claude Haiku 4.5claude-haiku-4-5-20251001200K64K
Fable 5 / Mythos 5 access note: Fable 5 and its Mythos-tier sibling first shipped June 9, 2026. Access was briefly suspended June 12–30, 2026 to comply with U.S. export-control review, then restored July 1, 2026. If /model fable ever errors out unexpectedly, check anthropic.com/news for the current access status before assuming a local misconfiguration.
Cost discipline: Defaulting every session to Opus or Fable can burn 3–5× the budget of Sonnet for marginal quality gains on routine work. Reserve Opus 4.8 / Fable 5 for architecture decisions, gnarly debugging, and security review; keep Sonnet 5 as the daily driver; push exploration/lint/batch work to Haiku subagents.
05

Effort Levels & Ultracode

// ADAPTIVE REASONING HAS REPLACED FIXED THINKING BUDGETS

Sonnet 5, Opus 4.8, and Fable 5 use adaptive reasoning — the model decides how much to think per turn within a ceiling you set with /effort. This replaced the old fixed thinking-token-budget model from the Claude 4.5 generation.

LevelPersistenceUse for
lowSessionTrivial edits, quick lookups, chat-style Q&A
mediumSessionRoutine coding, small scoped changes
highSession (default on Opus 4.8)Real feature work, multi-file changes
xhighSessionHard multi-step problems: architecture, tricky debugging, security audits. Only Fable 5, Opus 4.8, and Opus 4.7 support it.
maxSession-onlyHighest single-turn reasoning depth; resets when the session ends
ultracodeSession-onlyxhigh reasoning + automatic Dynamic Workflow orchestration for every substantive task — see below
# Set effort for the whole session
/effort high
/effort xhigh
/effort ultracode

# CLI flag / env var
claude --effort xhigh
export CLAUDE_CODE_EFFORT_LEVEL=high

# Turn thinking off entirely on think-by-default models
export MAX_THINKING_TOKENS=0
claude --thinking disabled

Ultracode — Automatic Multi-Agent Orchestration

Typing the word ultracode anywhere in a prompt triggers that single task to run as a Dynamic Workflow: a background orchestration script that a runtime executes, coordinating up to 16 concurrent subagents, with intermediate results kept in script variables rather than the main context window. Setting /effort ultracode makes this automatic for every substantive task in the session — Claude decides on its own when a request is big enough to fan out, verify with an independent subagent, and merge results.

# One-off: trigger a workflow for this task only
> "ultracode: migrate every route handler in src/api to the new validation middleware"

# Session-wide: every substantive task gets auto-orchestrated
/effort ultracode

# Disable the keyword trigger but keep manual /effort control
# /config → "Ultracode keyword trigger" → off

# Disable workflows entirely
export CLAUDE_CODE_DISABLE_WORKFLOWS=1
# or in settings.json: "disableWorkflows": true
Expensive by design. Ultracode is meant for codebase-wide audits, large migrations, and cross-checked research — not routine edits. Drop back to /effort high for day-to-day work and reserve ultracode for tasks that genuinely need multi-agent orchestration. Switching effort or model mid-session forces a full-price, uncached re-read of the conversation — decide your effort level up front rather than ratcheting it up turn by turn.
06

Extended Thinking — Prompt-Level Nudges

// SUPPLEMENTS EFFORT LEVELS, DOES NOT REPLACE THEM

Trigger phrases like think, think harder, and ultrathink still work as in-context instructions that ask the model to reason more before answering a specific turn. They're a lighter-weight nudge than /effort — useful when you want deeper reasoning on one message without changing the whole session's ceiling.

Trigger phraseScopeWhen to use
thinkThis turnSimple reasoning, quick decision
think harder / think moreThis turnMulti-step problems, debugging
ultrathinkThis turnHard research, novel algorithm design — requests deeper reasoning without spawning extra agents
ultracodeThis task (or session via /effort)Same depth as ultrathink plus automatic subagent orchestration — see §05
The model's raw chain-of-thought is never returned — you see a summary of its reasoning (display: "summarized" in the API). Local/open-weight models generally lack extended-thinking tokens entirely — see §24.
07

Permission Modes — All Five, Explained

// FROM FULLY MANUAL TO "GOD MODE" (BYPASS)

Claude Code ships five permission modes. Cycle between them with Shift+Tab, or set one explicitly with --permission-mode. Protected paths (like .env, credentials, CI secrets) stay protected in every mode except bypass.

ModeFlag / settingBehavior
Default (Manual)defaultEvery file write and Bash command asks for approval. Safest; the out-of-the-box mode again as of v2.1.200 (July 3, 2026).
Accept EditsacceptEditsFile edits auto-approve; Bash and other risky tools still prompt. Good middle ground for refactor sessions.
Plan ModeplanRead-only tools only — no writes at all until you approve a plan. See §08.
Auto ModeautoA classifier grades every tool call before it runs and auto-approves what it judges safe, escalating risky actions for approval. See §09.
Bypass Permissions "god mode"bypassPermissions / --dangerously-skip-permissionsNo prompts, no checks, full autonomy. Offers no protection against prompt injection or unintended destructive actions. Hooks still run and can still block operations even in bypass mode.
# Cycle modes interactively
Shift+Tab

# Set explicitly via CLI flag
claude --permission-mode plan
claude --permission-mode acceptEdits
claude --permission-mode auto
claude --dangerously-skip-permissions    # bypass — use only in disposable containers
Don't reach for bypass casually. The people who call this "god mode" mean it half-jokingly, but the risk is real: an agent with unattended write access and no injection defenses can be steered by malicious content in a file it reads or a web page it fetches. If prompts are annoying you, the answer is Auto Mode (§09), not bypass. Reserve bypass for fully disposable sandboxes/containers with nothing sensitive mounted.
08

Plan Mode

// SPEC FIRST, SAFE EXPLORATION
Plan Mode Shift+Tab (cycle)  |  /plan

Use when: starting a non-trivial feature, refactor, or architecture change. Claude reads, analyzes, and produces a structured plan — no file writes until you approve.

In plan mode Claude only has access to read-only tools: Read, LS, Glob, Grep, Task, TodoRead/Write, WebFetch, WebSearch, NotebookRead. It automatically spawns an Explore subagent (Haiku-powered) to scan the repo so your main context window stays clean.

Spec-first Safe exploration Token-efficient Human checkpoint
# Activate plan mode then share a spec
Shift+Tab
> "Read CLAUDE.md and plan how to add rate limiting to the ingest API"

# Or via command
/plan

# Combine with a higher effort level for architecture-grade plans
/effort xhigh
/plan
09

Auto Mode & Bypass — Unattended Autonomy

// TWO WAYS TO SKIP PROMPTS, ONE WAY THAT'S ACTUALLY SAFE

Auto mode is a permission mode where a background classifier makes approval decisions on your behalf, monitoring actions before they run. It sits between manual approval and bypass: far fewer interruptions than default, but real safety checks that bypass doesn't have.

How Auto Mode Works
  • Input layer: a prompt-injection probe scans tool outputs (file reads, web fetches, shell output, external responses) before Claude sees them
  • Action layer: a two-stage classifier (running on a fast model) evaluates each tool call before execution, auto-approving low-risk operations and escalating risky ones
  • Requires Opus 4.6+ or Sonnet 4.6+ on the Anthropic API; on Bedrock/Vertex/Foundry it's gated to Opus 4.7/4.8 and needs CLAUDE_CODE_ENABLE_AUTO_MODE=1
  • Docs call it a research preview: it "reduces prompts but does not guarantee safety" — treat it as trusting the direction of a task, not skipping review of sensitive operations
Bypass Permissions ("YOLO" / "god mode")
  • No classifier, no prompt-injection scanning, no approval gate at all
  • Equivalent to the old --dangerously-skip-permissions flag
  • Only real protection remaining: hooks still fire and can still block operations
  • Appropriate only inside a disposable container/VM with no real credentials, secrets, or production access mounted
# Enable auto mode for a session
claude --permission-mode auto

# Org admins can lock auto mode off entirely
# managed-settings.json:
{
  "permissions": { "disableAutoMode": "disable" }
}
Timeline for context: Auto mode launched March 24, 2026 as a research preview, expanded to Max/Team/Enterprise through mid-April, then Claude Code briefly defaulted to it. As of v2.1.200 (July 3, 2026) the shipped default reverted to manual approval on every surface — auto mode remains available, it's just opt-in again. This aligns with OWASP LLM Top 10 guidance recommending human-in-the-loop checkpoints for high-stakes agent actions.
10

CLAUDE.md — Project Memory

// THE "SHOULD DO" LAYER — PROBABILISTIC, NOT ENFORCED

CLAUDE.md is a markdown file Claude automatically loads into context at the start of every session. Think of it as onboarding notes for a new team member: coding standards, architecture context, build commands, and things to avoid.

Where CLAUDE.md Files Live — Resolution Order

LocationScopePrecedence
./CLAUDE.md (repo root)Project — shared, checked into gitLoaded first, always
./CLAUDE.local.mdProject, personal — gitignoredMerges on top of the project file for your machine only
~/.claude/CLAUDE.mdUser — applies to every project you openMerges under project-level instructions
Nested CLAUDE.md in subdirectoriesDirectory-scopedLoaded when Claude works within that subtree
Enterprise-managed CLAUDE.mdOrg-wide policyHighest — set by admins, cannot be overridden by users

Anatomy of a Good CLAUDE.md

# CLAUDE.md — project-name

### Project overview
Brief description of what this repo does and its core architecture.

### Coding standards
- TypeScript strict mode; no `any` without a comment justifying it
- Config-driven: no magic numbers in code, use config files
- All async operations require explicit error handling
- Tests: vitest, colocated as `*.test.ts`
- Never hardcode secrets; use `.env` + a typed config loader

### Build & test commands
!`cat package.json | grep -A 10 '"scripts"'`   # live-injects your npm scripts

### Recent activity (dynamic context)
!`git log --oneline -5`
!`git status`

### Do NOT
- Modify files under /infra/prod/
- Push directly to main; always use feature branches
- Run database migrations without human confirmation

### Reference docs
@./docs/architecture.md
@./configs/base_config.yaml
💡
Keep CLAUDE.md under ~200 lines. Use @filename imports for large reference docs, and move library-specific or workflow-specific knowledge into Skills (§13) instead of bloating this file. Use !`command` to inject dynamic, always-fresh context (e.g. !`git log --oneline -5`) rather than hand-maintaining a stale summary. CLAUDE.md is probabilistic — Claude usually follows it, but for rules that must always hold ("never touch prod configs"), enforce them with a Hook (§15) instead, which is deterministic.
# Auto-generate CLAUDE.md by scanning the current codebase
/init

# Progressive-disclosure tuning — trims a bloated CLAUDE.md
# while preserving critical rules (community skill pattern, see §14)
/claude-md-progressive-disclosurer
11

Settings & Permissions

// LAYERED CONFIG RESOLUTION

Settings resolve hierarchically: Enterprise/managed policy → CLI flags → .claude/settings.local.json (personal, gitignored) → .claude/settings.json (project, shared) → ~/.claude/settings.json (user). More specific scopes override less specific ones; managed policy always wins.

# .claude/settings.json — project-level, shared via git
{
  "model": "claude-sonnet-5",
  "permissions": {
    "allow": [
      "Bash(git add:*)",
      "Bash(git commit:*)",
      "Bash(npm run:*)",
      "Write(src/**)",
      "Edit(*.ts)",
      "Edit(*.yaml)"
    ],
    "deny": [
      "Bash(rm -rf:*)",
      "Bash(curl * | bash:*)",
      "Write(.env)",
      "Write(infra/prod/**)"
    ]
  },
  "disableBundledSkills": false,
  "disableWorkflows": false,
  "fallbackModel": ["claude-sonnet-4-6", "claude-haiku-4-5-20251001"]
}
# Interactive permission management
/permissions

# Useful CLI flags
claude --allowedTools "Read,Grep,Glob"      # restrict tools
claude --disallowedTools "Bash,Write"       # deny specific tools
claude --permission-mode acceptEdits        # auto-accept all edits, still gate Bash
Fixed in v2.1.214/215: single-segment dir/** allow rules like Edit(src/**) no longer auto-approve writes to nested src/ directories anywhere in the tree — only under your current working directory. Bash permission checks also now fail closed on unusual redirect forms and always prompt on commands over 10,000 characters. Re-check any custom allow rules you wrote before mid-July 2026 against this tightened behavior.
12

Custom Slash Commands

// LIGHTWEIGHT, PROJECT-SCOPED PROMPTS

Commands are markdown files in .claude/commands/ (project) or ~/.claude/commands/ (global). They surface as /command-name with tab-completion. For anything that needs supporting files, templates, or subagent delegation, prefer a Skill (§13) instead.

# Create a command
mkdir -p .claude/commands
nano .claude/commands/review-pr.md

# Use it
/review-pr
/fix-issue 123          # $ARGUMENTS passes "123"
/deploy-staging main    # $ARGUMENTS passes "main"

Command Anatomy

--- file: .claude/commands/commit.md ---
---
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)
description: Create a semantic git commit from staged changes
---

## Context
- Current status: !`git status`
- Current diff: !`git diff HEAD`
- Branch: !`git branch --show-current`
- Recent commits: !`git log --oneline -5`

Create a conventional commit message (type(scope): description) for these changes.
Stage all relevant files and commit.

Built-in Commands Reference

CommandWhat it does
/initScan codebase and auto-generate CLAUDE.md
/clearReset context (use between unrelated tasks)
/compactSummarize and compress context
/rewindStep the session back to an earlier checkpoint
/forkBranch the current session into a parallel background session
/continue / --resumeResume last session or a specific session ID
/modelSwitch model interactively
/effortSet reasoning effort level — see §05
/permissionsView / edit tool permissions
/hooksList configured hooks
/skillsList available skills
/pluginBrowse, install, and manage plugins — see §14
/costShow token usage and spend
/contextView context usage as a colored grid
/doctorRun diagnostics
/verifyRun the verify skill against the current change — no longer auto-runs, invoke it directly (v2.1.215)
/code-reviewRun the code-review skill — same change, invoke it directly
/goalRun-until-verified loop primitive — see §20
/scheduleSchedule remote/background Claude Code agents on a cadence
/agents / claude agentsOpen Agent View — dashboard of running/blocked/completed sessions
/vimEnter vim keybinding mode
/output-styleSet output verbosity / format
/configSession and feature-flag configuration (ultracode trigger, etc.)
Behavior change (v2.1.215, July 19, 2026): Claude no longer runs /verify and /code-review on its own after finishing a task — invoke them explicitly when you want that check.
13

Agent Skills

// PACKAGED, REUSABLE, INSTALLABLE EXPERTISE

Skills are the evolution of custom commands: directories under .claude/skills/ (project) or ~/.claude/skills/ (personal, applies to every project) with a SKILL.md entrypoint, plus optional supporting files, templates, scripts, and reference docs. Unlike commands, skills are not code that runs — they're structured instructions Claude reads and follows, optionally delegating to a subagent.

# Directory structure
.claude/skills/
  code-review/
    SKILL.md          # entrypoint, metadata
    checklist.md       # supporting doc
    templates/
      review.md
  train-eval/
    SKILL.md
    scripts/
      evaluate.py
--- .claude/skills/train-eval/SKILL.md ---
---
name: train-eval
description: Run a training evaluation loop and compare checkpoints. Use when asked to evaluate, benchmark, or compare model checkpoints.
allowed-tools: [Bash, Read, Write, Grep]
agent: general-purpose
context: fork
---

# Training Evaluation Skill

## Steps
1. Read the active config from configs/active.yaml
2. Run: python scripts/evaluate.py --checkpoint $ARGUMENTS
3. Parse the run URL from stdout
4. Summarize eval metrics in a markdown table
5. Compare against baseline in configs/baselines.yaml

Include ultrathink to deeply analyze any regression.
context: fork runs the skill in an isolated subagent so output returns to the main thread cleanly without polluting your working context. Add ultrathink or ultracode anywhere in skill content to request deeper reasoning or auto-orchestration for that skill specifically.

Skills vs. MCP Connections

Skills (SKILL.md)MCP Servers
What they doTeach Claude how to do a taskGive Claude access to external services
FormatMarkdown instructions + optional scriptsServer endpoint over the Model Context Protocol
InstallationDrop a folder in .claude/skills/ or install as a pluginConfigure a connection in .claude/mcp.json
Requires hostingNoYes (a running MCP server)
Example"Review code checking for OWASP Top 10""Read pull requests from our GitHub org"

They're complementary: a code-review skill tells Claude how to review code; a GitHub MCP connector gives it PRs to review. Together, Claude pulls the PR via MCP and reviews it using the skill's standards.

# Hide Claude's built-in bundled skills/commands (v2.1.169+)
# .claude/settings.json
{ "disableBundledSkills": true }
14

Plugin Marketplace

// INSTALLING SKILLS FROM THE TERMINAL

A plugin bundles one or more skills, along with optional hooks and MCP server configs, into a single installable package. Plugins are the distribution format; skills are the content. Anthropic ships an official marketplace (claude-plugins-official) alongside dozens of community marketplaces.

# Browse the built-in Discover tab
/plugin

# Add a marketplace, then install from it
/plugin marketplace add anthropics/claude-plugins-official
/plugin install code-simplifier@claude-plugins-official
/plugin install security-guidance@claude-plugins-official

# Add a community marketplace by GitHub repo
/plugin marketplace add owner/repo
/plugin install some-skill@repo-marketplace

# Install by domain bundle (community pattern)
claude /plugin install engineering-skills
claude /plugin install devops-skills
Official Anthropic Marketplace

Built into Claude Code. Anthropic-built plugins cover language servers, dev workflow (feature-dev, code-review, commit-commands, security-guidance, frontend-design), setup tools, and output styles. Partner plugins connect GitHub, Playwright, Supabase, Figma, Vercel, Linear, Sentry, Stripe, Firebase, and more.

Community Marketplaces

Independent, GitHub-hosted marketplaces with hundreds of skills — engineering, marketing, DevOps, and niche stacks (Cloudflare, iOS, LLM eval). Same SKILL.md format works across Claude Code, Codex CLI, and other compatible agents.

ScopeInstall locationBest for
User~/.claude/skills/General-purpose skills you want in every project
Project.claude/skills/Skills specific to this repo's stack and conventions
Plugin~/.claude/plugins/Anything installed via /plugin install — works across projects
💡
Custom beats generic. A downloaded "code review" skill is fine as a baseline, but a skill built around your own stack's specific conventions, URL patterns, and known failure modes compounds in value the more you run it. Treat marketplace skills as starting templates, not finished products.
15

Hooks — Deterministic Automation

// THE "MUST ALWAYS HAPPEN" LAYER

Hooks intercept Claude Code's lifecycle and run your code — shell scripts, HTTP endpoints, LLM prompts, or agents — at specific events. Unlike CLAUDE.md's probabilistic "should do" guidance, hooks are deterministic: they run every time, and they still fire even in bypass permission mode.

Event fires
Matcher regex
Handler runs
Decision: allow / block / inject
# .claude/settings.json — hooks section
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{
          "type": "command",
          "command": "python hooks/block_dangerous.py"
        }]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [{
          "type": "command",
          "command": "prettier --write $CLAUDE_TOOL_INPUT_FILE_PATH"
        }]
      }
    ],
    "Stop": [
      {
        "matcher": "*",
        "hooks": [{
          "type": "command",
          "command": "notify-send 'Claude Code' 'Session complete'"
        }]
      }
    ]
  }
}

Hook Events

SessionStartSession begins or resumes — load dev context, env varsOnce/session
PreToolUseBefore any tool call — block dangerous commands, audit, inject secretsPer tool call
PostToolUseAfter tool returns — auto-format, lint, log, transform outputsPer tool call
PostToolUseFailureTool failed — structured error logging, alertingPer failure
UserPromptSubmitUser submits prompt — validate/enhance before Claude sees itPer message
NotificationPermission dialog shown — audit, auto-allow read-only opsPer dialog
SubagentStartSubagent spawned — log spawn, TTS announcementPer spawn
StopSession ends (exit / sigint / error) — git checkpoint, cleanup, notifyOnce/session
IdleAgent waiting — send updates, run background checksPeriodic

Hook Handler Types

command
Shell script. JSON input on stdin. Returns decision via exit code + stdout. Most common; full OS access.
http
HTTP POST to your endpoint. Same JSON in/out contract as command. Useful for external audit systems or webhooks.
prompt
Sends a prompt to a Claude model for a yes/no evaluation. Returns a structured JSON decision. Use for nuanced condition checks.
agent
Spawns a subagent with Read/Grep/Glob tools to verify conditions before deciding — full code analysis before a block/allow decision.
--- hooks/block_dangerous.py ---
import json, sys, re

data = json.load(sys.stdin)
cmd = data.get("tool_input", {}).get("command", "")

BLOCKED = [r"rm\s+-rf", r"curl.*\|\s*bash", r":(){:|:&};:"]
for pattern in BLOCKED:
    if re.search(pattern, cmd):
        print(json.dumps({"decision": "block", "reason": f"Blocked: {pattern}"}))
        sys.exit(0)

sys.exit(0)  # allow
17

Agent System

// TASK TOOL, BUILT-IN AGENTS, AGENT VIEW

Claude Code's main session can delegate work to subagents through the Task tool. Each subagent runs in its own isolated context window, with its own model, tool access, and cache — results return to the caller as a distilled summary, keeping the main thread's context clean.

Explore
Haiku-powered. Scans codebase structure, searches files, returns a distilled map. Auto-spawned in plan mode. Cost-efficient for large repos.
Plan (enhanced)
Runs the plan-mode analysis pipeline. Produces a structured task breakdown with dependencies and execution order, and can write plan.md.
General-purpose
Default subagent. Searches, analyzes, and edits code across the codebase. Reports findings concisely back to the caller.
# Open Agent View — research-preview operations dashboard
claude agents

# Scope to one directory
claude agents --cwd ./services/api

# Dispatch flags for background sessions (v2.1.142+)
claude agents --add-dir ./libs --model claude-sonnet-5 --effort high --permission-mode acceptEdits
18

Custom Subagents

// SPECIALIZED, RE-INVOCABLE, UP TO 10 IN PARALLEL

Custom subagents live in .claude/agents/ (project) or ~/.claude/agents/ (personal) as markdown files with YAML frontmatter. Claude Code can run up to 10 subagents in parallel, and subagents can themselves spawn nested subagents (since v2.1.172).

--- .claude/agents/reviewer.md ---
---
name: reviewer
description: Reviews code changes for correctness, security, and test coverage. Use proactively after any implementation is complete, or when asked to review, compare, or audit changes.
tools: Read, Grep, Glob, Bash
model: sonnet
---

You are an expert code reviewer.

When reviewing a change:
1. Run the test suite and linter
2. Check for injection risks, unhandled errors, and missing edge cases
3. Flag any diff that touches auth, payments, or data-deletion paths for extra scrutiny
4. Output a structured markdown report: status, key findings, recommendations

Return only the report — no preamble.
# Invoke a custom agent directly
@reviewer check the changes from the last commit

# Or let Claude auto-delegate by description match
> "Review the auth module changes"  # Claude delegates if a subagent's description matches

Meta-Agent (Agent That Builds Agents)

--- .claude/agents/meta-agent.md ---
---
name: meta-agent
description: Generates new subagent definitions from natural language descriptions. Use when asked to "build a new agent" or "create a subagent for..."
---

Given a description, produce a properly formatted .claude/agents/*.md file
following the project's agent standards. Ask clarifying questions if needed.
> "Build a new subagent that monitors bundle size after every build"
# meta-agent creates .claude/agents/bundle-size-monitor.md automatically
19

Multi-Agent Patterns & Dynamic Workflows

// BUILDER + VALIDATOR, PARALLEL WORKTREES, ORCHESTRATED FAN-OUT

Builder + Validator

--- .claude/agents/validator.md ---
---
name: validator
description: Validates code changes for correctness, security, and test coverage. Use after implementation is complete.
tools: Read, Bash, Grep
model: sonnet
---
Run: the test suite, linter, type-checker, and a security scanner.
Return: PASS or FAIL with specific findings.
# In a session
> "Implement the rate limiter, then validate it"
# Claude builds → spawns validator → reports consolidated result
# The agent that wrote the code never grades its own work.

Parallel Worktree Agents

# Run 3 agents on different features simultaneously
claude -w feature-auth &
claude -w feature-billing &
claude -w feature-notifications &
wait
# Each works in an isolated git worktree — no conflicts
git merge feature-auth feature-billing feature-notifications

Dynamic Workflows — Automatic Orchestration

Introduced with Opus 4.8 (v2.1.154, May 28, 2026): when triggered by the ultracode keyword or /effort ultracode, Claude writes a small orchestration script that a background runtime executes, coordinating up to 16 concurrent subagents per task (tens to hundreds across a full session). Intermediate results live in script variables, not the main context window — this is what lets it scale past what a single conversation can coordinate.

Failure modes it fixes
  • Early quitting — spreading a large task across isolated agents means no single context window has to hold all of it
  • Self-preferential grading — verification is handed to a separate agent that never wrote the answer it's judging
  • Goal drift — each agent's window stays short enough that drift never sets in before it finishes and returns
When to reach for it
  • Codebase-wide audits and migrations
  • Cross-checked research spanning many sources
  • Large refactors that would otherwise blow a single context window
  • Not for routine single-file edits — it's expensive by design
20

/goal — Run-Until-Verified Loops

// LOOP ENGINEERING, NATIVE TO CLAUDE CODE

/goal sets a verifiable end condition. Claude works toward it continuously — spawning subagents, running tests, iterating — until a separate evaluator confirms the condition is met, or a budget is exhausted. No more typing "keep going" every few files; the loop self-terminates when the goal is actually verified, not when Claude feels done.

# A useful /goal prompt carries the full control contract.
# The goal line itself is the least important part.

/goal "Fix all failing tests in packages/api"

Context:
  - Failing tests: [paste output of `npm test 2>&1`]
  - Codebase: TypeScript, Express, Prisma ORM
  - Do NOT modify test files — fix the implementation only

Verifier:         run `npm test` after each change batch
                  pass condition: exit code 0, 0 failed tests

Evidence:         paste final test output as proof of completion

Budget:
  max_turns:      25
  max_duration:   45 minutes
  max_cost:       $2.00

Stop conditions:
  ✓ All tests pass (exit 0)
  ✗ Budget hit → summarize work done, open issues list, stop
  ✗ Same test fails 3 times in a row → stop, explain blocker

Do NOT:
  - Skip or disable failing tests
  - Modify test expectations
  - Leave TODO comments as fixes
💡
Pair /goal with /schedule for self-correcting loops that run on a cadence until a validator passes — e.g. a nightly job that re-runs /goal against the current failing-test list and only pages a human if the same failure persists three runs in a row.
# Headless / scripted usage — run against a prompt file until
# the goal is marked complete or the iteration limit is reached

# prompt.md
Task: Bring test coverage on src/billing/ above 85%.
Done when: coverage report shows >=85%, all new tests pass, PR is open.
Limit: 20 iterations.

claude --headless -p "$(cat prompt.md)"
21

MCP Servers — External Integrations

// THE ACTION LAYER — READ AND WRITE TO EXTERNAL SYSTEMS

Model Context Protocol gives Claude Code access to databases, APIs, and services through a standardized interface. Hundreds of servers are available, official and community-maintained.

# .claude/mcp.json — project MCP config
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_TOKEN": "${GITHUB_TOKEN}" },
      "request_timeout_ms": 120000
    },
    "postgres": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-postgres", "${DATABASE_URL}"]
    }
  }
}
# Manage MCP servers interactively
/mcp                         # list connected servers + tool counts, flags zero-tool connections
claude --mcp-server github   # enable specific server

# Use in prompts naturally
> "Open a GitHub issue for the rate-limiter bug and assign it to me"
> "Query the last 5 failed CI runs and summarize what broke"
MCP ServerUse caseInstall
GitHubPRs, issues, code review@modelcontextprotocol/server-github
PostgreSQLQuery prod/dev databases@modelcontextprotocol/server-postgres
FilesystemExtended file access outside project@modelcontextprotocol/server-filesystem
PlaywrightBrowser automation, regression testing@executeautomation/playwright-mcp
SlackSend notifications, read messages@modelcontextprotocol/server-slack
Linear / JiraTicket creation, status updatesCommunity server
Fixed in v2.1.214: MCP servers configured via --mcp-config or .mcp.json now respect a per-server request_timeout_ms — previously long-running MCP tool calls could time out at the 60-second default even when you'd set a longer one.
22

Agent SDK

// BUILD YOUR OWN ORCHESTRATOR ON TOP OF CLAUDE CODE

The Agent SDK lets you build custom agent orchestrators in TypeScript or Python — with full control over tool access, hooks, subagents, and permissions. Use it when Claude Code's interactive mode isn't enough and you need to embed agentic behavior into your own service.

TypeScript SDK

import { query, type ClaudeCodeOptions } from "@anthropic-ai/claude-code";

const options: ClaudeCodeOptions = {
  maxTurns: 10,
  model: "claude-sonnet-5",
  allowedTools: ["Read", "Write", "Bash", "Grep"],
  systemPrompt: "You are a specialist reviewer for this codebase...",
  hooks: {
    PreToolUse: async (input) => {
      if (input.tool_name === "Bash" && input.tool_input.command.includes("rm -rf")) {
        return { decision: "block", reason: "Destructive command blocked" };
      }
    },
    Stop: async (input) => {
      console.log(`Session ended: ${input.session_id}`);
    }
  }
};

for await (const message of query({
  prompt: "Audit the auth module for injection risks",
  options
})) {
  console.log(message);
}
23

CI/CD & GitHub Actions

// CLAUDE AS A PIPELINE STEP
.github/workflows/claude-review.yml
name: Claude Code Review
on: [pull_request]
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: anthropic/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: "Review this PR diff for bugs, security issues, and test coverage gaps"
          permission-mode: plan
💡
Pin permission-mode: plan or a narrow allowedTools list in CI — you don't want a PR-triggered agent making unattended writes back to the repo without a human merge gate.
24

Local Model Setup

// OLLAMA, OPEN-WEIGHT MODELS, AND THE CLAUDE CODE ROUTER

Claude Code speaks the Anthropic Messages API natively, but it can be pointed at any Anthropic-compatible or OpenAI-compatible endpoint — including local inference via Ollama and open-weight models from Zhipu (GLM), Moonshot (Kimi), MiniMax, Alibaba (Qwen), and DeepSeek.

Native Ollama Routing (Simplest Path)

Ollama ships native Anthropic API compatibility, so no proxy is required for basic use — just point the two environment variables at your local Ollama instance.

# ~/.claude/settings.json — environment overrides
{
  "env": {
    "ANTHROPIC_BASE_URL": "http://localhost:11434",
    "ANTHROPIC_AUTH_TOKEN": "ollama",
    "ANTHROPIC_API_KEY": ""
  }
}

# Pull and run a local model
ollama pull qwen3.6:27b
claude --model qwen3.6:27b

# Guided setup
ollama launch claude --config

Ollama Cloud — Frontier Open-Weight Models, No GPU Required

Models tagged :cloud (e.g. glm-5.1:cloud, kimi-k2.6:cloud, deepseek-v4-pro:cloud) run on Ollama's infrastructure rather than your hardware — same environment variables, but your prompts leave the machine. Useful when local hardware can't fit a frontier-class open model.

ollama pull glm-5.1:cloud
claude --model glm-5.1:cloud
# Ollama Cloud plans: Free / Pro (~$20/mo) / Max (~$100/mo)

Recommended Open-Weight Models (mid-2026)

TierModelNotes
Daily driver, localQwen 3.6-27BRuns on a 24–32GB Mac or 24GB GPU; strong agentic coding
Frontier open-weightGLM-5.2Leads open-weight benchmarks on SWE-Bench Pro and LiveBench agentic coding
Frontier open-weightKimi K2.7 CodeBest-balanced open-weight model for agentic coding per independent benchmarks
Frontier open-weightMiniMax M31M-token context, native multimodality, released June 2026
Frontier open-weightDeepSeek-V4-Pro-MaxStrongest on LiveCodeBench v6 among the June 2026 wave

Claude Code Router — Per-Request-Type Routing

For finer control than a single global backend, @musistudio/claude-code-router is an open-source proxy that intercepts Claude Code's requests and routes each request type to a different provider — useful because a coding session isn't one workload: summarizing a diff is a throwaway task, planning a refactor is a reasoning task, and applying an edit is where quality matters most.

# Launch with the router instead of `claude`
npm install -g @musistudio/claude-code-router
ccr code

# config.json — route each request type to a different provider/model
{
  "Providers": [
    { "name": "ollama", "api_base_url": "http://localhost:11434/v1/chat/completions", "models": ["qwen3.6:27b"] },
    { "name": "deepseek", "api_base_url": "https://api.deepseek.com/v1", "api_key": "${DEEPSEEK_API_KEY}", "models": ["deepseek-v4-pro-max"] }
  ],
  "Router": {
    "default":     "ollama,qwen3.6:27b",
    "background":  "ollama,qwen3.6:27b",
    "think":       "deepseek,deepseek-v4-pro-max",
    "longContext": "deepseek,deepseek-v4-pro-max"
  }
}

# Override any route mid-session
/model provider,model-name
Capability gap. Many open-weight and smaller local models don't support extended thinking tokens or fully native structured tool use, and their agentic tool-calling is measurably weaker than Sonnet 5/Opus 4.8. Hooks and subagents that depend on reliable JSON tool calls will degrade — use local/open models for review, summarization, and background tasks, not for orchestration-heavy or long-horizon agentic work. Claude Code's edit format was tuned specifically for Claude models; expect a lower diff-apply success rate on other providers.
💡
You can mix backends per project: one repo's .claude/settings.local.json points at local Ollama for a fully offline workflow, while another points at the Anthropic API or OpenRouter — no manual environment-variable juggling required.
25

Context Management

// KEEP THE WINDOW LEAN
  • /context — view token usage as a colored grid before you hit a wall
  • /compact — summarize and compress when context gets heavy mid-task
  • /clear — hard reset between unrelated tasks; don't carry stale context forward
  • /fork — branch into a background session to explore a risky change without polluting the main thread
  • Push verbose, read-heavy operations (large file scans, log parsing) into subagents — their context doesn't count against your main window
  • Keep CLAUDE.md lean (§10) and move deep reference material into Skills, loaded only when relevant
26

Workflow Patterns

// PRACTICAL RECIPES

Curriculum-Aware Slash Command

--- .claude/commands/run-suite.md ---
---
allowed-tools: Bash(npm:*), Read, Write
description: Run a named test suite and summarize failures
---

Run test suite $ARGUMENTS:
1. Validate config: !`cat configs/$ARGUMENTS.yaml`
2. Run: npm test -- --suite=$ARGUMENTS
3. If failures, invoke @reviewer on the failing files
4. Log a one-line summary to CHANGELOG-tests.md

Post-Deploy Verification Hook

--- hooks/post-deploy-check.sh ---
#!/bin/bash
# PostToolUse hook on Bash — triggers after any deploy script
INPUT=$(cat)
CMD=$(echo "$INPUT" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('tool_input',{}).get('command',''))")

if echo "$CMD" | grep -q "deploy.sh"; then
  echo '{"systemMessage": "Deploy finished. Run @reviewer against the release diff."}'
fi
27

Troubleshooting

// COMMON ISSUES AND FIXES
SymptomFix
Context limit hit mid-task/compact then continue; push verbose ops to subagents
Claude ignoring CLAUDE.md rulesMove critical rules to Hooks (deterministic); CLAUDE.md is probabilistic
Hook not firing/hooks to verify; check matcher regex
Local/open model tool calls brokenLocal models lack robust structured tool use — use for review/summarization only, see §24
Subagent context bleedEnsure the skill uses context: fork in frontmatter
Effort/model switch feels slowEvery switch forces a full-price uncached re-read; decide effort up front instead
Plan mode not exitingShift+Tab to cycle back; or explicitly approve the plan
Permissions errors/permissions → add allow rule; check tightened Bash/Edit rules from v2.1.214
Session lost after crashclaude --continue or claude --resume <session-id>
MCP server not connecting / timing outCheck .mcp.json, run /mcp, set request_timeout_ms for slow servers
Expired login shows misleading model errorRun /login — fixed cosmetically but still worth checking first, v2.1.214
/verify / /code-review not running automaticallyExpected as of v2.1.215 — invoke them explicitly now
Something feels globally brokenclaude --safe-mode for a clean session with all customizations disabled
# Useful debug commands
/doctor          # full diagnostics
/context         # token grid
claude --version # verify version
claude update    # update to latest

# Read raw session transcripts
ls ~/.claude/projects/
cat ~/.claude/projects/<project-hash>/<session-id>.jsonl | jq .
28

Reference Links

// OFFICIAL DOCS AND COMMUNITY RESOURCES

Official Docs

Community Resources

Prompt Engineering for Claude Code

Back to Handbooks