01

Mental modelhow the pieces fit together

Claude Code is an agentic CLI. You speak in natural language; it reads files, runs commands, edits code, and ships work. Everything else is configuration around that loop.

The agentic loop runs in three blended phases โ€” gather context, take action, verify results โ€” and uses built-in tools (Read, Edit, Write, Bash, Grep, Glob, WebFetch, Task) to touch your project. Each tool call feeds the next decision. You extend this loop by adding knowledge, connections, or constraints โ€” without ever changing the loop itself.

The five extension points

CLAUDE.mdProject memory. Auto-loaded at session start.
SkillsModel-invoked capabilities. Claude picks them.
Slash commandsUser-invoked prompts. You type /name.
SubagentsIsolated contexts for specialized tasks.
MCP serversExternal tools (GitHub, Sentry, DBs, APIs).

Every extension costs some context window. Skills load descriptions upfront and bodies on demand. Subagents cost zero main-context tokens because they run in isolation. Hooks cost nothing unless they return output. Choose accordingly โ€” see context costs per feature.

The three execution modes

InteractiveTUI conversation. claude.
HeadlessOne-shot or piped. claude -p "โ€ฆ".
RemoteClaude Code on Web / mobile Remote Control.

Config resolution order (first = highest priority)

  1. /etc/claude-code/managed-settings.json โ€” enterprise policy
  2. .claude/settings.local.json โ€” personal, git-ignored
  3. .claude/settings.json โ€” project, checked in
  4. ~/.claude/settings.json โ€” user defaults

Later layers never override earlier ones. A deny rule in project settings can't be loosened by a personal override.

02

Install & launchget up in under a minute

Four supported installers. The native script is the only one that auto-updates in the background; Homebrew and winget need manual upgrades. The npm path still works but is deprecated โ€” if you're new, don't start there.

macOS / Linux โ€” native installer (recommended)

# Official install script
curl -fsSL https://claude.ai/install.sh | bash

# Homebrew
brew install --cask claude-code
brew upgrade claude-code   # manual upgrade

Windows

# PowerShell
irm https://claude.ai/install.ps1 | iex

# winget
winget install Anthropic.ClaudeCode
winget upgrade Anthropic.ClaudeCode  # manual

IDE integration

VS Code and JetBrains plugins exist โ€” launch Claude from an IDE gutter, get inline diff proposals, and keep your terminal free. See VS Code and JetBrains docs.

Launch & maintenance

# Start in the current project
cd your-project && claude

# Version / update / health
claude --version
claude update
claude doctor

# Force reinstall if update misbehaves
claude install --force

# Auth
claude   # prompts /login on first run
Auth notes Pro plans limit Opus access โ€” see model configuration on support. For API-key, Bedrock, Vertex, or Foundry use, set ANTHROPIC_AUTH_TOKEN or the provider's credentials before launch.
Tip Run claude doctor after any config change โ€” it flags unreachable permission rules, duplicate MCP servers, missing LSP binaries, and broken hooks.
03

CLI flagshow you launch determines what you get

Every flag is also available via config file or an env var. The CLI is the canonical source โ€” the full CLI reference lists everything including less-used diagnostic flags.

Session control

-c, --continueResume most recent session in this dir
-r, --resume <id>Resume a specific session id or /rename name
--fork-sessionBranch from a resumed session, preserving the original
--from-pr <#>Resume session linked to a PR
-w, --worktree <name>Run in a named git worktree
--teleportMove current session to another cwd
--rename / --nameSet human-readable session name
--add-dir <path>Grant access to another directory

Model & prompt

--model <id>Override session model (alias or full name)
--effort <level>low ยท medium ยท high
--append-system-promptAdd to default system prompt (safe)
--system-prompt[-file]Replace default system prompt (strict)
--agents '<json>'Define subagents inline via JSON
--mcp-config <file>Load MCP servers from a specific JSON file
--plugin-dir <path>Load a local plugin for this session (dev mode)

Headless / automation

-p, --print "q"Non-interactive. Print result, exit.
--output-formattext ยท json ยท stream-json
--max-turns <n>Cap agentic turns
--allowedTools "โ€ฆ"Whitelist tools (comma-sep)
--disallowedTools "โ€ฆ"Deny specific tools
--disable-slash-commandsKill all /cmd
--permission-mode <m>Launch in plan / acceptEdits / bypassPermissions
--setting-sourcesLimit which settings files load
--verbose / --debugDebug logging + MCP handshake logs

Notable flags since 2.1.98

--exclude-dynamic-
system-prompt-sections
Better cross-user prompt caching in print mode
--setting-sourcesRestrict loaded settings to specific sources
System prompt Prefer --append-system-prompt. --system-prompt strips Claude Code's defaults (tool-use framing, safety rails) โ€” only use it when you need full control.
Sessions & forking --continue + --fork-session lets you explore a risky path without destroying the original transcript. Great for "try rewriting this with X, but let me go back if it breaks."
04

Keyboard shortcutslearned in an hour, saved forever

Memorize Esc, Esc Esc, Shift+Tab, Ctrl+B, and Alt/Option+P before anything else. Full list in the interactive mode reference.

Prompt editing

!Bash mode prefix (single command)
@File / folder mention autocomplete
\+EnterNewline in prompt (backslash + Enter)
Alt+EnterNewline (most terminals)
Shift+EnterNewline (run /terminal-setup first)
TabAccept suggestion / add supplementary context
Ctrl+VPaste image
Ctrl+GEdit prompt in external editor ($EDITOR)
Ctrl+UClear entire input buffer

Session control

EscInterrupt Claude
Esc EscOpen rewind menu
โ†‘ after interruptRestore + rewind in one step
Shift+TabCycle: normal โ†’ auto-accept โ†’ plan
Ctrl+BSend task to background
Ctrl+X Ctrl+KStop all background agents
Alt/Option+PSwitch models mid-prompt
Ctrl+RFull output / context pane
Ctrl+OVerbose transcript toggle
Ctrl+TToggle task list (when active)
macOS Option key Alt/Option shortcuts (Alt+B, Alt+F, Alt+P, etc.) require configuring Option as Meta. In iTerm2: Settings โ†’ Profiles โ†’ Keys โ†’ Left/Right Option key = "Esc+". In Terminal.app: Settings โ†’ Profiles โ†’ Keyboard โ†’ "Use Option as Meta Key". In VS Code: "terminal.integrated.macOptionIsMeta": true.
05

Slash commandsbuilt-ins you actually reach for

Type / to open the menu; continue typing to filter. Unknown commands suggest the closest match. Full catalog in the commands reference.

Daily drivers

/initGenerate CLAUDE.md by scanning the repo. Run first in any new project.
/clearWipe conversation history (files on disk remain). Use when switching tasks.
/compact [focus]Compress context while keeping a focus area. Use above ~80% context.
/rewind ยท /undoRestore to a prior checkpoint โ€” conversation, code, or both.
/contextGrouped view of skills, agents, rules, and context usage by category.
/stats ยท /costToken usage ยท spend breakdown for the current session.
/usagePlan usage and rate-limit status.
/model [alias]Switch model. Warns before switching mid-conversation (re-reads history uncached).
/effort [level]Adaptive reasoning tuner: low / medium / high.
/btwAsk a side question without polluting main conversation context.
/helpList everything, filtered as you type.

Project & code

/reviewCode review of recent changes.
/security-reviewAutomated security audit of the diff.
/pr_commentsRead / respond to PR review comments.
/team-onboardingGenerate an onboarding guide for new contributors based on the project structure and CLAUDE.md. 2.1.101
/add-dir [--remember]Grant Claude access to an extra directory. --remember persists to settings.
/memoryEdit CLAUDE.md memory files inline.
/renameGive the session a descriptive name (e.g. oauth-migration).
/sandboxEnable sandboxed Bash tool with filesystem + network isolation.

Extensions & integrations

/agentsManage subagents (project + user scope). Tabbed UI for Running / Library.
/skillsList installed skills. Sort by token cost with t in newer versions.
/pluginPlugin manager UI. install ยท enable ยท disable ยท uninstall.
/reload-pluginsPick up plugin changes without restarting.
/mcpMCP server list + OAuth actions.
/hooksConfigure event hooks.
/permissionsInspect / edit permission rules.
/chromeDrive Chrome via the Claude in Chrome extension. BETA

Session & environment

/configSettings editor (replaces /output-style).
/themeColors + syntax highlighting. Toggle highlight with Ctrl+T.
/statuslineCustomize terminal status line.
/terminal-setupInstall Shift+Enter binding (iTerm2, VS Code, Kitty, Alacritty, Zed, Warp).
/keybindingsEdit ~/.claude/keybindings.json.
/vimVim-style modal editing in the prompt.
/tasksBackground task manager.
/login ยท /logoutAnthropic account auth.
/bug ยท /feedbackReport issues to Anthropic.
/doctorDiagnostics: unreachable permission rules, duplicate MCP configs, missing deps.
Tips Unknown slash commands suggest the closest match (e.g. /revieww โ†’ "did you mean /review?"). MCP-exposed prompts appear as /mcp__<server>__<prompt>.
06

Permission modeswhat Claude can do without asking

Toggle with Shift+Tab. The current mode shows under the prompt. Permission rules layer on top โ€” see the IAM & permissions docs.

normalDefault. Asks before write/edit/bash and sensitive reads.
acceptEdits"YOLO-lite". Accepts file edits automatically. Still asks for risky Bash.
planRead-only brainstorming. Produces a plan file, no writes. End plan to execute.
bypassPermissionsAccepts everything. Only use in sandboxed / throwaway envs. Can be disabled via disableBypassPermissionsMode.

Rule evaluation order

Permission rules evaluate deny โ†’ ask โ†’ allow. First match wins. Use Tool alone or Tool(specifier) โ€” for example, Bash(git push:*) or Read(./.env*). MCP server rules use the server name: mcp__github (whole server) or an exact tool like mcp__github__get_issue. Wildcards on tool names don't exist.

Security PreToolUse hooks returning updatedInput are re-checked against permissions.deny rules. Deny always wins over hook-granted permissions โ€” a hook cannot downgrade a deny into an ask.
07

Models & effortpick the right brain for the task

Claude Code resolves aliases per-provider. On the Anthropic API, opus โ†’ Opus 4.7 and sonnet โ†’ Sonnet 4.6. On Bedrock / Vertex / Foundry, opus โ†’ Opus 4.6 and sonnet โ†’ Sonnet 4.5 (newer models available by explicit name or pinning env var). Always pin versions in production.

Current model aliases

AliasAnthropic APIBedrock / Vertex / FoundryUse for
opusclaude-opus-4-7claude-opus-4-6Architecture, complex reasoning, gnarly debugging
sonnetclaude-sonnet-4-6claude-sonnet-4-5Daily driver. 90 %+ of coding work.
haikuclaude-haiku-4-5claude-haiku-4-5Mechanical edits, routing, high-volume tasks
opusplanhybridOpus for planning, Sonnet for execution
Default Anthropic API defaults to Sonnet. Bedrock / Vertex / Foundry default to Sonnet 4.5. Pin versions for reproducibility with ANTHROPIC_DEFAULT_{OPUS,SONNET,HAIKU}_MODEL.

Switching model

# Launch with a specific model
claude --model claude-sonnet-4-6
claude --model claude-opus-4-7

# Mid-session
/model sonnet
/model opus
/model opusplan

# While typing a prompt
Alt+P  # or Option+P on macOS

Effort levels

lowFast, cheap. Good for mechanical edits, routing, high-volume tasks.
mediumDefault for most tasks. Balanced reasoning and speed.
highDeep chain-of-thought. Use for thorny problems and architecture decisions.
Cost gotcha Switching model mid-conversation re-reads the entire history without prompt-cache benefit โ€” expensive on long sessions. Claude warns you first. Plan to switch at natural breaks (after /clear or /compact).
08

Memory ยท CLAUDE.mdpersistent project brief

Loaded automatically at session start. One per project root, plus a user-global file at ~/.claude/CLAUDE.md. Edit inline via /memory. The first 200 lines or 25 KB โ€” whichever comes first โ€” are loaded into every session's context.

What goes in it

  • Project purpose in 2โ€“3 lines
  • Tech stack, package manager, Node/Python version
  • Commands: dev, test, lint, build, deploy
  • Conventions: commit style, branch names, code style
  • "Do not touch" zones (generated code, migrations, vendored libs)
  • Links to architecture docs (use @path/to/doc.md to import)

What doesn't

  • Secrets โ€” use .env + deny rules instead
  • Everything about the codebase โ€” Claude reads files on demand
  • Rarely-needed reference material โ€” move to a skill
  • Stale instructions โ€” trim aggressively; it costs context every turn

Example skeleton

# BrandName โ€” project management SaaS
  
Stack: Next.js 15 ยท TypeScript ยท Drizzle + Postgres ยท Tailwind.
Package manager: pnpm. Node 20.

## Commands
- Dev: pnpm dev
- Test: pnpm test  (Vitest, watch by default)
- Lint: pnpm lint --fix

## Conventions
- Commit style: Conventional Commits.
- Server components by default; mark client with "use client".
- Never edit db/migrations/** โ€” generate via pnpm db:generate.

## Refs
@docs/architecture.md
@docs/api-contract.md
Rule of thumb Keep CLAUDE.md under 200 lines. If it's growing, move reference content to skills or split into .claude/rules/ files with paths frontmatter that only load when Claude touches matching files.
09

Skills & custom slash commandspackage prompts as first-class assets

Skills and commands have converged. .claude/commands/ still works; .claude/skills/ is the recommended home โ€” it supports auto-invocation, supporting files, subagent execution, and the Agent Skills open standard.

DimensionSlash commandSkill
InvocationUser types /nameModel picks it OR user types /name
Location.claude/commands/*.md.claude/skills/<name>/SKILL.md
StructureSingle fileDirectory + templates, scripts, refs
Best forQuick repeat promptsReusable capabilities shared with team

Authoring a custom command

// .claude/commands/commit.md
---
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)
argument-hint: [message]
description: Create a conventional commit
model: claude-haiku-4-5
---

## Context
- Status: !`git status`
- Diff: !`git diff HEAD`
- Branch: !`git branch --show-current`
- Recent: !`git log --oneline -10`

## Task
Create a single Conventional Commits commit.
Message hint from user: $ARGUMENTS

Authoring a skill

// .claude/skills/api-conventions/SKILL.md
---
name: api-conventions
description: API design rules for this codebase. Use when writing
  or reviewing any route under app/api or services/*.
allowed-tools: Read, Grep, Glob
---

# API conventions

- REST nouns; no verbs in paths.
- Validate inputs with Zod at the route boundary.
- Errors: return { error: { code, message } }, HTTP code matches.
- Server components fetch via typed client in lib/api/.

Argument patterns

  • $ARGUMENTS โ€” all args as one string
  • $1, $2, $3 โ€” positional
  • !`cmd` โ€” run shell command, inject output
  • @path/to/file โ€” inline file contents

Frontmatter keys worth knowing

allowed-toolsRestrict to a tool subset
modelOverride model for this invocation
disable-model-invocationtrue = user-only
context: forkRun in a forked context
agentRun under a named subagent
argument-hintShows in command picker
Description budget Skill descriptions are capped at 1,536 chars. Front-load the use case โ€” when budget is tight, descriptions are truncated. Raise the total budget with SLASH_COMMAND_TOOL_CHAR_BUDGET.
10

Subagentsspecialized workers with their own context

Subagents run in an isolated context window with a custom system prompt and a whitelisted toolset. Use them when a task would pollute the main conversation, or when you want a proactive expert that jumps in automatically. They return a summary, not a full transcript โ€” zero main-context cost.

// .claude/agents/code-reviewer.md
---
name: code-reviewer
description: Proactively reviews code for quality, security,
  maintainability. MUST BE USED immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: inherit
---

You are a senior reviewer. When invoked:
1. Run git diff to see recent changes.
2. Check for: readability, naming, duplication, error handling,
   exposed secrets, input validation, test coverage, performance.
3. Output feedback by priority: Critical ยท Warnings ยท Suggestions.
4. For each, provide a concrete fix.

Invocation

  • Proactive โ€” include "proactively" or "MUST BE USED" in description. Claude invokes automatically.
  • Explicit โ€” "Use the code-reviewer subagent to check my last diff."
  • Chained โ€” "Use debugger then code-reviewer."
  • Inline CLI โ€” claude --agents '{...}' for one-off definitions.

Scope & frontmatter

.claude/agents/Project subagents (highest priority)
~/.claude/agents/Personal subagents
tools / disallowedToolsTool allowlist / denylist
model / effortOverride per-agent
backgroundRun concurrently vs. blocking
isolation: worktreeRun inside a fresh git worktree
memoryPersistent agent-scoped dir
Tip Grant only the tools a subagent needs. A code-reviewer that can't Edit or Write is safer and stays in its lane.
11

Hooksshell scripts on lifecycle events

Danger Hooks run shell commands with your credentials. Never install hooks you haven't read. Malicious hooks can exfiltrate secrets or destroy your filesystem.

Hooks fall into three cadences: once per session (SessionStart, SessionEnd), once per turn (UserPromptSubmit, Stop, StopFailure), every tool call (PreToolUse, PostToolUse). They can be shell commands, HTTP endpoints, or prompts. See the full event schema reference.

EventFires when
SessionStartClaude Code starts or resumes
UserPromptSubmitYou submit a prompt, before Claude sees it. Stdout adds to context.
PreToolUseBefore a tool call. Can block (exit 2) or mutate input.
PostToolUseAfter a tool call completes
PreCompactBefore /compact. Can block with exit 2.
SubagentStopSubagent finished. Gets $AGENT_ID + transcript path.
StopClaude finishes responding
SessionEndSession closes
NotificationClaude fires a notification
SetupRepo setup / maintenance ops

Format & wiring

// .claude/settings.json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command",
            "command": "npx prettier --write \"$FILE_PATH\"" }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          { "type": "command",
            "command": "echo \"$(date): $CONVERSATION_SUMMARY\" >> ~/.claude/activity.log" }
        ]
      }
    ]
  }
}

Exit codes

0Success, continue
2Block tool call, send stderr back to Claude
otherError, surfaces in --debug

Useful env vars inside hooks

  • $FILE_PATH โ€” affected file
  • $CLAUDE_PROJECT_DIR โ€” project root
  • $CLAUDE_SESSION_ID โ€” current session
  • $CONVERSATION_SUMMARY โ€” Stop only
  • $AGENT_ID โ€” SubagentStop only
12

MCP serversexternal tools & services as first-class citizens

Model Context Protocol servers expose tools, resources, and prompts. HTTP transport is preferred over stdio โ€” it's cross-client compatible and easier to manage. See the MCP setup guide.

Management

claude mcp add <name> <cmd>Add stdio server with command
claude mcp add --transport http <name> <url>Add HTTP-transport server
claude mcp add --transport sse <name> <url>Add SSE-transport server
claude mcp listShow installed servers
claude mcp get <name>Details on one server
claude mcp remove <name>Uninstall
/mcp enable|disable <name>Toggle in-session

Tool Search โ€” why 2.1.x MCP scales

When MCP tool descriptions would consume more than 10 % of context, Claude Code loads them dynamically instead of preloading. Set ENABLE_TOOL_SEARCH=true to force it on. Expect ~85 % token reduction on heavy setups and better tool-selection accuracy on Opus.

HTTP transport For Context7, the right pattern is HTTP transport at https://mcp.context7.com/mcp, with the API key in env.CONTEXT7_API_KEY using the ctx7sk_ prefix. Full quit-and-relaunch of Claude Desktop is required after config changes.

Popular connectors โ€” quick reference

GitHubclaude mcp add --transport http github https://api.githubcopilot.com/mcp/
Linearclaude mcp add --transport http linear https://mcp.linear.app/mcp
Notionclaude mcp add --transport http notion https://mcp.notion.com/mcp
Sentryclaude mcp add --transport http sentry https://mcp.sentry.dev/mcp
Vercelclaude mcp add --transport http vercel https://mcp.vercel.com/
Supabasenpx -y @supabase/mcp-server-supabase@latest (stdio, needs SUPABASE_ACCESS_TOKEN)
Stripeclaude mcp add --transport http stripe https://mcp.stripe.com
Playwrightnpx @playwright/mcp@latest (stdio)
Figmaclaude mcp add --transport http figma https://mcp.figma.com/mcp
Cloudflareclaude mcp add --transport http cloudflare https://mcp.cloudflare.com/mcp

MCP-exposed prompts appear as /mcp__<server>__<prompt>. Example: /mcp__github__list_prs.

Enterprise policy

// /etc/claude-code/managed-mcp.json (excerpt)
{
  "allowedMcpServers": [
    { "serverName": "github" },
    { "serverName": "sentry" }
  ],
  "deniedMcpServers": [
    { "serverName": "filesystem" }
  ]
}

Denylist takes absolute precedence over allowlist.

13

Pluginsshare bundles of commands, agents, skills, hooks, MCPs

A plugin is a self-contained directory โ€” the unit of sharing for Claude Code extensions. Install scopes: user (personal), project (checked into git, shared with team), local (project-local, gitignored).

/pluginOpen plugin manager UI
/plugin marketplace add <url|path>Register a marketplace (GitHub org, local dir)
/plugin install <name>@<marketplace>Install
/plugin enable|disable|uninstall <name>@<mkt>Lifecycle
/reload-pluginsPick up plugin changes without restart
claude plugin updatePull latest marketplace versions
claude plugin install <n>@<m> --scope projectInstall to project (shared with team)
claude --plugin-dir <path>Dev-mode: load a local plugin for the session only

Plugin directory shape

my-plugin/
โ”œโ”€โ”€ .claude-plugin/
โ”‚   โ””โ”€โ”€ plugin.json        # manifest (required)
โ”œโ”€โ”€ skills/                # auto-invokable capabilities
โ”œโ”€โ”€ commands/              # flat .md slash commands
โ”œโ”€โ”€ agents/                # subagents
โ”œโ”€โ”€ hooks/                 # hook configs
โ”œโ”€โ”€ monitors/              # background monitors
โ”œโ”€โ”€ .mcp.json              # MCP servers
โ”œโ”€โ”€ .lsp.json              # LSP servers
โ””โ”€โ”€ scripts/
Audit first Plugins ship executable code. Review plugin.json and any hook scripts before enabling. Policy-managed plugins auto-update correctly regardless of where you first installed them from.
14

Background tasks & worktreesparallel work without context thrash

Background tasks

Ctrl+BSend current task to background
Prefix prompt with &Start backgrounded immediately
/tasksList + manage running tasks
Ctrl+X Ctrl+KStop all background agents
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1Disable entirely
Monitor tool The Monitor tool streams events from background scripts โ€” a debugging lifesaver when a long-running subagent misbehaves.

Git worktrees

Run parallel sessions on the same repo without git stash dances. Each worktree keeps its own Claude session with full context. Great for "feature branch + urgent hotfix + model comparison" scenarios.

# Parallel feature + hotfix
git worktree add ../app-auth -b feature/auth main
git worktree add ../app-hotfix -b hotfix/crit main

cd ../app-auth   && claude        # terminal 1
cd ../app-hotfix && claude        # terminal 2

# Claude-native shortcut
claude -w feature/auth
claude --worktree hotfix/crit

The status line JSON input includes workspace.git_worktree, set whenever cwd is inside a linked worktree โ€” handy for custom statuslines. Subagents with isolation: worktree run in a fresh worktree automatically.

15

Headless mode & SDKCI/CD, cron, pipelines

Headless mode (-p/--print) is the backbone of every Claude-in-CI story: PR reviews, security audits, nightly dependency reports, log triage. The Agent SDK gives you the same capabilities from TypeScript or Python, with fine-grained control over permissions, hooks, and approvals.

Print mode essentials

# One-shot
claude -p "summarize the last 10 commits"

# Structured output with metadata (cost, session_id)
claude -p --output-format json "audit this file" > result.json

# Streaming messages for real-time UIs
claude -p --output-format stream-json "long task"

# Pipe in
gh pr diff 123 | claude -p \
  --append-system-prompt "You are a security reviewer" \
  --output-format json \
  --allowedTools "Read,Grep" > audit.json

# Multi-turn via session id
sid=$(claude -p "start analysis" --output-format json | jq -r .session_id)
claude --resume "$sid" -p "now check test coverage"
claude --resume "$sid" -p "summarize findings"

Caching for CI

--exclude-dynamic-system-prompt-sections trims out per-user sections from print mode so cross-user prompt caching actually hits. Worth using on any shared CI job where many runs share a static system prompt.

Agent SDK

// TypeScript โ€” @anthropic-ai/claude-agent-sdk
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const msg of query({
  prompt: "/code-review",
  options: { maxTurns: 3 }
})) {
  // msg has type + payload
  console.log(msg);
}
Tracing Headless/SDK sessions read TRACEPARENT / TRACESTATE from the environment, so Claude Code runs slot into your existing distributed trace tree. Use with OTEL_LOG_TOOL_DETAILS / OTEL_LOG_TOOL_CONTENT for full observability.
16

Config & permissionssettings.json patterns that actually matter

Settings layer from enterprise โ†’ project โ†’ project-local โ†’ user. Full schema in the settings reference. Permission rule syntax is in the IAM reference.

Commands

claude config listAll settings (merged view)
claude config get <key>Read one setting
claude config set <key> <value>Write
claude config add / remove <key> <value>List-valued settings

Safe-default permission template

// .claude/settings.json
{
  "permissions": {
    "allow": [
      "Bash(npm run *)",
      "Bash(pnpm *)",
      "Bash(git status)",
      "Bash(git diff)",
      "Bash(git add *)",
      "Bash(git commit *)"
    ],
    "ask": [
      "Bash(git push:*)",
      "Bash(npm install *)",
      "Bash(pnpm add *)"
    ],
    "deny": [
      "Read(./.env*)",
      "Read(./secrets/**)",
      "Read(./**/credentials*)",
      "Read(./**/*.key)",
      "Read(./**/*.pem)",
      "Bash(rm -rf:*)",
      "Bash(curl:*)",
      "Bash(wget:*)"
    ]
  }
}

Git-ignore essentials

# Keep personal settings out of git
.claude/settings.local.json

# Keep policy-managed hooks + plugin locks IN git
# so the team gets the same behavior
No wildcards on tool names mcp__github__* does nothing. Use "mcp__github" (whole server) or an exact tool name like "mcp__github__get_issue".
Reachability claude doctor warns about unreachable permission rules (e.g. a deny shadowed by an earlier allow). Run it after editing settings.
17

Environment variablesthe knobs that change behavior globally

Any env var can also be set under env in settings.json to apply it to every session. Full list in the environment variables reference.

VariableEffect
ANTHROPIC_MODELDefault model for new sessions
ANTHROPIC_DEFAULT_OPUS_MODELPin Opus alias to a specific version (prod)
ANTHROPIC_DEFAULT_SONNET_MODELPin Sonnet alias
ANTHROPIC_DEFAULT_HAIKU_MODELPin Haiku alias
ANTHROPIC_AUTH_TOKENCustom auth header (proxies)
ANTHROPIC_CUSTOM_HEADERSExtra HTTP headers
API_TIMEOUT_MSPer-request API timeout
ENABLE_LSP_TOOL=1Turn on Language Server Protocol integration
ENABLE_TOOL_SEARCH=trueForce dynamic MCP tool loading
SLASH_COMMAND_TOOL_CHAR_BUDGETRaise the skill-description budget
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1Disable background agents
CLAUDE_CODE_PERFORCE_MODE 2.1.98Fail on read-only edits with a p4 edit hint instead of overwriting
CLAUDE_CODE_SUBPROCESS_ENV_SCRUB 2.1.98Scrub subprocess env + enable PID namespace isolation (Linux)
CLAUDE_CODE_SCRIPT_CAPS 2.1.98Cap per-session script invocations
CLAUDE_CODE_CERT_STOREbundled to use bundled CA store instead of OS trust store
CLAUDE_ENV_FILEExtra env file to source (e.g. ~/.zprofile)
CLAUDE_CODE_TMPDIROverride temp dir
CLAUDE_CODE_GIT_BASH_PATHWindows: path to git-bash
CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1Disable cd carry-over across Bash calls
ENABLE_PROMPT_CACHING_1HOpt into 1-hour prompt cache TTL
FORCE_PROMPT_CACHING_5MForce 5-minute TTL
DISABLE_TELEMETRYDisable usage telemetry
DISABLE_PROMPT_CACHINGKill prompt caching (warns at startup)
OTEL_LOG_USER_PROMPTSOpt-in: include user prompts in OTEL spans
OTEL_LOG_TOOL_DETAILS / _CONTENTOpt-in: tool-call detail in traces
TRACEPARENT / TRACESTATE 2.1.98W3C distributed tracing for Bash subprocesses + SDK
18

Workflows that pay rentbattle-tested patterns, not theoretical ones

Starting points, not scripture. Mix and match for your stack. For richer patterns, see common workflows and best practices.

1. New-project bootstrap

cd your-project
claude
> /init
> # review the generated CLAUDE.md, trim aggressively
> /memory   # add commands, conventions, "do not touch" zones
> /permissions   # lock down .env and secrets

2. Plan โ†’ execute with opusplan

claude --model opusplan
> Shift+Tab Shift+Tab   # enter plan mode
> Plan a migration from REST to GraphQL for the user service.
> # exit plan โ†’ Claude switches to Sonnet for execution

3. Safe parallel work

git worktree add ../app-hotfix -b hotfix/login-500 main
cd ../app-hotfix && claude "fix the 500 on /api/login"
# main project keeps running in the other terminal, full context

4. Automated PR review in CI

# .github/workflows/review.yml (excerpt)
- run: |
    gh pr diff ${{ github.event.number }} | \
      claude -p \
        --append-system-prompt "Senior reviewer. Focus on security, regressions." \
        --output-format json \
        --allowedTools "Read,Grep" \
        --exclude-dynamic-system-prompt-sections \
      > review.json

5. Auto-format on write

// .claude/settings.json
{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Edit|Write",
      "hooks": [{
        "type": "command",
        "command": "npx prettier --write \"$FILE_PATH\" 2>/dev/null || true"
      }]
    }]
  }
}

6. Cost discipline

19

Gotchas & limitsthe things nobody tells you until you hit them