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.
What's New in v2
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.
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.
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.
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 (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.
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.
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.
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.Install & Setup
# 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
/model (v2.1.196+) and cannot be overridden by users unless the policy allows it.IDE Integrations
| Surface | How to activate | Notes |
|---|---|---|
| VS Code | Install Claude Code extension, Ctrl+Shift+C | Inline diffs, native diagnostics panel |
| JetBrains | Plugin marketplace → "Claude Code" | IntelliJ, PyCharm, WebStorm, GoLand |
| Terminal | claude in any directory | Primary surface; full feature set first |
| GitHub Actions | uses: anthropic/claude-code-action | See §23 |
| Agent View (dashboard) | claude agents | Research preview — monitor running / blocked / completed background sessions; --cwd <path> scopes to a directory |
| Web / Desktop | claude.ai → Claude Code tab | Remote sessions from mobile too |
Model Selection
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.
high effort; supports xhigh and ultracode.
Slow
$$$
# 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
| Model | Model ID | Context | Max output |
|---|---|---|---|
| Claude Fable 5 | claude-fable-5 | 1M | 128K |
| Claude Opus 4.8 | claude-opus-4-8 | 1M | 128K |
| Claude Opus 4.7 | claude-opus-4-7 | 1M | 128K |
| Claude Opus 4.6 | claude-opus-4-6 | 1M | 128K |
| Claude Sonnet 5 | claude-sonnet-5 | 1M | 128K |
| Claude Sonnet 4.6 | claude-sonnet-4-6 | 1M | 128K |
| Claude Haiku 4.5 | claude-haiku-4-5-20251001 | 200K | 64K |
/model fable ever errors out unexpectedly, check anthropic.com/news for the current access status before assuming a local misconfiguration.Effort Levels & Ultracode
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.
| Level | Persistence | Use for |
|---|---|---|
low | Session | Trivial edits, quick lookups, chat-style Q&A |
medium | Session | Routine coding, small scoped changes |
high | Session (default on Opus 4.8) | Real feature work, multi-file changes |
xhigh | Session | Hard multi-step problems: architecture, tricky debugging, security audits. Only Fable 5, Opus 4.8, and Opus 4.7 support it. |
max | Session-only | Highest single-turn reasoning depth; resets when the session ends |
ultracode | Session-only | xhigh 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
/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.Extended Thinking — Prompt-Level Nudges
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 phrase | Scope | When to use |
|---|---|---|
think | This turn | Simple reasoning, quick decision |
think harder / think more | This turn | Multi-step problems, debugging |
ultrathink | This turn | Hard research, novel algorithm design — requests deeper reasoning without spawning extra agents |
ultracode | This task (or session via /effort) | Same depth as ultrathink plus automatic subagent orchestration — see §05 |
display: "summarized" in the API). Local/open-weight models generally lack extended-thinking tokens entirely — see §24.Permission Modes — All Five, Explained
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.
| Mode | Flag / setting | Behavior |
|---|---|---|
| Default (Manual) | default | Every 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 Edits | acceptEdits | File edits auto-approve; Bash and other risky tools still prompt. Good middle ground for refactor sessions. |
| Plan Mode | plan | Read-only tools only — no writes at all until you approve a plan. See §08. |
| Auto Mode | auto | A 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-permissions | No 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
Plan Mode
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.
# 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
Auto Mode & Bypass — Unattended Autonomy
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.
- 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
- No classifier, no prompt-injection scanning, no approval gate at all
- Equivalent to the old
--dangerously-skip-permissionsflag - 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" } }
CLAUDE.md — Project Memory
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
| Location | Scope | Precedence |
|---|---|---|
./CLAUDE.md (repo root) | Project — shared, checked into git | Loaded first, always |
./CLAUDE.local.md | Project, personal — gitignored | Merges on top of the project file for your machine only |
~/.claude/CLAUDE.md | User — applies to every project you open | Merges under project-level instructions |
Nested CLAUDE.md in subdirectories | Directory-scoped | Loaded when Claude works within that subtree |
Enterprise-managed CLAUDE.md | Org-wide policy | Highest — 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
@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
Settings & Permissions
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
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.Custom Slash Commands
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
| Command | What it does |
|---|---|
/init | Scan codebase and auto-generate CLAUDE.md |
/clear | Reset context (use between unrelated tasks) |
/compact | Summarize and compress context |
/rewind | Step the session back to an earlier checkpoint |
/fork | Branch the current session into a parallel background session |
/continue / --resume | Resume last session or a specific session ID |
/model | Switch model interactively |
/effort | Set reasoning effort level — see §05 |
/permissions | View / edit tool permissions |
/hooks | List configured hooks |
/skills | List available skills |
/plugin | Browse, install, and manage plugins — see §14 |
/cost | Show token usage and spend |
/context | View context usage as a colored grid |
/doctor | Run diagnostics |
/verify | Run the verify skill against the current change — no longer auto-runs, invoke it directly (v2.1.215) |
/code-review | Run the code-review skill — same change, invoke it directly |
/goal | Run-until-verified loop primitive — see §20 |
/schedule | Schedule remote/background Claude Code agents on a cadence |
/agents / claude agents | Open Agent View — dashboard of running/blocked/completed sessions |
/vim | Enter vim keybinding mode |
/output-style | Set output verbosity / format |
/config | Session and feature-flag configuration (ultracode trigger, etc.) |
/verify and /code-review on its own after finishing a task — invoke them explicitly when you want that check.Agent Skills
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 do | Teach Claude how to do a task | Give Claude access to external services |
| Format | Markdown instructions + optional scripts | Server endpoint over the Model Context Protocol |
| Installation | Drop a folder in .claude/skills/ or install as a plugin | Configure a connection in .claude/mcp.json |
| Requires hosting | No | Yes (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 }
Plugin Marketplace
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
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.
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.
| Scope | Install location | Best 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 |
Hooks — Deterministic Automation
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.
# .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
Hook Handler Types
stdin. Returns decision via exit code + stdout. Most common; full OS access.command. Useful for external audit systems or webhooks.--- 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
Agent System
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.
plan.md.# 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
Custom Subagents
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
Multi-Agent Patterns & Dynamic Workflows
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.
- 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
- 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
/goal — Run-Until-Verified Loops
/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
/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)"
MCP Servers — External Integrations
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 Server | Use case | Install |
|---|---|---|
| GitHub | PRs, issues, code review | @modelcontextprotocol/server-github |
| PostgreSQL | Query prod/dev databases | @modelcontextprotocol/server-postgres |
| Filesystem | Extended file access outside project | @modelcontextprotocol/server-filesystem |
| Playwright | Browser automation, regression testing | @executeautomation/playwright-mcp |
| Slack | Send notifications, read messages | @modelcontextprotocol/server-slack |
| Linear / Jira | Ticket creation, status updates | Community server |
--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.Agent SDK
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); }
CI/CD & GitHub Actions
.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
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.Local Model Setup
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)
| Tier | Model | Notes |
|---|---|---|
| Daily driver, local | Qwen 3.6-27B | Runs on a 24–32GB Mac or 24GB GPU; strong agentic coding |
| Frontier open-weight | GLM-5.2 | Leads open-weight benchmarks on SWE-Bench Pro and LiveBench agentic coding |
| Frontier open-weight | Kimi K2.7 Code | Best-balanced open-weight model for agentic coding per independent benchmarks |
| Frontier open-weight | MiniMax M3 | 1M-token context, native multimodality, released June 2026 |
| Frontier open-weight | DeepSeek-V4-Pro-Max | Strongest 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
.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.Context Management
/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
Workflow Patterns
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
Troubleshooting
| Symptom | Fix |
|---|---|
| Context limit hit mid-task | /compact then continue; push verbose ops to subagents |
| Claude ignoring CLAUDE.md rules | Move critical rules to Hooks (deterministic); CLAUDE.md is probabilistic |
| Hook not firing | /hooks to verify; check matcher regex |
| Local/open model tool calls broken | Local models lack robust structured tool use — use for review/summarization only, see §24 |
| Subagent context bleed | Ensure the skill uses context: fork in frontmatter |
| Effort/model switch feels slow | Every switch forces a full-price uncached re-read; decide effort up front instead |
| Plan mode not exiting | Shift+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 crash | claude --continue or claude --resume <session-id> |
| MCP server not connecting / timing out | Check .mcp.json, run /mcp, set request_timeout_ms for slow servers |
| Expired login shows misleading model error | Run /login — fixed cosmetically but still worth checking first, v2.1.214 |
/verify / /code-review not running automatically | Expected as of v2.1.215 — invoke them explicitly now |
| Something feels globally broken | claude --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 .
Reference Links
Official Docs
- Overview code.claude.com/docs/en/overview
- Changelog code.claude.com/docs/en/changelog
- CLI ref docs.claude.com — CLI Reference
- Model config code.claude.com/docs/en/model-config
- Permission modes code.claude.com — Permission modes
- Auto mode claude.com/blog/auto-mode
- Auto mode engineering anthropic.com/engineering — How we built auto mode
- Hooks code.claude.com/docs/en/hooks
- Skills code.claude.com/docs/en/skills
- Plugins code.claude.com/docs/en/plugins
- Subagents SDK platform.claude.com — Subagents
- MCP docs.claude.com — MCP
- GHA docs.claude.com — GitHub Actions
- CLAUDE.md docs.claude.com — Memory & CLAUDE.md
- Models overview platform.claude.com — Models overview
- Fable / Mythos anthropic.com/news — Fable & Mythos access notice
Community Resources
- Awesome CC github.com/hesreallyhim/awesome-claude-code
- Hooks mastery github.com/disler/claude-code-hooks-mastery
- Router github.com/musistudio/claude-code-router
- Compatible models github.com/Alorse/cc-compatible-models
- Skills marketplace claudemarketplaces.com
Prompt Engineering for Claude Code
- Prompting docs.claude.com — Prompt engineering overview
- Extended thinking docs.claude.com — Extended thinking