Choose your environment to get started. Most surfaces require a Claude subscription or Anthropic Console account. The Terminal CLI and VS Code also support third-party providers.
The full-featured CLI for working with Claude Code directly in your terminal. Edit files, run commands, and manage your entire project from the command line.
To install Claude Code, use one of the following methods:
Windows PowerShell:
irm https://claude.ai/install.ps1 | iex
macOS, Linux, WSL:
curl -fsSL https://claude.ai/install.sh | bash
Native Windows setups require Git for Windows. Install it first if you don't have it. WSL setups do not need it.
Info
Native installations automatically update in the background to keep you on the latest version.
brew install --cask claude-code
Homebrew offers two casks. claude-code tracks the stable release channel, which is typically about a week behind and skips releases with major regressions. claude-code@latest tracks the latest channel and receives new versions as soon as they ship.
Info
Homebrew installations do not auto-update. Run brew upgrade claude-code or brew upgrade claude-code@latest, depending on which cask you installed, to get the latest features and security fixes.
Then start Claude Code in any project:
cd your-project
claude
You'll be prompted to log in on first use. That's it! Continue with the Quickstart →
Tip
See advanced setup for installation options, manual updates, or uninstallation instructions. Visit troubleshooting if you hit issues.
The VS Code extension provides inline diffs, @-mentions, plan review, and conversation history directly in your editor.
Or search for "Claude Code" in the Extensions view (Cmd+Shift+X on Mac, Ctrl+Shift+X on Windows/Linux). After installing, open the Command Palette (Cmd+Shift+P / Ctrl+Shift+P), type "Claude Code", and select Open in New Tab.
Run Claude Code in your browser with no local setup. Kick off long-running tasks and check back when they're done, work on repos you don't have locally, or run multiple tasks in parallel. Available on desktop browsers and the Claude iOS app.
Start coding at claude.ai/code.
A plugin for IntelliJ IDEA, PyCharm, WebStorm, and other JetBrains IDEs with interactive diff viewing and selection context sharing.
Install the Claude Code plugin from the JetBrains Marketplace and restart your IDE.
Here are some of the ways you can use Claude Code:
Claude Code handles the tedious tasks that eat up your day: writing tests for untested code, fixing lint errors across a project, resolving merge conflicts, updating dependencies, and writing release notes.
claude "write tests for the auth module, run them, and fix any failures"
Describe what you want in plain language. Claude Code plans the approach, writes the code across multiple files, and verifies it works.
For bugs, paste an error message or describe the symptom. Claude Code traces the issue through your codebase, identifies the root cause, and implements a fix. See common workflows for more examples.
Claude Code works directly with git. It stages changes, writes commit messages, creates branches, and opens pull requests.
claude "commit my changes with a descriptive message"
In CI, you can automate code review and issue triage with GitHub Actions or GitLab CI/CD.
The Model Context Protocol (MCP) is an open standard for connecting AI tools to external data sources. With MCP, Claude Code can read your design docs in Google Drive, update tickets in Jira, pull data from Slack, or use your own custom tooling.
CLAUDE.md is a markdown file you add to your project root that Claude Code reads at the start of every session. Use it to set coding standards, architecture decisions, preferred libraries, and review checklists. Claude also builds auto memory as it works, saving learnings like build commands and debugging insights across sessions without you writing anything.
Create custom commands to package repeatable workflows your team can share, like /review-pr or /deploy-staging.
Hooks let you run shell commands before or after Claude Code actions, like auto-formatting after every file edit or running lint before a commit.
Spawn multiple Claude Code agents that work on different parts of a task simultaneously. A lead agent coordinates the work, assigns subtasks, and merges results.
For fully custom workflows, the Agent SDK lets you build your own agents powered by Claude Code's tools and capabilities, with full control over orchestration, tool access, and permissions.
Claude Code is composable and follows the Unix philosophy. Pipe logs into it, run it in CI, or chain it with other tools:
# Analyze recent log output
tail -200 app.log | claude -p "Slack me if you see any anomalies"
# Automate translations in CI
claude -p "translate new strings into French and raise a PR for review"
# Bulk operations across files
git diff main --name-only | claude -p "review these changed files for security issues"
See the CLI reference for the full set of commands and flags.
Run Claude on a schedule to automate work that repeats: morning PR reviews, overnight CI failure analysis, weekly dependency audits, or syncing docs after PRs merge.
/schedule in the CLI./loop repeats a prompt within a CLI session for quick pollingSessions aren't tied to a single surface. Move work between environments as your context changes:
claude --teleport@Claude in Slack with a bug report and get a pull request backEach surface connects to the same underlying Claude Code engine, so your CLAUDE.md files, settings, and MCP servers work across all of them.
Beyond the Terminal, VS Code, JetBrains, Desktop, and Web environments above, Claude Code integrates with CI/CD, chat, and browser workflows:
| I want to... | Best option |
|---|---|
| Continue a local session from my phone or another device | Remote Control |
| Push events from Telegram, Discord, iMessage, or my own webhooks into a session | Channels |
| Start a task locally, continue on mobile | Web or Claude iOS app |
| Run Claude on a recurring schedule | Cloud scheduled tasks or Desktop scheduled tasks |
| Automate PR reviews and issue triage | GitHub Actions or GitLab CI/CD |
| Get automatic code review on every PR | GitHub Code Review |
| Route bug reports from Slack to pull requests | Slack |
| Debug live web applications | Chrome |
| Build custom agents for your own workflows | Agent SDK |
Once you've installed Claude Code, these guides help you go deeper.
Welcome to Claude Code!
This quickstart guide will have you using AI-powered coding assistance in a few minutes. By the end, you'll understand how to use Claude Code for common development tasks.
Make sure you have:
Note
This guide covers the terminal CLI. Claude Code is also available on the web, as a desktop app, in VS Code and JetBrains IDEs, in Slack, and in CI/CD with GitHub Actions and GitLab. See all interfaces.
To install Claude Code, use one of the following methods:
Windows PowerShell:
irm https://claude.ai/install.ps1 | iex
macOS, Linux, WSL:
curl -fsSL https://claude.ai/install.sh | bash
Native Windows setups require Git for Windows. Install it first if you don't have it. WSL setups do not need it.
Info
Native installations automatically update in the background to keep you on the latest version.
brew install --cask claude-code
Homebrew offers two casks. claude-code tracks the stable release channel, which is typically about a week behind and skips releases with major regressions. claude-code@latest tracks the latest channel and receives new versions as soon as they ship.
Info
Homebrew installations do not auto-update. Run brew upgrade claude-code or brew upgrade claude-code@latest, depending on which cask you installed, to get the latest features and security fixes.
Claude Code requires an account to use. When you start an interactive session with the claude command, you'll need to log in:
claude
# You'll be prompted to log in on first use
/login
# Follow the prompts to log in with your account
You can log in using any of these account types:
Once logged in, your credentials are stored and you won't need to log in again. To switch accounts later, use the /login command.
Open your terminal in any project directory and start Claude Code:
cd /path/to/your/project
claude
You'll see the Claude Code welcome screen with your session information, recent conversations, and latest updates. Type /help for available commands or /resume to continue a previous conversation.
Tip
After logging in (Step 2), your credentials are stored on your system. Learn more in Credential Management.
Let's start with understanding your codebase. Try one of these commands:
what does this project do?
Claude will analyze your files and provide a summary. You can also ask more specific questions:
what technologies does this project use?
where is the main entry point?
explain the folder structure
You can also ask Claude about its own capabilities:
what can Claude Code do?
how do I create custom skills in Claude Code?
can Claude Code work with Docker?
Note
Claude Code reads your project files as needed. You don't have to manually add context.
Now let's make Claude Code do some actual coding. Try a simple task:
add a hello world function to the main file
Claude Code will:
Note
Claude Code always asks for permission before modifying files. You can approve individual changes or enable "Accept all" mode for a session.
Claude Code makes Git operations conversational:
what files have I changed?
commit my changes with a descriptive message
You can also prompt for more complex Git operations:
create a new branch called feature/quickstart
show me the last 5 commits
help me resolve merge conflicts
Claude is proficient at debugging and feature implementation.
Describe what you want in natural language:
add input validation to the user registration form
Or fix existing issues:
there's a bug where users can submit empty forms - fix it
Claude Code will:
There are a number of ways to work with Claude:
Refactor code
refactor the authentication module to use async/await instead of callbacks
Write tests
write unit tests for the calculator functions
Update documentation
update the README with installation instructions
Code review
review my changes and suggest improvements
Tip
Talk to Claude like you would a helpful colleague. Describe what you want to achieve, and it will help you get there.
Here are the most important commands for daily use:
| Command | What it does | Example |
|---|---|---|
claude |
Start interactive mode | claude |
claude "task" |
Run a one-time task | claude "fix the build error" |
claude -p "query" |
Run one-off query, then exit | claude -p "explain this function" |
claude -c |
Continue most recent conversation in current directory | claude -c |
claude -r |
Resume a previous conversation | claude -r |
/clear |
Clear conversation history | /clear |
/help |
Show available commands | /help |
exit or Ctrl+D |
Exit Claude Code | exit |
See the CLI reference for a complete list of commands.
For more, see best practices and common workflows.
Instead of: "fix the bug"
Try: "fix the login bug where users see a blank screen after entering wrong credentials"
Break complex tasks into steps:
1. create a new database table for user profiles
2. create an API endpoint to get and update user profiles
3. build a webpage that allows users to see and edit their information
Before making changes, let Claude understand your code:
analyze the database schema
build a dashboard showing products that are most frequently returned by our UK customers
? to see all available keyboard shortcuts/ to see all commands and skillsNow that you've learned the basics, explore more advanced features:
Understand the agentic loop, built-in tools, and how Claude Code interacts with your project
Get better results with effective prompting and project setup
Step-by-step guides for common tasks
Customize with CLAUDE.md, skills, hooks, MCP, and more
/help or ask "how do I..."Release notes for Claude Code, including new features, improvements, and bug fixes by version.
This page is generated from the CHANGELOG.md on GitHub.
Run claude --version to check your installed version.
path parameter to the EnterWorktree tool to switch into an existing worktree of the current repository{"decision":"block"}monitors manifest key that auto-arms at session start or on skill invoke/proactive is now an alias for /loop/doctor layout with status icons; press f to have Claude fix reported issues/config labels and descriptions for clarityWebFetch to strip <style> and <script> contents from fetched pages so CSS-heavy pages no longer exhaust the content budget before reaching actual textjq for JSON, computed Read chunk sizes for text)rich/loguru logging)package.json and lockfile not having dependencies installed automatically after install/update/resume, --worktree, or /branch/model picker on AWS Bedrock in non-US regions persisting invalid us.* model IDs to settings.json when inference profile discovery is still in-flight/help dropping the tab bar, Shortcuts heading, and footer at short terminal heightskeybindings.json being silently loaded instead of rejected with a clear errorCLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC in one project's settings permanently disabling usage metrics for all projects on the machineacceptEdits permission mode when exiting plan mode would downgrade from a higher permission level/team-onboarding command to generate a teammate ramp-up guide from your local Claude Code usageCLAUDE_CODE_CERT_STORE=bundled to use only bundled CAs)/ultraplan and other remote-session features now auto-create a default cloud environment instead of requiring web setup firstclaude -p --resume <name> to accept session titles set via /rename or --namesettings.json no longer causes the entire file to be ignoredallowManagedHooksOnly is set/plugin and claude plugin update to show a warning when the marketplace could not be refreshed, instead of silently reporting a stale versionOTEL_LOG_USER_PROMPTS, OTEL_LOG_TOOL_DETAILS, and OTEL_LOG_TOOL_CONTENT; sensitive span attributes are no longer emitted unless opted inquery to clean up subprocess and temp files when consumers break from for await or use await usingwhich fallback used by LSP binary detection--resume/--continue losing conversation context on large sessions when the loader anchored on a dead-end branch instead of the live conversation--resume chain recovery bridging into an unrelated subagent conversation when a subagent message landed near a main-chain write gap--resume when a persisted Edit/Write tool result was missing its file_pathAPI_TIMEOUT_MSpermissions.deny rules not overriding a PreToolUse hook's permissionDecision: "ask" — previously the hook could downgrade a deny into a prompt--setting-sources without user causing background cleanup to ignore cleanupPeriodDays and delete conversation history older than 30 daysANTHROPIC_AUTH_TOKEN, apiKeyHelper, or ANTHROPIC_CUSTOM_HEADERS set an Authorization headerclaude -w <name> failing with "already exists" after a previous session's worktree cleanup left a stale directorymktemp: No such file or directory after a fresh bootclaude mcp serve tool calls failing with "Tool execution failed" in MCP clients that validate outputSchemaRemoteTrigger tool's run action sending an empty body and being rejected by the server/resume picker issues: narrow default view hiding sessions from other projects, unreachable preview on Windows Terminal, incorrect cwd in worktrees, session-not-found errors not surfacing in stderr, terminal title not being set, and resume hint overlapping the prompt inputrg and self-heals mid-session/btw writing a copy of the entire conversation to disk on every use/context Free space and Messages breakdown disagreeing with the header percentagename: frontmatter, /plugin update failing with ENAMETOOLONG, Discover showing already-installed plugins, directory-source plugins loading from a stale version cache, and skills not honoring context: fork and agent frontmatter fields/mcp menu offering OAuth-specific actions for MCP servers configured with headersHelper; Reconnect is now offered instead to re-invoke the helper scriptctrl+], ctrl+\, and ctrl+^ keybindings not firing in terminals that send raw C0 control bytes (Terminal.app, default iTerm2, xterm)/login OAuth URL rendering with padding that prevented clean mouse selectionsettings.json env values are numbers instead of strings/add-dir --remember, /config) not refreshing the in-memory snapshot, preventing removed directories from being revoked mid-session~/.claude/keybindings.json) not loading on Bedrock, Vertex, and other third-party providersclaude --continue -p not correctly continuing sessions created by -p or the SDK/remote-control failing over SSH when only CLAUDE_CODE_ORGANIZATION_UUID is set/insights sometimes omitting the report file link from its responseCLAUDE_CODE_PERFORCE_MODE env var: when set, Edit/Write/NotebookEdit fail on read-only files with a p4 edit hint instead of silently overwriting themCLAUDE_CODE_SUBPROCESS_ENV_SCRUB is set, and CLAUDE_CODE_SCRIPT_CAPS env var to limit per-session script invocations--exclude-dynamic-system-prompt-sections flag to print mode for improved cross-user prompt cachingworkspace.git_worktree to the status line JSON input, set whenever the current directory is inside a linked git worktreeTRACEPARENT env var to Bash tool subprocesses when OTEL tracing is enabled, so child-process spans correctly parent to Claude Code's trace treeclientInfo in the initialize requestLANG, TZ, NO_COLOR, etc.)/dev/tcp/... or /dev/udp/... not prompting instead of auto-allowingRetry-After — exponential backoff now applies as a minimumoauth.authServerMetadataUrl config override not being honored on token refresh after restart, affecting ADFS and similar IdPs--dangerously-skip-permissions being silently downgraded to accept-edits mode after approving a write to a protected path via Bashpermissions.additionalDirectories changes not applying mid-session — removed directories lose access immediately and added ones work without restartadditionalDirectories revoking access to the same directory passed via --add-dirBash(cmd:*) and Bash(git commit *) wildcard permission rules failing to match commands with extra spaces or tabsBash(...) deny rules being downgraded to a prompt for piped commands that mix cd with other segmentscut -d /, paste -d /, column -s /, awk '{print $1}' file, and filenames containing %toString) causing settings.json to be silently ignored--dangerously-skip-permissions--resume when the edited file was larger than 10KB/resume picker issues: --resume <name> opening uneditable, filter reload wiping search state, empty list swallowing arrow keys, cross-project staleness, and transient task-status text replacing conversation summaries/export not honoring absolute paths and ~, and silently rewriting user-supplied extensions to .txt/effort max being denied for unknown or future model IDsname is a YAML boolean keyword_meta["anthropic/maxResultSizeChars"] not bypassing the token-based persist layerDISABLE_AUTOUPDATER not fully suppressing the npm registry version check and symlink modification on npm-based installsgrep -f FILE / rg -f FILE not prompting when reading a pattern file outside the working directorysandbox.network.allowMachLookup not taking effect on macOS/resume filter hint labels and added project/worktree/branch names in the filter indicator/agents with a tabbed layout: a Running tab shows live subagents, and the Library tab adds Run agent and View running instance actions/reload-plugins to pick up plugin-provided skills without requiring a restartj/k in NORMAL mode now navigate history and select the footer pill at the input boundary--debug/claude-api skill to cover Managed Agents alongside Claude APICLAUDE_CODE_GIT_BASH_PATH is set or Git is installed at a default locationCLAUDE_CODE_MAX_CONTEXT_TOKENS to honor DISABLE_COMPACT when it is set./compact hints when DISABLE_COMPACT is set.Ctrl+O) in NO_FLICKER mode showing prompt, one-line tool summary with edit diffstats, and final responserefreshInterval status line setting to re-run the status line command every N secondsworkspace.git_worktree to the status line JSON input, set when the current directory is inside a linked git worktree● N running indicator in /agents next to agent types with live subagent instances.cedar, .cedarpolicy)--dangerously-skip-permissions being silently downgraded to accept-edits mode after approving a write to a protected pathtoString) causing settings.json to be silently ignoredpermissions.additionalDirectories changes in settings not applying mid-sessionsettings.permissions.additionalDirectories revoking access to the same directory passed via --add-diroauth.authServerMetadataUrl not being honored on token refresh after restart, fixing ADFS and similar IdPsRetry-After — exponential backoff now applies as a minimum/resume picker issues: --resume <name> opening uneditable, Ctrl+A reload wiping search, empty list swallowing navigation, task-status text replacing conversation summary, and cross-project staleness--resume when the edited file was larger than 10KB--resume cache misses and lost mid-turn input from attachment messages not being saved to the transcriptStop/SubagentStop hooks failing on long sessions, and hook evaluator API errors displaying "JSON validation failed" instead of the actual messagecwd: override leaking their working directory back to the parent session's Bash toolclaude plugin update reporting "already at the latest version" for git-based marketplace plugins when the remote had newer commitsname is a YAML boolean keywordNO_FLICKER mode inserting spaces at line breaksNO_FLICKER mode when running inside zellijNO_FLICKER mode when hovering over MCP tool resultsNO_FLICKER mode memory leak where API retries left stale streaming stateNO_FLICKER mode on Windows TerminalNO_FLICKER mode on terminals shorter than 24 rowsNO_FLICKER modeAWS_BEARER_TOKEN_BEDROCK or ANTHROPIC_BEDROCK_BASE_URL are set to empty strings (as GitHub Actions does for unset inputs)LANG=C rm foo, timeout 5 mkdir out)sandbox.network.allowMachLookup now takes effect on macOS@-mention completion to trigger after CJK sentence punctuation, so Japanese/Chinese input no longer requires a space before / or @TRACEPARENT env var when tracing is enabled/claude-api skill to cover Managed Agents alongside the Claude API403 "Authorization header is missing" when using AWS_BEARER_TOKEN_BEDROCK or CLAUDE_CODE_SKIP_BEDROCK_AUTH (regression in 2.1.94)CLAUDE_CODE_USE_MANTLE=1/effort)Slacked #channel header with a clickable channel link for Slack MCP send-message tool callskeep-coding-instructions frontmatter field support for plugin output styleshookSpecificOutput.sessionTitle to UserPromptSubmit hooks for setting the session title"skills": ["./"] now use the skill's frontmatter name for the invocation name instead of the directory basename, giving a stable name across install methodsclaude doctor diagnoses the fixCLAUDE_PLUGIN_ROOT was not set${CLAUDE_PLUGIN_ROOT} resolving to the marketplace source directory instead of the installed cache for local-marketplace plugins on startup❯ caret instead of under the textFORCE_HYPERLINK environment variable being ignored when set via settings.json envus. inference profile ID--resume to resume sessions from other worktrees of the same repo directly instead of printing a cd commandsettings.json files fail to parse, so users know their permission rules are not being appliedforceRemoteSettingsRefresh policy setting: when set, the CLI blocks startup until remote managed settings are freshly fetched, and exits if the fetch fails (fail-closed)/cost for subscription users/release-notes is now an interactive version pickermyhost-graceful-unicorn), overridable with --remote-control-session-name-prefixok:false, and restored preventContinuation:true semantics for non-Stop prompt-type hooksclaude-code → stable, claude-code@latest → latest)ctrl+e jumping to the end of the next line when already at end of line in multiline prompts&/$)/tag command/vim command (toggle vim mode via /config → Editor mode)apply-seccomp helper in both npm and native builds, restoring unix-socket blocking for sandboxed commands_meta["anthropic/maxResultSizeChars"] annotation (up to 500K), allowing larger results like DB schemas to pass through without truncationdisableSkillShellExecution setting to disable inline shell execution in skills, custom slash commands, and plugin commandsclaude-cli://open?q= deep links (encoded newlines %0A no longer rejected)bin/ and invoke them as bare commands from the Bash tool--resume that could lose conversation history when async transcript writes fail silentlycmd+delete not deleting to start of line on iTerm2, kitty, WezTerm, Ghostty, and Windows Terminalpermissions.defaultMode: "auto" in settings.json/feedback now explains why it's unavailable instead of disappearing from the slash menu/claude-api skill guidance for agent design patterns including tool surface decisions, context management, and caching strategystripAnsi on Bun by routing through Bun.stripANSIold_string anchors, reducing output tokens/powerup — interactive lessons teaching Claude Code features with animated demosCLAUDE_CODE_PLUGIN_KEEP_MARKETPLACE_ON_FAILURE env var to keep the existing marketplace cache when git pull fails, useful in offline environments.husky to protected directories (acceptEdits mode)--resume causing a full prompt-cache miss on the first request for users with deferred tools, MCP servers, or custom agents (regression since v2.1.69)Edit/Write failing with "File content has changed" when a PostToolUse format-on-save hook rewrites the file between consecutive editsPreToolUse hooks that emit JSON to stdout and exit with code 2 not correctly blocking the tool call/model, /config, and other selection screens& background job bypass, -ErrorAction Break debugger hang, archive-extraction TOCTOU, and parse-fail fallback deny-rule degradation/resume all-projects view to load project sessions in parallel, improving load times for users with many projects--resume picker to no longer show sessions created by claude -p or SDK invocationsGet-DnsClientCache and ipconfig /displaydns from auto-allow (DNS cache privacy)"defer" permission decision to PreToolUse hooks — headless sessions can pause at a tool call and resume with -p --resume to have the hook re-evaluateCLAUDE_CODE_NO_FLICKER=1 environment variable to opt into flicker-free alt-screen rendering with virtualized scrollbackPermissionDenied hook that fires after auto mode classifier denials — return {retry: true} to tell the model it can retry@ mention typeahead suggestionsMCP_CONNECTION_NONBLOCKING=true for -p mode to skip the MCP connection wait entirely, and bounded --mcp-config server connections at 5s instead of blocking on the slowest server/permissions → Recent tab where you can retry with rEdit(//path/**) and Read(//path/**) allow rules to check the resolved symlink target, not just the requested pathStructuredOutput schema cache bug causing ~50% failure rate when using multiple schemas~/.claude/history.jsonl/stats undercounting tokens by excluding subagent usage, and losing historical data beyond 30 days when the stats cache format changes-p --resume hangs when the deferred tool input exceeds 64KB or no deferred marker exists, and -p --continue not resuming deferred toolsclaude-cli:// deep links not opening on macOSfile_path as an absolute path for Write/Edit/Read tools, matching the documented behavior--resume crash when transcript contains a tool result from an older CLI version or interrupted writeif condition filtering not matching compound commands (ls && git push) or commands with env-var prefixes (FOO=bar git push)invalidates not clearing the currently-displayed notification immediatelygit push wrote progress to stderr on Windows PowerShell 5.1ls/tree/du instead of "Read N files"@-mention typeahead to rank source files above MCP resources with similar namesEdit to work on files viewed via Bash with sed -n or cat, without requiring a separate Read call firstcleanupPeriodDays: 0 in settings.json to be rejected with a validation error — it previously silently disabled transcript persistenceshowThinkingSummaries: true in settings.json to restoreTaskCreated hook event and its blocking behavior/env now applies to PowerShell tool commands (previously only affected Bash)/usage now hides redundant "Current week (Sonnet only)" bar for Pro and Enterprise plans!command into an empty prompt now enters bash mode, matching typed ! behavior/buddy is here for April 1st — hatch a small creature that watches you codeX-Claude-Code-Session-Id header to API requests so proxies can aggregate requests by session without parsing the body.jj and .sl to VCS directory exclusion lists so Grep and file autocomplete don't descend into Jujutsu or Sapling metadata--resume failing with "tool_use ids were found without tool_result blocks" on sessions created before v2.1.85~/.claude/CLAUDE.md) when conditional skills or rules are configured/feedback on very long sessions with large transcript files--bare mode dropping MCP tools in interactive sessions and silently discarding messages enqueued mid-turnc shortcut copying only ~20 characters of the OAuth login URL instead of the full URL/model in one of them/plugin uninstall dialog: pressing n now correctly uninstalls the plugin while preserving its data directoryultrathink hint lingering after deleting the keyword@ — raw string content no longer JSON-escaped/skills listing are now capped at 250 characters to reduce context usage/skills menu to sort alphabetically for easier scanningCLAUDE_CODE_MCP_SERVER_NAME and CLAUDE_CODE_MCP_SERVER_URL environment variables to MCP headersHelper scripts, allowing one helper to serve multiple serversif field for hooks using permission rule syntax (e.g., Bash(git *)) to filter when they run, reducing process spawning overhead/loop, CronCreate) fire[Image #N] placeholder when pasting imagesclaude-cli://open?q=…) now support up to 5,000 characters, with a "scroll to review" warning for long pre-filled promptsmanaged-settings.json) can no longer be installed or enabled, and are hidden from marketplace viewsAskUserQuestion by returning updatedInput alongside permissionDecision: "allow", enabling headless integrations that collect answers via their own UItool_parameters in OpenTelemetry tool_result events are now gated behind OTEL_LOG_TOOL_DETAILS=1/compact failing with "context exceeded" when the conversation has grown too large for the compact request itself to fit/plugin enable and /plugin disable failing when a plugin's install location differs from where it's declared in settings--worktree exiting with an error in non-git repositories before the WorktreeCreate hook could rundeniedMcpServers setting not blocking claude.ai MCP serversswitch_display in the computer-use tool returning "not available in this session" on multi-monitor setupsOTEL_LOGS_EXPORTER, OTEL_METRICS_EXPORTER, or OTEL_TRACES_EXPORTER is set to none403 insufficient_scope now correctly trigger the re-authorization flowtype:'sdk' MCP servers passed via --mcp-config are no longer dropped during startupANTHROPIC_DEFAULT_{OPUS,SONNET,HAIKU}_MODEL_SUPPORTS env vars to override effort/thinking capability detection for pinned default models for 3p (Bedrock, Vertex, Foundry), and _MODEL_NAME/_DESCRIPTION to customize the /model picker labelCLAUDE_STREAM_IDLE_TIMEOUT_MS env var to configure the streaming idle watchdog threshold (default 90s)TaskCreated hook that fires when a task is created via TaskCreateWorktreeCreate hook support for type: "http" — return the created worktree path via hookSpecificOutput.worktreePath in the response JSONallowedChannelPlugins managed setting for team/enterprise admins to define a channel plugin allowlistx-client-request-id header to API requests for debugging timeouts/clear, reducing unnecessary token re-caching on stale sessionsclaude-cli://) now open in your preferred terminal instead of whichever terminal happens to be first in the detection listpaths: frontmatter now accepts a YAML list of globsToolSearch is enabled, including for users with MCP tools configuredCtrl+U (kill-to-line-start) being a no-op at line boundaries in multiline input, so repeated Ctrl+U now clears across lines"ctrl+x ctrl+k": null) still entering chord-wait mode instead of freeing the prefix key--json-schema and the subagent also specifies a schemaEdit(.claude) allow rulesC:\, C:\Windows, etc.)setup in parallel with slash command and agent loadingclaude "prompt" with MCP servers — the REPL now renders immediately instead of blocking until all servers connectowner/repo#123 — bare #123 is no longer auto-linked/voice, /mobile, /chrome, /upgrade, etc.) are now hidden instead of shownmanaged-settings.d/ drop-in directory alongside managed-settings.json, letting separate teams deploy independent policy fragments that merge alphabeticallyCwdChanged and FileChanged hook events for reactive environment management (e.g., direnv)sandbox.failIfUnavailable setting to exit with an error when sandbox is enabled but cannot start, instead of running unsandboxeddisableDeepLinkRegistration setting to prevent claude-cli:// protocol handler registrationCLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1 to strip Anthropic and cloud provider credentials from subprocess environments (Bash tool, hooks, MCP stdio servers)/ in transcript mode (Ctrl+O) to search, n/N to step through matchesCtrl+X Ctrl+E as an alias for opening the external editor (readline-native binding; Ctrl+G still works)[Image #N] chip at the cursor so you can reference them positionally in your promptinitialPrompt in frontmatter to auto-submit a first turnchat:killAgents and chat:fastMode are now rebindable via ~/.claude/keybindings.json--mcp-config CLI flag bypassing allowedMcpServers/deniedMcpServers managed policy enforcement--print modecaffeinate process not properly terminating when Claude Code exits, preventing Mac from sleeping!-prefixed command suggestions/config menu showing both the search cursor and list selection at the same time--channels showing "Channels are not currently available" on first launch after upgradeCtrl+B interfering with readline backward-char at an idle prompt — it now only fires when a foreground task can be backgroundedcleanupPeriodDays settingwhich is kernel-restricted--resume memory usage and startup latency on large sessionsWebFetch to identify as Claude-User so site operators can recognize and allowlist Claude Code traffic via robots.txtWebFetch peak memory usage for large pagesclaude -p startup with unauthenticated HTTP/SSE MCP servers (~600ms saved)/status now works while Claude is responding, instead of being queued until the turn finishesXDG_DATA_HOME when registering the claude-cli:// protocol handlerCtrl+F to Ctrl+X Ctrl+K to stop shadowing readline forward-charTaskOutput tool in favor of using Read on the background task's output file pathCLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK env var to disable the non-streaming fallback when streaming failsmanifest.userConfig) now available externally — plugins can prompt for configuration at enable time, with sensitive: true values stored in keychain (macOS) or protected credentials file (other platforms)Ctrl+L now clears the screen and forces a full redraw — use this to recover when Cmd+K leaves the UI partially blank. Use Ctrl+U or double-Esc to clear prompt input.--bare -p (SDK pattern) is ~14% faster to the API requestMEMORY.md index now truncates at 25KB as well as 200 linesAskUserQuestion and plan-mode tools when --channels is activerg ... | wc -l and similar piped commands hanging and returning 0 in sandbox mode on Linux--worktree hanging silently when the worktree name contained a forward slash/rewind) to open a keyboard-navigable rewind picker--bare flag for scripted -p calls — skips hooks, LSP, plugin sync, and skill directory walks; requires ANTHROPIC_API_KEY or an apiKeyHelper via --settings (OAuth and keychain auth disabled); auto-memory fully disabled--channels permission relay — channel servers that declare the permission capability can forward tool approval prompts to your phoneCLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS not suppressing the structured-outputs beta header, causing 400 errors on proxy gateways forwarding to Vertex/Bedrock--channels bypass for Team/Enterprise orgs with no other managed settings configured/btw not including pasted text when used during an active response/rename not syncing the title for Remote Control sessions/exit not reliably archiving the session{server}" line (expand with Ctrl+O)! bash mode discoverability — Claude now suggests it when you need to run an interactive command"showClearContextOnPlanAccept": true)rate_limits field to statusline scripts for displaying Claude.ai rate limit usage (5-hour and 7-day windows with used_percentage and resets_at)source: 'settings' plugin marketplace source — declare plugin entries inline in settings.jsoneffort frontmatter support for skills and slash commands to override the model effort level when invoked--channels (research preview) — allow MCP servers to push messages into your session--resume dropping parallel tool results — sessions with parallel tool calls now restore all tool_use/tool_result pairs instead of showing [Tool result missing] placeholders/remote-control appearing for gateway and third-party provider deployments where it cannot function/sandbox tab switching not responding to Tab or arrow keys@ file autocomplete in large git repositories/effort to show what auto currently resolves to, matching the status bar indicator/permissions — Tab and arrow keys now switch tabs from within a list/plugin install command instead of a two-step flowenabledPlugins, permissions.defaultMode, policy-set env vars) not being applied at startup when remote-settings.json was cached from a prior session--console flag to claude auth login for Anthropic Console (API billing) authentication/config menuclaude -p hanging when spawned as a subprocess without explicit stdin (e.g. Python subprocess.run)-p (print) mode/btw returning the main agent's output instead of answering the side question when triggered during streamingvoiceEnabled: true is set/permissionsCLAUDE_CODE_DISABLE_TERMINAL_TITLE not preventing terminal title from being set on startupSessionEnd hooks not firing when using interactive /resume to switch sessionsCLAUDE_CODE_PLUGIN_SEED_DIR now supports multiple seed directories separated by the platform path delimiter (: on Unix, ; on Windows)/remote-control — bridge your session to claude.ai/code to continue from a browser or phoneStopFailure hook event that fires when the turn ends due to an API error (rate limit, auth failure, etc.)${CLAUDE_PLUGIN_DATA} variable for plugin persistent state that survives plugin updates; /plugin uninstall prompts before deleting iteffort, maxTurns, and disallowedTools frontmatter support for plugin-shipped agentsset -g allow-passthrough ongit log HEAD failing with "ambiguous argument" inside sandboxed Bash on Linux, and stub files polluting git status in the working directorycc log and --resume silently truncating conversation history on large sessions (>5 MB) that used subagentsdeny: ["mcp__servername"] permission rules not removing MCP server tools before sending to the model, allowing it to see and attempt blocked toolssandbox.filesystem.allowWrite not working with absolute paths (previously required // prefix)/sandbox Dependencies tab showing Linux prerequisites on macOS instead of macOS-specific infosandbox.enabled: true is set but dependencies are missing — now shows a visible startup warning.git, .claude, and other protected directories being writable without a prompt in bypassPermissions mode--worktree flag not loading skills and hooks from the worktree directoryCLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS and includeGitInstructions setting not suppressing the git status section in the system promptANTHROPIC_CUSTOM_MODEL_OPTION env var to add a custom entry to the /model picker, with optional _NAME and _DESCRIPTION suffixed vars for displayANTHROPIC_BETAS environment variable being silently ignored when using Haiku modelsallowRead sandbox filesystem setting to re-allow read access within denyRead regions/copy now accepts an optional index: /copy N copies the Nth-latest assistant responsecd src && npm test) saving a single rule for the full string instead of per-subcommand, leading to dead rules and repeated permission prompts--resume silently truncating recent conversation history due to a race between memory-extraction writes and the main transcript"allow" bypassing deny permission rules, including enterprise managed settingsCLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS not stripping beta tool-schema fields, causing proxy gateways to reject requests/feedback text input deleting forward instead of the second press exiting the sessiongit-subdir plugins at different subdirectories of the same monorepo commit colliding in the plugin cache/mcp or similar dialogs while the agent is running⌘V or tmux prefix+]←/→ accidentally switching tabs in settings, permissions, and sandbox dialogs while navigating lists--resume on fork-heavy and very large sessions — up to 45% faster loading and ~100-150MB less peak memoryclaude plugin validate to check skill, agent, and command frontmatter plus hooks/hooks.json, catching YAML parse errors and schema violationsCLAUDE_CODE_PLUGIN_SEED_DIRapiKeyHelper takes longer than 10s, preventing it from blocking the main loopresume parameter — use SendMessage({to: agentId}) to continue a previously spawned agentSendMessage now auto-resumes stopped agents in the background instead of returning an error/fork to /branch (/fork still works as an alias)macOptionClickForcesSelection settingElicitation and ElicitationResult hooks to intercept and override responses before they're sent back-n / --name <name> CLI flag to set a display name for the session at startupworktree.sparsePaths setting for claude --worktree in large monorepos to check out only the directories you need via git sparse-checkoutPostCompact hook that fires after compaction completes/effort slash command to set model effort levelfeedbackSurveyRate settingToolSearch) losing their input schemas after conversation compaction, causing array and number parameters to be rejected with type errors/voice not working on Windows when installed via npmmodel: frontmatter on a 1M-context sessionBash(cmd:*) permission rules not matching when a quoted argument contains #/export showing only the filename instead of the full file path in the success message--worktree startup performance by reading git refs directly and skipping redundant git fetch when the remote branch is already available locally/voice to show your dictation language on enable and warn when your language setting isn't supported for voice input--plugin-dir to only accept one path to support subcommands — use repeated --plugin-dir for multiple directories/color command for all users to set a prompt-bar color for your session/rename/voice twice/model or Option+P! in piped commands (e.g., jq 'select(.x != .y)' now works correctly)/plugin Installed tab — plugins force-disabled by your organization are now hiddentool_use blocks, preventing premature context compaction/resume losing session names after resuming a forked or continued session/status dialog after visiting the Config tab--verbose or transcript mode)C:\ProgramData\ClaudeCode\managed-settings.json — use C:\Program Files\ClaudeCode\managed-settings.json/context command — identifies context-heavy tools, memory bloat, and capacity warnings with specific optimization tipsautoMemoryDirectory setting to configure a custom directory for auto-memory storageask rules being bypassed by user allow rules or skill allowed-toolsclaude-opus-4-5) being silently ignored in agent frontmatter model: field and --agents JSON config — agents now accept the same model values as --modelaudio-input entitlement so macOS prompts correctlySessionEnd hooks being killed after 1.5 s on exit regardless of hook.timeout — now configurable via CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS/plugin install failing inside the REPL for marketplace plugins with local sources--plugin-dir so local dev copies now override installed marketplace plugins with the same name (unless that plugin is force-enabled by managed settings)modelOverrides setting to map model picker entries to custom provider model IDs (e.g. Bedrock inference profile ARNs)NODE_EXTRA_CA_CERTS)git pull in a repo with a large .claude/skills/ directory)model: opus/sonnet/haiku being silently downgraded to older model versions on Bedrock, Vertex, and Microsoft Foundry/resume showing the current session in the picker/ide crashing with onInstall is not defined when auto-installing the extension/loop not being available on Bedrock/Vertex/Foundry and when telemetry was disabled--resume or --continue/heapdump failing on Windows with EEXIST error when the Desktop folder already exists/effort to work while Claude is responding, matching /model behavior/output-style command — use /config instead. Output style is now fixed at session start for better prompt cachingANTHROPIC_BASE_URL as long as ENABLE_TOOL_SEARCH is set.w key in /copy to write the focused selection directly to a file, bypassing the clipboard (useful over SSH)/plan (e.g., /plan fix the auth bug) that enters plan mode and immediately startsExitWorktree tool to leave an EnterWorktree sessionCLAUDE_CODE_DISABLE_CRON environment variable to immediately stop scheduled cron jobs mid-sessionlsof, pgrep, tput, ss, fd, and fdfind to the bash auto-approval allowlist, reducing permission prompts for common read-only operationsmodel parameter on the Agent tool for per-invocation model overrides/effort auto to reset to default/config — Escape now cancels changes, Enter saves and closes, Space toggles settings<!-- ... -->) to be hidden from Claude when auto-injected. Comments remain visible when read with the Read tool--continue not resuming from the most recent point after --compact.git suffix (Azure DevOps, AWS CodeCommit)EEXIST error in OneDrive folders, marketplace blocking user-scope installs when a project-scope install exists, CLAUDE_CODE_PLUGIN_CACHE_DIR creating literal ~ directories, and plugin.json with marketplace-only fields failing to load--effort CLI flag being reset by unrelated settings writes on startup/clear/clear killing background agent/bash tasks — only foreground tasks are now clearedworktreePath and worktreeBranch/model not displaying results when run while Claude is working/tmp/claude/) prompting unnecessarilyquery calls, reducing input token costs up to 12xtranscript_path pointing to the wrong directory for resumed/forked sessions, agent prompt being silently deleted from settings.json on every settings write, PostToolUse block reason displaying twice, async hooks not receiving stdin with bash read -r, and validation error message showing an example that fails validationCLAUDE_CODE_DISABLE_TERMINAL_TITLE was setsandbox.excludedCommands failing with env var prefixes; "always allow" suggesting overly broad prefixes for nested CLI tools; and deny rules not applying to all command formsvscode://anthropic.claude-code/open URI handler to open a new Claude Code tab programmatically, with optional prompt and session query parameters/loop command to run a prompt or slash command on a recurring interval (e.g. /loop 5m check the deploy)voice:pushToTalk keybinding to make the voice activation key rebindable in keybindings.json (default: space) — modifier+letter combos like meta+k have zero typing interferencefmt, comm, cmp, numfmt, expr, test, printf, getconf, seq, tsort, and pr to the bash auto-approval allowlist/fork) sharing the same plan file, which caused plan edits in one fork to overwrite the other/plugin marketplace update failing with merge conflicts when the marketplace is pinned to a branch/tag ref/plugin marketplace add owner/repo@ref incorrectly parsing @ — previously only # worked as a ref separator, causing undiagnosable errors with strictKnownMarketplaces/permissions Workspace tab when the same directory is added with and without a trailing slash--print hanging forever when team agents are configured — the exit loop no longer waits on long-lived in_process_teammate tasksToolSearch callcd <cwd> && git ... on Windows when the model uses a mingw-style path/plugin uninstall to disable project-scoped plugins in .claude/settings.local.json instead of modifying .claude/settings.json, so changes don't affect teammates/plugin menu./debug to toggle debug logging on mid-session, since debug logs are no longer written by defaultANTHROPIC_BASE_URL with a third-party gateway — tool search now correctly detects proxy endpoints and disables tool_reference blocksAPI Error: 400 This model does not support the effort parameter when using custom Bedrock inference profiles or other model identifiers not matching standard Claude naming patternsToolSearch — the server renders tool schemas with system-prompt-style tags at the prompt tail, which could confuse models into stopping earlyinstructions connects after the first turnSet-ClipboardvoiceEnabled: true was set in settings#NNN references incorrectly pointing to the current repository instead of the linked URL.claude/settings.json has a legacy Opus model string pinned/plugin/security-review command failing with unknown option merge-base on older git versions/color command having no way to reset back to the default color — /color default, /color gray, /color reset, and /color none now restore the defaultAskUserQuestion preview dialog that re-ran markdown rendering on every keystroke in the notes inputpermissions.defaultMode settings values other than acceptEdits or plan being applied in Claude Code Remote environments — they are now ignored--resume (~600 tokens saved per resume)/rename to work while Claude is processing, instead of being silently queued/poll rate to once per 10 minutes while connected (was 1–2s), cutting server load ~300×. Reconnection is unaffected — transport loss immediately wakes fast polling./mcp in the chat panel to enable/disable servers, reconnect, and manage OAuth authentication without switching to the terminal/claude-api skill for building applications with the Claude API and Anthropic SDK!) to exit bash mode, matching escape and backspace/remote-control and claude remote-control (/remote-control My Project or --name "My Project") to set a custom session title visible in claude.ai/codeclaude --agentsandbox.enableWeakerNetworkIsolation setting (macOS only) to allow Go programs like gh, gcloud, and terraform to verify TLS certificates when using a custom MITM proxy with httpProxyPortincludeGitInstructions setting (and CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS env var) to remove built-in commit and PR workflow instructions from Claude's system prompt/reload-plugins command to activate pending plugin changes without restarting${CLAUDE_SKILL_DIR} variable for skills to reference their own directory in SKILL.md contentInstructionsLoaded hook event that fires when CLAUDE.md or .claude/rules/*.md files are loaded into contextagent_id (for subagents) and agent_type (for subagents and --agent) to hook eventsworktree field to status line hook commands with name, path, branch, and original repo directory when running in a --worktree sessionpluginTrustMessage in managed settings to append organization-specific context to the plugin trust warning shown before installationpathPattern to strictKnownMarketplaces for regex-matching file/directory marketplace sources alongside hostPattern restrictionsgit-subdir to point to a subdirectory within a git repooauth.authServerMetadataUrl config option for MCP servers to specify a custom OAuth metadata discovery URL when standard discovery failsnode_modules.mcp.json servers on first run. You'll now see the per-server approval dialog as expectedclaude remote-control crashing immediately on npm installs with "bad option: --sdk-url" (anthropics/claude-code#28334)--model claude-opus-4-0 and --model claude-opus-4-1 resolving to deprecated Opus versions instead of currentsecurity -i stdin buffer, silently leaving stale credentials behind and causing repeated /login prompts..credentials.json losing subscriptionType (showing "Claude API" instead of "Claude Pro"/"Claude Max") when the profile endpoint transiently fails during token refresh (anthropics/claude-code#30185).bashrc, HEAD, etc.) appearing as untracked files in the working directory after sandboxed Bash commands on Linux[27;2;13~ instead of inserting a newline in Ghostty over SSH/stats crash when transcript files contain entries with missing or malformed timestamps--setting-sources user not blocking dynamically discovered project skillsclaude -w)/plugin operation${CLAUDE_PLUGIN_ROOT}/... command templatename parameterCLAUDE_CODE_MAX_OUTPUT_TOKENS being ignored during conversation compaction/compact summary rendering as a user bubble in SDK consumers (Claude Code Remote web UI, VSCode extension).claude folder detection on WindowsacceptEdits modeallowManagedDomainsOnly is enabled in managed settings — non-allowed domains are now blocked automatically with no bypassAskUserQuestion) being silently auto-allowed when listed in a skill's allowed-tools, bypassing the permission prompt and running with empty answers/voice, /cost) in Remote Control sessionsmemoCache over long sessions/clear or auto-compact--mcp-config points to a corrupted filecd <outside-dir> && <cmd> permission prompt to surface the chained command instead of only showing "Yes, allow reading from <dir>/".claude/rules/*.md files (with paths: frontmatter) and nested CLAUDE.md files not loading in print mode (claude -p)/clear not fully clearing all session caches, reducing memory retention in long sessionsTeammateIdle and TaskCompleted hooks to support {"continue": false, "stopReason": "..."} to stop the teammate, matching Stop hook behaviorWorktreeCreate and WorktreeRemove plugin hooks being silently ignoreddescription: frontmatter field not appearing in Claude's available skills list/context showing identical token counts for all MCP tools from a servernul file creation on Windows when the model uses CMD-style 2>nul redirection in Git Bash/config search box is focused but empty[ERROR] logs with 403s from profile-scoped endpoints--worktree startup by eliminating a git subprocess on the startup path-p startup by pipelining claude.ai config fetch with local connections and using a concurrency pool instead of sequential batchingonSubmit across message updates--append-system-prompt-file and --system-prompt-file work in interactive mode (the docs previously said print mode only)/resume picker to show your most recent prompt instead of the first one. This also resolves some titles appearing as (session).activeForm field — the spinner falls back to the task subjectpermissions.disableBypassPermissionsMode from your effective Claude Code settings (including managed/policy settings) — when set to disable, bypass permissions mode is hidden from the picker/model/simplify and /batch bundled slash commandsENABLE_CLAUDEAI_MCP_SERVERS=false env var to opt out from making claude.ai MCP servers available/model command to show the currently active model in the slash command menu/copy picker. When selected, future /copy commands will skip the code block picker and copy the full response directly./clear not resetting cached skills, which could cause stale skill content to persist in the new conversation/copy command to show an interactive picker when code blocks are present, allowing selection of individual code blocks or the full response.cd /tmp && git fetch && git push) to compute smarter per-subcommand prefixes instead of treating the whole command as one--worktree sometimes being ignored on first launchclaude remote-control subcommand for external builds, enabling local environment serving for all users.CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS to configure.-l flag) by default when a shell snapshot is available, improving command execution performance. Previously this required setting CLAUDE_BASH_NO_LOGIN=true.statusLine and fileSuggestion hook commands could execute without workspace trust acceptance in interactive mode.control_response messages (e.g. from WebSocket reconnects) could cause API 400 errors by pushing duplicate assistant messages into the conversation.CLAUDE_CODE_ACCOUNT_UUID, CLAUDE_CODE_USER_EMAIL, and CLAUDE_CODE_ORGANIZATION_UUID environment variables for SDK callers to provide account info synchronously, eliminating a race condition where early telemetry events lacked account metadata./model picker now shows human-readable labels (e.g., "Sonnet 4.5") instead of raw model IDs for pinned model versions, with an upgrade hint when a newer version is available.startupTimeout configuration for LSP serversWorktreeCreate and WorktreeRemove hook events, enabling custom VCS setup and teardown when agent worktree isolation creates or removes worktrees.CLAUDE_CODE_SIMPLE to fully strip down skills, session memory, custom agents, and CLAUDE.md token counting/mcp reconnect freezing the CLI when given a server name that doesn't existisolation: worktree in agent definitions, allowing agents to declaratively run in isolated git worktrees.CLAUDE_CODE_SIMPLE mode now also disables MCP tools, attachments, hooks, and CLAUDE.md file loading for a fully minimal experience.claude agents CLI command to list all configured agents-p flag) by deferring Yoga WASM and UI component importsCLAUDE_CODE_DISABLE_1M_CONTEXT environment variable to disable 1M context window support/extra-usage command support in VS Code sessions--worktree (-w) flag to start Claude in an isolated git worktreeisolation: "worktree" for working in a temporary git worktreebackground: true to always run as a background tasksettings.json for default configurationplugin enable and plugin disable to auto-detect the correct scope when --scope is not specified, instead of always defaulting to user scopeCLAUDE_CODE_SIMPLE) now includes the file edit tool in addition to the Bash tool, allowing direct file editing in simple mode./config — memo comparators now correctly detect verbose changes-p) by skipping unnecessary API calls during startupsupportsEffort, supportedEffortLevels, and supportsAdaptiveThinking fields so consumers can discover model capabilities.ConfigChange hook event that fires when configuration files change during a session, enabling enterprise security auditing and optional blocking of settings changes.disableAllHooks setting to respect managed settings hierarchy — non-managed settings can no longer disable managed hooks set by policy (#26637)--resume session picker showing raw XML tags for sessions that start with commands like /clear. Now correctly falls through to the session ID fallback.trimEnd.os.EOL (\r\n) in display code — line counts now show correct values instead of always showing 1 on Windows.\r\n line endings.@ file mentions - file suggestions now appear faster by pre-warming the index on startup and using session-based caching with background refresh.ctrl+f to kill all background agents instead of double-pressing ESC. Background agents now continue running when you press ESC to cancel the main thread, giving you more control over agent lifecycle.last_assistant_message field to Stop and SubagentStop hook inputs, providing the final assistant response text so hooks can access it without parsing transcript files./rename being lost after resuming a conversation (anthropics/claude-code#23610)\) would produce spurious empty arguments, potentially breaking command execution./help, /model, /compact, etc.) being hidden from the autocomplete dropdown when many user skills are installed (anthropics/claude-code#22020)/clear command (anthropics/claude-code#26082)name or description in SKILL.md frontmatter is a bare number (e.g., name: 3000) — the value is now properly coerced to a string (anthropics/claude-code#25837)chat:newline keybinding action for configurable multi-line input (anthropics/claude-code#26075)added_dirs to the statusline JSON workspace section, exposing directories added via /add-dir to external scripts (anthropics/claude-code#26096)claude doctor misclassifying mise and asdf-managed installations as native installs (anthropics/claude-code#26033)model field in .claude/agents/*.md being ignored when spawning team teammates (anthropics/claude-code#26064)alwaysThinkingEnabled: true in settings.json not enabling thinking mode on Bedrock and Vertex providers (anthropics/claude-code#26074)tool_decision OTel telemetry event not being emitted in headless/SDK mode (anthropics/claude-code#26059)/resume <session-id> failing to find sessions whose first message exceeds 16KB (anthropics/claude-code#25920)argument-hint in SKILL.md frontmatter uses YAML sequence syntax (e.g., [topic: foo | bar]) — the value is now properly coerced to a string (anthropics/claude-code#25826)/fork on sessions that used web search — null entries in search results from transcript deserialization are now handled gracefully (anthropics/claude-code#25811).claude/agents/ and .claude/skills/ from the main repository are now included (anthropics/claude-code#25816)claude doctor and claude plugin validate being blocked inside nested Claude sessions (anthropics/claude-code#25803)findReferences and other location-based operations returning results from gitignored files (e.g., node_modules/, venv/) (anthropics/claude-code#26051)~/.claude/backups/ to reduce home directory clutter (anthropics/claude-code#26130)__git_ps1) not being preserved across shell sessions (anthropics/claude-code#25824)[25~ escape sequence residue in the input field on Windows/Git Bash terminals (anthropics/claude-code#25943)/rename command now updates the terminal tab title by default (anthropics/claude-code#25789)enabledPlugins and extraKnownMarketplaces from --add-dir directoriesspinnerTipsOverride setting to customize spinner tips — configure tips with an array of custom tip strings, and optionally set excludeDefault: true to show only your custom tips instead of the built-in onesSDKRateLimitInfo and SDKRateLimitEvent types to the SDK, enabling consumers to receive rate limit status updates including utilization, reset times, and overage informationReferenceError on completion (anthropics/claude-code#22087).claude.json.backup files accumulating on every startup.claude/agents/ directoryspeed attribute to OTel events and trace spans for fast mode visibilityclaude auth login, claude auth status, and claude auth logout CLI subcommands/rename to auto-generate session name from conversation context when called without arguments@README.md#installation)/dev/stdin, and large files.claude/skills directory in sandbox modesandbox.excludedCommands or dangerouslyDisableSandbox) could bypass the Bash ask permission rule when autoAllowBashIfSandboxed was enabledTeammateIdle and TaskCompleted hook events for multi-agent workflowsTask(agent_type) syntax in agent "tools" frontmattermemory frontmatter field support for agents, enabling persistent memory with user, project, or local scope/skills menu for better discoverabilitysettings.json environment variables were not applied to WebFetch and other HTTP requests on the Node.js build/resume session picker showing raw XML markup instead of clean titles for sessions started with slash commands.claude/skills/ within additional directories (--add-dir) are now loaded automatically.@ file completion showing incorrect relative paths when running from a subdirectory${index + 1}, which previously interrupted tool execution~/.claude.json was missing default fieldstemperatureOverride being silently ignored in the streaming API path, causing all streaming requests to use the default temperature (1) regardless of the configured overridecat, sed, grep, find), reducing unnecessary bash command usagepages parameter to the Read tool for PDFs, allowing specific page ranges to be read (e.g., pages: "1-5"). Large PDFs (>10 pages) now return a lightweight reference when @ mentioned instead of being inlined into context.--client-id and --client-secret with claude mcp add./debug for Claude to help troubleshoot the current sessiongit log and git show flags in read-only mode (e.g., --topo-order, --cherry-pick, --format, --raw)/login when the conversation contained thinking blocksparentUuid cycles.bashrc file could not run bash commands--resume (68% reduction for users with many sessions) by replacing the session index with lightweight stat-based loading and progressive enrichmentTaskStop tool to display the stopped command/task description in the result line instead of a generic "Task stopped" message/model to execute immediately instead of being queuedsaved_hook_contextCLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1 avoids the error--from-pr flag to resume sessions linked to a specific GitHub PR number or URLgh pr create.bashrc filesCLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1 avoids the errorspinnerVerbs)python and pip commands use the correct interpreter (configurable via claudeCode.usePythonEnvironment setting)CLAUDE.md files from additional directories specified via --add-dir flag (requires setting CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1)TaskUpdate tool/context/sandbox command UI to show dependency status with installation instructions when dependencies are missingToolSearch results to appear as a brief notification instead of inline in the conversation/commit-push-pr skill to automatically post PR URLs to Slack channels when configured via MCP tools/copy command to be available to all usersBash(*) to be accepted and treated as equivalent to BashCLAUDE_CODE_ENABLE_TASKS, set to false to keep the old system temporarily$0, $1, etc. for accessing individual arguments in custom commandsprocess.exit and using SIGKILL as fallback/rename and /tag not updating the correct session when resuming from a different directory (e.g., git worktrees)$ARGUMENTS.0 to $ARGUMENTS[0] (bracket syntax)queued_command attachment messages as SDKUserMessageReplay events when replayUserMessages is enabled/keybindings to get started. Learn more at https://code.claude.com/docs/en/keybindings/compactclaude install or see https://docs.anthropic.com/en/docs/claude-code/getting-started for more options/compact!) - type a partial command and press Tab to complete from your bash command history@ symbol incorrectly triggering file autocomplete suggestions in bash mode@-mention menu folder click behavior to navigate into directories instead of selecting them/feedback command generating invalid GitHub issue URLs when description is very long/context command to show the same token count and percentage as the status line in verbose mode/config, /context, /model, and /todos command overlays could close unexpectedly/context vs /compact)/usage command to display current plan usageSetup hook event that can be triggered via --init, --init-only, or --maintenance CLI flags for repository setup and maintenance operations${index + 1}auto:N syntax for configuring the MCP tool search auto-enable threshold, where N is the context window percentage (0-100)plansDirectory setting to customize where plan files are storedPreToolUse hooks to return additionalContext to the model${CLAUDE_SESSION_ID} string substitution for skills to access the current session IDshowTurnDuration setting to hide turn duration messages (e.g., "Cooked for 1m 6s")/model or /themet or n that were misinterpreted as escape sequencesMCPSearch to disallowedTools in their settings.claudeProcessWrapper setting passing the wrapper path instead of the Claude binary path/config command for quickly filtering settings/doctor showing auto-update channel and available npm versions (stable/latest)/stats command - press r to cycle between Last 7 days, Last 30 days, and All time.claude/skills directories when working with files in subdirectoriescontext_window.used_percentage and context_window.remaining_percentage fields to status line input for easier context window displaymcp list and mcp get commands leaving orphaned MCP server processesdisplay:none/tasks dialog to go directly to task details when there's only one background task running/mcp enable <name> insteadCLAUDE_CODE_TMPDIR environment variable to override the temp directory used for internal temp files, useful for environments with custom temp directory requirementsCLAUDE_CODE_DISABLE_BACKGROUND_TASKS environment variable to disable all background task functionality including auto-backgrounding and the Ctrl+B shortcutstable or latest) toggle to /config/doctor and after saving rules that include the source of each rule and actionable fix guidance/clear commands, now ensuring a fresh plan file is used after clearing a conversationFORCE_AUTOUPDATE_PLUGINS environment variable to allow plugin autoupdate even when the main auto-updater is disabledagent_type to SessionStart hook input, populated if --agent is specified@include directives in CLAUDE.md files/tasks commandscp instead of the unhelpful clipboard shortcut hint/plugins installed tab to unify plugins and MCPs with scope-based groupingC:\ProgramData\ClaudeCode\managed-settings.json - administrators should migrate to C:\Program Files\ClaudeCode\managed-settings.json~/.claude/skills or .claude/skills are now immediately available without restarting the sessioncontext: fork in skill frontmatteragent field in skills to specify agent type for executionlanguage setting to configure Claude's response language (e.g., language: "japanese")respectGitignore support in settings.json for per-project control over @-mention file picker behaviorIS_DEMO environment variable to hide email and organization from the UI, useful for streaming or recording sessions-c or --resumeupdatedInput when returning ask permission decision, enabling hooks to act as middleware while still requesting user consent* at any position in rules (e.g., Bash(npm *), Bash(* install), Bash(git * main))list_changed notifications, allowing MCP servers to dynamically update their available tools, prompts, and resources without requiring reconnection/teleport and /remote-env slash commands for claude.ai subscribers, allowing them to resume and configure remote sessionsTask(AgentName) syntax in settings.json permissions or the --disallowedTools CLI flag; and , to repeat f/F/t/T motions, y operator for yank with yy/Y, p/P for paste, text objects (iw, aw, iW, aW, i", a", i', a', i(, a(, i[, a[, i{, a{), >> and << for indent/dedent, and J to join lines/plan command shortcut to enable plan mode directly from the prompt/ appears anywhere in input, not just at the beginning--tools flag support in interactive mode to restrict which built-in tools Claude can use during interactive sessionsCLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS environment variable to override the default file read token limitonce: true config for hooksallowed-tools field for cleaner skill declarations${CLAUDE_PLUGIN_ROOT} not being substituted in plugin allowed-tools frontmatter, which caused tools to incorrectly require approval$ command substitution failing with parse errorsgit -C /path log now correctly matches Bash(git log:*) rules)claude /context) not being executed properly/context to accurately reflect frontmatter-only loading--model haiku/hooks menu selecting wrong hook type when scrolling to a different optionls and cat) not being counted in collapsed read/search groups, causing groups to incorrectly show "Read 0 files"cat refactor.md | claude/skills/ directories to be visible in the slash command menu by default (opt-out with user-invocable: false in frontmatter)/stats output/terminal-setup support for Kitty, Alacritty, Zed, and Warp terminals/theme to toggle syntax highlighting on/offallowed-tools not being applied to tools invoked by the skill/plugins discover where list selection indicator showed while search box was focused/context command visualization with grouped skills and agents by source, slash commands, and sorted token count[Image #N] links that open attached images in the default viewer--session-id combined with --resume or --continue and --fork-session/theme command to open theme picker directly/context command not respecting custom system prompts in non-interactive mode.ignore or .rgignore files/settings as an alias for the /config command.mcp.json not loading when using --dangerously-skip-permissionsls *.txt, for f in *.png)ANTHROPIC_BEDROCK_BASE_URL is now respected for token counting and inference profile listingmcp__server__* for MCP tool permissions to allow or deny all tools from a servercurrent_usage field to status line input, enabling accurate context window percentage calculations/permissions command with / keyboard shortcut for filtering rules by tool name/doctorclaude update while another instance is already on the latest version.mcp.json being stuck in pending state when running in non-interactive mode (-p flag or piped input)/permissionsclaude install --force not bypassing stale lock filesfileSuggestion setting for custom @ file search commandsCLAUDE_CODE_SHELL environment variable to override automatic shell detection (useful when login shell differs from actual working shell)/rename to name sessions, /resume <name> in REPL or claude --resume <name> from the terminal to resume them--system-prompt being ignored when using --continue or --resume flags/resume screen with grouped forked sessions and keyboard shortcuts for preview (P) and rename (R)aws login AWS Management Console credentialsattribution setting to customize commit and PR bylines (deprecates includeCoAuthoredBy)agent setting to configure main thread with a specific agent's system prompt, tool restrictions, and modelC:\Program Files\ClaudeCode if it exists. Support for C:\ProgramData\ClaudeCode will be removed in a future version.CLAUDE_CODE_PROXY_RESOLVES_HOSTS=true environment variable@ file suggestions with faster, more accurate results/usage command progress bars to fill up as usage increases (instead of showing remaining percentage)$! in bash commands/usage back to "% used"claude --teleport/usagesettings.jsonPermissionRequest hook to automatically approve or deny tool permission requests with custom logic&permissionMode field for custom agentstool_use_id field to PreToolUseHookInput and PostToolUseHookInput typesSubagentStart hook eventCLAUDE.md files not loading when @-mentioning filescell-Nagent_id and agent_transcript_path fields to SubagentStop hooks.model parameter to prompt-based stop hooks, allowing users to specify a custom model for hook evaluation--model haikukeep-coding-instructions option to frontmatterchat.fontSize and chat.fontFamily settings throughout the entire UI, and apply font changes immediately without requiring reloadCLAUDE_CODE_EXIT_AFTER_STOP_DELAY environment variable to automatically exit SDK mode after a specified idle duration, useful for automated workflows and scriptsignorePatterns from project config to deny permissions in the localSettings./hooks menu)claude doctor incorrectly detecting Homebrew vs npm-global installations by properly resolving symlinksclaude mcp serve exposing tools with incompatible outputSchemascompanyAnnouncements setting for displaying announcements on startup/compact to fail with prompt_too_long by making it respect existing compact boundariessecurity unlock-keychain when encountering API key errors on macOS with locked keychainallowUnsandboxedCommands sandbox setting to disable the dangerouslyDisableSandbox escape hatch at policy leveldisallowedTools field to custom agent definitions for explicit tool blocking/output-style and use --system-prompt-file, --system-prompt, --append-system-prompt, CLAUDE.md, or plugins instead/context would sometimes fail with "max_tokens must be greater than thinking.budget_tokens" error message--mcp-config flag to correctly override file-based MCP configurations/terminal-setup from adding backslash to Shift + Enter in VS Codeowner/repo#branch)structuredContent field in tool responsesANTHROPIC_DEFAULT_HAIKU_MODELCLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC now disables release notes fetching-p mode where @-mentioned files needed to be read again before writing/plugin not working on native build/plugin install, /plugin enable/disable, /plugin marketplace commands for plugin managementextraKnownMarketplaces for team collaboration/plugin validate command for validating plugin structure and configuration/doctor command/model selector/help/resume summaries/config now persist across sessionsglobal.anthropic.claude-sonnet-4-5-20250929-v1:0--agents flagCLAUDE_BASH_NO_LOGIN environment variable to 1 or true to to skip login shell for BashToolBash(python:*) matches python script.py > output.txt)spinnerTipsEnabled setting to disable spinner tips--include-partial-messages CLI flagRead(//c/Users/...))exceeds_200k_tokensANTHROPIC_DEFAULT_SONNET_MODEL and ANTHROPIC_DEFAULT_OPUS_MODEL for controlling model aliases opusplan, opus, and sonnet.--replay-user-messages to replay user messages back to stdout/model to run Opus only in plan mode, Sonnet otherwise--mcp-config file1.json file2.json/pr-comments.claude.json - manually merge the history field if desired.disableAllHooks setting<your-custom-agent> to invoke it--settings flag to load settings from a JSON fileCLAUDE_CODE_AUTO_CONNECT_IDE=false for disabling IDE auto-connectionCLAUDE_CODE_SHELL_PREFIX for wrapping Claude and user-provided shell commands run by Claude Code--append-system-prompt can now be used in interactive mode, not just --print/-p.fg. Prompt input undo is now Ctrl+U.~) expansion support to /add-dir commandtool_decision eventNODE_EXTRA_CA_CERTS was setProxy-Authorization header via ANTHROPIC_AUTH_TOKEN or apiKeyHelpertotal_cost to total_cost_usdDISABLE_INTERLEAVED_THINKING to give users the option to opt out of interleaved thinking.ANTHROPIC_MODEL or ANTHROPIC_SMALL_FAST_MODEL should no longer contain an escaped slash (specify / instead of %2F)DEBUG=true in favor of ANTHROPIC_LOG=debug, to log all requestsclaude --mcp-config <path-to-file>claude config add/remove commands now accept multiple values separated by commas or spacesclaude mcp add-from-claude-desktopclaude mcp add-json <n> <json>Understand the agentic loop, built-in tools, and how Claude Code interacts with your project.
Claude Code is an agentic assistant that runs in your terminal. While it excels at coding, it can help with anything you can do from the command line: writing docs, running builds, searching files, researching topics, and more.
This guide covers the core architecture, built-in capabilities, and tips for working effectively. For step-by-step walkthroughs, see Common workflows. For extensibility features like skills, MCP, and hooks, see Extend Claude Code.
When you give Claude a task, it works through three phases: gather context, take action, and verify results. These phases blend together. Claude uses tools throughout, whether searching files to understand your code, editing to make changes, or running tests to check its work.
The loop adapts to what you ask. A question about your codebase might only need context gathering. A bug fix cycles through all three phases repeatedly. A refactor might involve extensive verification. Claude decides what each step requires based on what it learned from the previous step, chaining dozens of actions together and course-correcting along the way.
You're part of this loop too. You can interrupt at any point to steer Claude in a different direction, provide additional context, or ask it to try a different approach. Claude works autonomously but stays responsive to your input.
The agentic loop is powered by two components: models that reason and tools that act. Claude Code serves as the agentic harness around Claude: it provides the tools, context management, and execution environment that turn a language model into a capable coding agent.
Claude Code uses Claude models to understand your code and reason about tasks. Claude can read code in any language, understand how components connect, and figure out what needs to change to accomplish your goal. For complex tasks, it breaks work into steps, executes them, and adjusts based on what it learns.
Multiple models are available with different tradeoffs. Sonnet handles most coding tasks well. Opus provides stronger reasoning for complex architectural decisions. Switch with /model during a session or start with claude --model <name>.
When this guide says "Claude chooses" or "Claude decides," it's the model doing the reasoning.
Tools are what make Claude Code agentic. Without tools, Claude can only respond with text. With tools, Claude can act: read your code, edit files, run commands, search the web, and interact with external services. Each tool use returns information that feeds back into the loop, informing Claude's next decision.
The built-in tools generally fall into five categories, each representing a different kind of agency.
| Category | What Claude can do |
|---|---|
| File operations | Read files, edit code, create new files, rename and reorganize |
| Search | Find files by pattern, search content with regex, explore codebases |
| Execution | Run shell commands, start servers, run tests, use git |
| Web | Search the web, fetch documentation, look up error messages |
| Code intelligence | See type errors and warnings after edits, jump to definitions, find references (requires code intelligence plugins) |
These are the primary capabilities. Claude also has tools for spawning subagents, asking you questions, and other orchestration tasks. See Tools available to Claude for the complete list.
Claude chooses which tools to use based on your prompt and what it learns along the way. When you say "fix the failing tests," Claude might:
Each tool use gives Claude new information that informs the next step. This is the agentic loop in action.
Extending the base capabilities: The built-in tools are the foundation. You can extend what Claude knows with skills, connect to external services with MCP, automate workflows with hooks, and offload tasks to subagents. These extensions form a layer on top of the core agentic loop. See Extend Claude Code for guidance on choosing the right extension for your needs.
This guide focuses on the terminal. Claude Code also runs in VS Code, JetBrains IDEs, and other environments.
When you run claude in a directory, Claude Code gains access to:
Because Claude sees your whole project, it can work across it. When you ask Claude to "fix the authentication bug," it searches for relevant files, reads multiple files to understand context, makes coordinated edits across them, runs tests to verify the fix, and commits the changes if you ask. This is different from inline code assistants that only see the current file.
The agentic loop, tools, and capabilities described above are the same everywhere you use Claude Code. What changes is where the code executes and how you interact with it.
Claude Code runs in three environments, each with different tradeoffs for where your code executes.
| Environment | Where code runs | Use case |
|---|---|---|
| Local | Your machine | Default. Full access to your files, tools, and environment |
| Cloud | Anthropic-managed VMs | Offload tasks, work on repos you don't have locally |
| Remote Control | Your machine, controlled from a browser | Use the web UI while keeping everything local |
You can access Claude Code through the terminal, IDE extensions, claude.ai/code, Remote Control, Slack, and CI/CD pipelines. The interface determines how you see and interact with Claude, but the underlying agentic loop is identical. See Use Claude Code everywhere for the full list.
Claude Code saves your conversation locally as you work. Each message, tool use, and result is written to a plaintext JSONL file under ~/.claude/projects/, which enables rewinding, resuming, and forking sessions. Before Claude makes code changes, it also snapshots the affected files so you can revert if needed. For paths, retention, and how to clear this data, see application data in ~/.claude.
Sessions are independent. Each new session starts with a fresh context window, without the conversation history from previous sessions. Claude can persist learnings across sessions using auto memory, and you can add your own persistent instructions in CLAUDE.md.
Each Claude Code conversation is a session tied to your current directory. When you resume, you only see sessions from that directory.
Claude sees your current branch's files. When you switch branches, Claude sees the new branch's files, but your conversation history stays the same. Claude remembers what you discussed even after switching.
Since sessions are tied to directories, you can run parallel Claude sessions by using git worktrees, which create separate directories for individual branches.
When you resume a session with claude --continue or claude --resume, you pick up where you left off using the same session ID. New messages append to the existing conversation. Your full conversation history is restored, but session-scoped permissions are not. You'll need to re-approve those.
To branch off and try a different approach without affecting the original session, use the --fork-session flag:
claude --continue --fork-session
This creates a new session ID while preserving the conversation history up to that point. The original session remains unchanged. Like resume, forked sessions don't inherit session-scoped permissions.
Same session in multiple terminals: If you resume the same session in multiple terminals, both terminals write to the same session file. Messages from both get interleaved, like two people writing in the same notebook. Nothing corrupts, but the conversation becomes jumbled. Each terminal only sees its own messages during the session, but if you resume that session later, you'll see everything interleaved. For parallel work from the same starting point, use --fork-session to give each terminal its own clean session.
Claude's context window holds your conversation history, file contents, command outputs, CLAUDE.md, auto memory, loaded skills, and system instructions. As you work, context fills up. Claude compacts automatically, but instructions from early in the conversation can get lost. Put persistent rules in CLAUDE.md, and run /context to see what's using space.
For an interactive walkthrough of what loads and when, see Explore the context window.
Claude Code manages context automatically as you approach the limit. It clears older tool outputs first, then summarizes the conversation if needed. Your requests and key code snippets are preserved; detailed instructions from early in the conversation may be lost. Put persistent rules in CLAUDE.md rather than relying on conversation history.
To control what's preserved during compaction, add a "Compact Instructions" section to CLAUDE.md or run /compact with a focus (like /compact focus on the API changes).
If a single file or tool output is so large that context refills immediately after each summary, Claude Code stops auto-compacting after a few attempts and shows an error instead of looping. See Auto-compaction stops with a thrashing error for recovery steps.
Run /context to see what's using space. MCP tool definitions are deferred by default and loaded on demand via tool search, so only tool names consume context until Claude uses a specific tool. Run /mcp to check per-server costs.
Beyond compaction, you can use other features to control what loads into context.
Skills load on demand. Claude sees skill descriptions at session start, but the full content only loads when a skill is used. For skills you invoke manually, set disable-model-invocation: true to keep descriptions out of context until you need them.
Subagents get their own fresh context, completely separate from your main conversation. Their work doesn't bloat your context. When done, they return a summary. This isolation is why subagents help with long sessions.
See context costs for what each feature costs, and reduce token usage for tips on managing context.
Claude has two safety mechanisms: checkpoints let you undo file changes, and permissions control what Claude can do without asking.
Every file edit is reversible. Before Claude edits any file, it snapshots the current contents. If something goes wrong, press Esc twice to rewind to a previous state, or ask Claude to undo.
Checkpoints are local to your session, separate from git. They only cover file changes. Actions that affect remote systems (databases, APIs, deployments) can't be checkpointed, which is why Claude asks before running commands with external side effects.
Press Shift+Tab to cycle through permission modes:
mkdir and mv without asking, still asks for other commandsYou can also allow specific commands in .claude/settings.json so Claude doesn't ask each time. This is useful for trusted commands like npm test or git status. Settings can be scoped from organization-wide policies down to personal preferences. See Permissions for details.
These tips help you get better results from Claude Code.
Claude Code can teach you how to use it. Ask questions like "how do I set up hooks?" or "what's the best way to structure my CLAUDE.md?" and Claude will explain.
Built-in commands also guide you through setup:
/init walks you through creating a CLAUDE.md for your project/agents helps you configure custom subagents/doctor diagnoses common issues with your installationClaude Code is conversational. You don't need perfect prompts. Start with what you want, then refine:
Fix the login bug
[Claude investigates, tries something]
That's not quite right. The issue is in the session handling.
[Claude adjusts approach]
When the first attempt isn't right, you don't start over. You iterate.
You can interrupt Claude at any point. If it's going down the wrong path, just type your correction and press Enter. Claude will stop what it's doing and adjust its approach based on your input. You don't have to wait for it to finish or start over.
The more precise your initial prompt, the fewer corrections you'll need. Reference specific files, mention constraints, and point to example patterns.
The checkout flow is broken for users with expired cards.
Check src/payments/ for the issue, especially token refresh.
Write a failing test first, then fix it.
Vague prompts work, but you'll spend more time steering. Specific prompts like the one above often succeed on the first attempt.
Claude performs better when it can check its own work. Include test cases, paste screenshots of expected UI, or define the output you want.
Implement validateEmail. Test cases: 'user@example.com' → true,
'invalid' → false, 'user@.com' → false. Run the tests after.
For visual work, paste a screenshot of the design and ask Claude to compare its implementation against it.
For complex problems, separate research from coding. Use plan mode (Shift+Tab twice) to analyze the codebase first:
Read src/auth/ and understand how we handle sessions.
Then create a plan for adding OAuth support.
Review the plan, refine it through conversation, then let Claude implement. This two-phase approach produces better results than jumping straight to code.
Think of delegating to a capable colleague. Give context and direction, then trust Claude to figure out the details:
The checkout flow is broken for users with expired cards.
The relevant code is in src/payments/. Can you investigate and fix it?
You don't need to specify which files to read or what commands to run. Claude figures that out.
Understand when to use CLAUDE.md, Skills, subagents, hooks, MCP, and plugins.
Claude Code combines a model that reasons about your code with built-in tools for file operations, search, execution, and web access. The built-in tools cover most coding tasks. This guide covers the extension layer: features you add to customize what Claude knows, connect it to external services, and automate workflows.
Note
For how the core agentic loop works, see How Claude Code works.
New to Claude Code? Start with CLAUDE.md for project conventions, then add other extensions as specific triggers come up.
Extensions plug into different parts of the agentic loop:
Skills are the most flexible extension. A skill is a markdown file containing knowledge, workflows, or instructions. You can invoke skills with a command like /deploy, or Claude can load them automatically when relevant. Skills can run in your current conversation or in an isolated context via subagents.
Features range from always-on context that Claude sees every session, to on-demand capabilities you or Claude can invoke, to background automation that runs on specific events. The table below shows what's available and when each one makes sense.
| Feature | What it does | When to use it | Example |
|---|---|---|---|
| CLAUDE.md | Persistent context loaded every conversation | Project conventions, "always do X" rules | "Use pnpm, not npm. Run tests before committing." |
| Skill | Instructions, knowledge, and workflows Claude can use | Reusable content, reference docs, repeatable tasks | /deploy runs your deployment checklist; API docs skill with endpoint patterns |
| Subagent | Isolated execution context that returns summarized results | Context isolation, parallel tasks, specialized workers | Research task that reads many files but returns only key findings |
| Agent teams | Coordinate multiple independent Claude Code sessions | Parallel research, new feature development, debugging with competing hypotheses | Spawn reviewers to check security, performance, and tests simultaneously |
| MCP | Connect to external services | External data or actions | Query your database, post to Slack, control a browser |
| Hook | Deterministic script that runs on events | Predictable automation, no LLM involved | Run ESLint after every file edit |
Plugins are the packaging layer. A plugin bundles skills, hooks, subagents, and MCP servers into a single installable unit. Plugin skills are namespaced (like /my-plugin:review) so multiple plugins can coexist. Use plugins when you want to reuse the same setup across multiple repositories or distribute to others via a marketplace.
You don't need to configure everything up front. Each feature has a recognizable trigger, and most teams add them in roughly this order:
| Trigger | Add |
|---|---|
| Claude gets a convention or command wrong twice | Add it to CLAUDE.md |
| You keep typing the same prompt to start a task | Save it as a user-invocable skill |
| You paste the same playbook or multi-step procedure into chat for the third time | Capture it as a skill |
| You keep copying data from a browser tab Claude can't see | Connect that system as an MCP server |
| A side task floods your conversation with output you won't reference again | Route it through a subagent |
| You want something to happen every time without asking | Write a hook |
| A second repository needs the same setup | Package it as a plugin |
The same triggers tell you when to update what you already have. A repeated mistake or a recurring review comment is a CLAUDE.md edit, not a one-off correction in chat. A workflow you keep tweaking by hand is a skill that needs another revision.
Some features can seem similar. Here's how to tell them apart.
Skills and subagents solve different problems:
| Aspect | Skill | Subagent |
|---|---|---|
| What it is | Reusable instructions, knowledge, or workflows | Isolated worker with its own context |
| Key benefit | Share content across contexts | Context isolation. Work happens separately, only summary returns |
| Best for | Reference material, invocable workflows | Tasks that read many files, parallel work, specialized workers |
Skills can be reference or action. Reference skills provide knowledge Claude uses throughout your session (like your API style guide). Action skills tell Claude to do something specific (like /deploy that runs your deployment workflow).
Use a subagent when you need context isolation or when your context window is getting full. The subagent might read dozens of files or run extensive searches, but your main conversation only receives a summary. Since subagent work doesn't consume your main context, this is also useful when you don't need the intermediate work to remain visible. Custom subagents can have their own instructions and can preload skills.
They can combine. A subagent can preload specific skills (skills: field). A skill can run in isolated context using context: fork. See Skills for details.
Both store instructions, but they load differently and serve different purposes.
| Aspect | CLAUDE.md | Skill |
|---|---|---|
| Loads | Every session, automatically | On demand |
| Can include files | Yes, with @path imports |
Yes, with @path imports |
| Can trigger workflows | No | Yes, with /<name> |
| Best for | "Always do X" rules | Reference material, invocable workflows |
Put it in CLAUDE.md if Claude should always know it: coding conventions, build commands, project structure, "never do X" rules.
Put it in a skill if it's reference material Claude needs sometimes (API docs, style guides) or a workflow you trigger with /<name> (deploy, review, release).
Rule of thumb: Keep CLAUDE.md under 200 lines. If it's growing, move reference content to skills or split into .claude/rules/ files.
All three store instructions, but they load differently:
| Aspect | CLAUDE.md | .claude/rules/ |
Skill |
|---|---|---|---|
| Loads | Every session | Every session, or when matching files are opened | On demand, when invoked or relevant |
| Scope | Whole project | Can be scoped to file paths | Task-specific |
| Best for | Core conventions and build commands | Language-specific or directory-specific guidelines | Reference material, repeatable workflows |
Use CLAUDE.md for instructions every session needs: build commands, test conventions, project architecture.
Use rules to keep CLAUDE.md focused. Rules with paths frontmatter only load when Claude works with matching files, saving context.
Use skills for content Claude only needs sometimes, like API documentation or a deployment checklist you trigger with /<name>.
Both parallelize work, but they're architecturally different:
| Aspect | Subagent | Agent team |
|---|---|---|
| Context | Own context window; results return to the caller | Own context window; fully independent |
| Communication | Reports results back to the main agent only | Teammates message each other directly |
| Coordination | Main agent manages all work | Shared task list with self-coordination |
| Best for | Focused tasks where only the result matters | Complex work requiring discussion and collaboration |
| Token cost | Lower: results summarized back to main context | Higher: each teammate is a separate Claude instance |
Use a subagent when you need a quick, focused worker: research a question, verify a claim, review a file. The subagent does the work and returns a summary. Your main conversation stays clean.
Use an agent team when teammates need to share findings, challenge each other, and coordinate independently. Agent teams are best for research with competing hypotheses, parallel code review, and new feature development where each teammate owns a separate piece.
Transition point: If you're running parallel subagents but hitting context limits, or if your subagents need to communicate with each other, agent teams are the natural next step.
Note
Agent teams are experimental and disabled by default. See agent teams for setup and current limitations.
MCP connects Claude to external services. Skills extend what Claude knows, including how to use those services effectively.
| Aspect | MCP | Skill |
|---|---|---|
| What it is | Protocol for connecting to external services | Knowledge, workflows, and reference material |
| Provides | Tools and data access | Knowledge, workflows, reference material |
| Examples | Slack integration, database queries, browser control | Code review checklist, deploy workflow, API style guide |
These solve different problems and work well together:
MCP gives Claude the ability to interact with external systems. Without MCP, Claude can't query your database or post to Slack.
Skills give Claude knowledge about how to use those tools effectively, plus workflows you can trigger with /<name>. A skill might include your team's database schema and query patterns, or a /post-to-slack workflow with your team's message formatting rules.
Example: An MCP server connects Claude to your database. A skill teaches Claude your data model, common query patterns, and which tables to use for different tasks.
Features can be defined at multiple levels: user-wide, per-project, via plugins, or through managed policies. You can also nest CLAUDE.md files in subdirectories or place skills in specific packages of a monorepo. When the same feature exists at multiple levels, here's how they layer:
Each extension solves a different problem: CLAUDE.md handles always-on context, skills handle on-demand knowledge and workflows, MCP handles external connections, subagents handle isolation, and hooks handle automation. Real setups combine them based on your workflow.
For example, you might use CLAUDE.md for project conventions, a skill for your deployment workflow, MCP to connect to your database, and a hook to run linting after every edit. Each feature handles what it's best at.
| Pattern | How it works | Example |
|---|---|---|
| Skill + MCP | MCP provides the connection; a skill teaches Claude how to use it well | MCP connects to your database, a skill documents your schema and query patterns |
| Skill + Subagent | A skill spawns subagents for parallel work | /audit skill kicks off security, performance, and style subagents that work in isolated context |
| CLAUDE.md + Skills | CLAUDE.md holds always-on rules; skills hold reference material loaded on demand | CLAUDE.md says "follow our API conventions," a skill contains the full API style guide |
| Hook + MCP | A hook triggers external actions through MCP | Post-edit hook sends a Slack notification when Claude modifies critical files |
Every feature you add consumes some of Claude's context. Too much can fill up your context window, but it can also add noise that makes Claude less effective; skills may not trigger correctly, or Claude may lose track of your conventions. Understanding these trade-offs helps you build an effective setup. For an interactive view of how these features combine in a running session, see Explore the context window.
Each feature has a different loading strategy and context cost:
| Feature | When it loads | What loads | Context cost |
|---|---|---|---|
| CLAUDE.md | Session start | Full content | Every request |
| Skills | Session start + when used | Descriptions at start, full content when used | Low (descriptions every request)* |
| MCP servers | Session start | Tool names; full schemas on demand | Low until a tool is used |
| Subagents | When spawned | Fresh context with specified skills | Isolated from main session |
| Hooks | On trigger | Nothing (runs externally) | Zero, unless hook returns additional context |
*By default, skill descriptions load at session start so Claude can decide when to use them. Set disable-model-invocation: true in a skill's frontmatter to hide it from Claude entirely until you invoke it manually. This reduces context cost to zero for skills you only trigger yourself.
Each feature loads at different points in your session. The tabs below explain when each one loads and what goes into context.
When: Session start
What loads: Full content of all CLAUDE.md files (managed, user, and project levels).
Inheritance: Claude reads CLAUDE.md files from your working directory up to the root, and discovers nested ones in subdirectories as it accesses those files. See How CLAUDE.md files load for details.
Tip
Keep CLAUDE.md under 200 lines. Move reference material to skills, which load on-demand.
Skills are extra capabilities in Claude's toolkit. They can be reference material (like an API style guide) or invocable workflows you trigger with /<name> (like /deploy). Claude Code includes bundled skills like /simplify, /batch, and /debug that work out of the box. You can also create your own. Claude uses skills when appropriate, or you can invoke one directly.
When: Depends on the skill's configuration. By default, descriptions load at session start and full content loads when used. For user-only skills (disable-model-invocation: true), nothing loads until you invoke them.
What loads: For model-invocable skills, Claude sees names and descriptions in every request. When you invoke a skill with /<name> or Claude loads it automatically, the full content loads into your conversation.
How Claude chooses skills: Claude matches your task against skill descriptions to decide which are relevant. If descriptions are vague or overlap, Claude may load the wrong skill or miss one that would help. To tell Claude to use a specific skill, invoke it with /<name>. Skills with disable-model-invocation: true are invisible to Claude until you invoke them.
Context cost: Low until used. User-only skills have zero cost until invoked.
In subagents: Skills work differently in subagents. Instead of on-demand loading, skills passed to a subagent are fully preloaded into its context at launch. Subagents don't inherit skills from the main session; you must specify them explicitly.
Tip
Use disable-model-invocation: true for skills with side effects. This saves context and ensures only you trigger them.
When: Session start.
What loads: Tool names from connected servers. Full JSON schemas stay deferred until Claude needs a specific tool.
Context cost: Tool search is on by default, so idle MCP tools consume minimal context.
Reliability note: MCP connections can fail silently mid-session. If a server disconnects, its tools disappear without warning. Claude may try to use a tool that no longer exists. If you notice Claude failing to use an MCP tool it previously could access, check the connection with /mcp.
Tip
Run /mcp to see token costs per server. Disconnect servers you're not actively using.
When: On demand, when you or Claude spawns one for a task.
What loads: Fresh, isolated context containing:
skills: fieldContext cost: Isolated from main session. Subagents don't inherit your conversation history or invoked skills.
Tip
Use subagents for work that doesn't need your full conversation context. Their isolation prevents bloating your main session.
When: On trigger. Hooks fire at specific lifecycle events like tool execution, session boundaries, prompt submission, permission requests, and compaction. See Hooks for the full list.
What loads: Nothing by default. Hooks run as external scripts.
Context cost: Zero, unless the hook returns output that gets added as messages to your conversation.
Tip
Hooks are ideal for side effects (linting, logging) that don't need to affect Claude's context.
Each feature has its own guide with setup instructions, examples, and configuration options.
Store project context, conventions, and instructions
Give Claude domain expertise and reusable workflows
Offload work to isolated context
Coordinate multiple sessions working in parallel
Connect Claude to external services
Automate workflows with hooks
Bundle and share feature sets
Host and distribute plugin collections
Where Claude Code reads CLAUDE.md, settings.json, hooks, skills, commands, subagents, rules, and auto memory. Explore the .claude directory in your project and ~/.claude in your home directory.
An interactive simulation of how Claude Code's context window fills during a session. See what loads automatically, what each file read costs, and when rules and hooks fire.
Give Claude persistent instructions with CLAUDE.md files, and let Claude accumulate learnings automatically with auto memory.
Each Claude Code session begins with a fresh context window. Two mechanisms carry knowledge across sessions:
This page covers how to:
.claude/rules/Claude Code has two complementary memory systems. Both are loaded at the start of every conversation. Claude treats them as context, not enforced configuration. The more specific and concise your instructions, the more consistently Claude follows them.
| CLAUDE.md files | Auto memory | |
|---|---|---|
| Who writes it | You | Claude |
| What it contains | Instructions and rules | Learnings and patterns |
| Scope | Project, user, or org | Per working tree |
| Loaded into | Every session | Every session (first 200 lines or 25KB) |
| Use for | Coding standards, workflows, project architecture | Build commands, debugging insights, preferences Claude discovers |
Use CLAUDE.md files when you want to guide Claude's behavior. Auto memory lets Claude learn from your corrections without manual effort.
Subagents can also maintain their own auto memory. See subagent configuration for details.
CLAUDE.md files are markdown files that give Claude persistent instructions for a project, your personal workflow, or your entire organization. You write these files in plain text; Claude reads them at the start of every session.
Treat CLAUDE.md as the place you write down what you'd otherwise re-explain. Add to it when:
Keep it to facts Claude should hold in every session: build commands, conventions, project layout, "always do X" rules. If an entry is a multi-step procedure or only matters for one part of the codebase, move it to a skill or a path-scoped rule instead. The extension overview covers when to use each mechanism.
CLAUDE.md files can live in several locations, each with a different scope. More specific locations take precedence over broader ones.
| Scope | Location | Purpose | Use case examples | Shared with |
|---|---|---|---|---|
| Managed policy | • macOS: /Library/Application Support/ClaudeCode/CLAUDE.md• Linux and WSL: /etc/claude-code/CLAUDE.md• Windows: C:\Program Files\ClaudeCode\CLAUDE.md |
Organization-wide instructions managed by IT/DevOps | Company coding standards, security policies, compliance requirements | All users in organization |
| Project instructions | ./CLAUDE.md or ./.claude/CLAUDE.md |
Team-shared instructions for the project | Project architecture, coding standards, common workflows | Team members via source control |
| User instructions | ~/.claude/CLAUDE.md |
Personal preferences for all projects | Code styling preferences, personal tooling shortcuts | Just you (all projects) |
| Local instructions | ./CLAUDE.local.md |
Personal project-specific preferences; add to .gitignore |
Your sandbox URLs, preferred test data | Just you (current project) |
CLAUDE.md and CLAUDE.local.md files in the directory hierarchy above the working directory are loaded in full at launch. Files in subdirectories load on demand when Claude reads files in those directories. See How CLAUDE.md files load for the full resolution order.
For large projects, you can break instructions into topic-specific files using project rules. Rules let you scope instructions to specific file types or subdirectories.
A project CLAUDE.md can be stored in either ./CLAUDE.md or ./.claude/CLAUDE.md. Create this file and add instructions that apply to anyone working on the project: build and test commands, coding standards, architectural decisions, naming conventions, and common workflows. These instructions are shared with your team through version control, so focus on project-level standards rather than personal preferences.
Tip
Run /init to generate a starting CLAUDE.md automatically. Claude analyzes your codebase and creates a file with build commands, test instructions, and project conventions it discovers. If a CLAUDE.md already exists, /init suggests improvements rather than overwriting it. Refine from there with instructions Claude wouldn't discover on its own.
Set CLAUDE_CODE_NEW_INIT=1 to enable an interactive multi-phase flow. /init asks which artifacts to set up: CLAUDE.md files, skills, and hooks. It then explores your codebase with a subagent, fills in gaps via follow-up questions, and presents a reviewable proposal before writing any files.
CLAUDE.md files are loaded into the context window at the start of every session, consuming tokens alongside your conversation. The context window visualization shows where CLAUDE.md loads relative to the rest of the startup context. Because they're context rather than enforced configuration, how you write instructions affects how reliably Claude follows them. Specific, concise, well-structured instructions work best.
Size: target under 200 lines per CLAUDE.md file. Longer files consume more context and reduce adherence. If your instructions are growing large, split them using imports or .claude/rules/ files.
Structure: use markdown headers and bullets to group related instructions. Claude scans structure the same way readers do: organized sections are easier to follow than dense paragraphs.
Specificity: write instructions that are concrete enough to verify. For example:
npm test before committing" instead of "Test your changes"src/api/handlers/" instead of "Keep files organized"Consistency: if two rules contradict each other, Claude may pick one arbitrarily. Review your CLAUDE.md files, nested CLAUDE.md files in subdirectories, and .claude/rules/ periodically to remove outdated or conflicting instructions. In monorepos, use claudeMdExcludes to skip CLAUDE.md files from other teams that aren't relevant to your work.
CLAUDE.md files can import additional files using @path/to/import syntax. Imported files are expanded and loaded into context at launch alongside the CLAUDE.md that references them.
Both relative and absolute paths are allowed. Relative paths resolve relative to the file containing the import, not the working directory. Imported files can recursively import other files, with a maximum depth of five hops.
To pull in a README, package.json, and a workflow guide, reference them with @ syntax anywhere in your CLAUDE.md:
See @README for project overview and @package.json for available npm commands for this project.
# Additional Instructions
- git workflow @docs/git-instructions.md
For private per-project preferences that shouldn't be checked into version control, create a CLAUDE.local.md at the project root. It loads alongside CLAUDE.md and is treated the same way. Add CLAUDE.local.md to your .gitignore so it isn't committed; running /init and choosing the personal option does this for you.
If you work across multiple git worktrees of the same repository, a gitignored CLAUDE.local.md only exists in the worktree where you created it. To share personal instructions across worktrees, import a file from your home directory instead:
# Individual Preferences
- @~/.claude/my-project-instructions.md
Warning
The first time Claude Code encounters external imports in a project, it shows an approval dialog listing the files. If you decline, the imports stay disabled and the dialog does not appear again.
For a more structured approach to organizing instructions, see .claude/rules/.
Claude Code reads CLAUDE.md, not AGENTS.md. If your repository already uses AGENTS.md for other coding agents, create a CLAUDE.md that imports it so both tools read the same instructions without duplicating them. You can also add Claude-specific instructions below the import. Claude loads the imported file at session start, then appends the rest:
@AGENTS.md
## Claude Code
Use plan mode for changes under `src/billing/`.
Claude Code reads CLAUDE.md files by walking up the directory tree from your current working directory, checking each directory along the way for CLAUDE.md and CLAUDE.local.md files. This means if you run Claude Code in foo/bar/, it loads instructions from foo/bar/CLAUDE.md, foo/CLAUDE.md, and any CLAUDE.local.md files alongside them.
All discovered files are concatenated into context rather than overriding each other. Within each directory, CLAUDE.local.md is appended after CLAUDE.md, so when instructions conflict, your personal notes are the last thing Claude reads at that level.
Claude also discovers CLAUDE.md and CLAUDE.local.md files in subdirectories under your current working directory. Instead of loading them at launch, they are included when Claude reads files in those subdirectories.
If you work in a large monorepo where other teams' CLAUDE.md files get picked up, use claudeMdExcludes to skip them.
Block-level HTML comments (<!-- maintainer notes -->) in CLAUDE.md files are stripped before the content is injected into Claude's context. Use them to leave notes for human maintainers without spending context tokens on them. Comments inside code blocks are preserved. When you open a CLAUDE.md file directly with the Read tool, comments remain visible.
The --add-dir flag gives Claude access to additional directories outside your main working directory. By default, CLAUDE.md files from these directories are not loaded.
To also load memory files from additional directories, set the CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD environment variable:
CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude --add-dir ../shared-config
This loads CLAUDE.md, .claude/CLAUDE.md, .claude/rules/*.md, and CLAUDE.local.md from the additional directory. CLAUDE.local.md is skipped if you exclude local from --setting-sources.
.claude/rules/For larger projects, you can organize instructions into multiple files using the .claude/rules/ directory. This keeps instructions modular and easier for teams to maintain. Rules can also be scoped to specific file paths, so they only load into context when Claude works with matching files, reducing noise and saving context space.
Note
Rules load into context every session or when matching files are opened. For task-specific instructions that don't need to be in context all the time, use skills instead, which only load when you invoke them or when Claude determines they're relevant to your prompt.
Place markdown files in your project's .claude/rules/ directory. Each file should cover one topic, with a descriptive filename like testing.md or api-design.md. All .md files are discovered recursively, so you can organize rules into subdirectories like frontend/ or backend/:
your-project/
├── .claude/
│ ├── CLAUDE.md # Main project instructions
│ └── rules/
│ ├── code-style.md # Code style guidelines
│ ├── testing.md # Testing conventions
│ └── security.md # Security requirements
Rules without paths frontmatter are loaded at launch with the same priority as .claude/CLAUDE.md.
Rules can be scoped to specific files using YAML frontmatter with the paths field. These conditional rules only apply when Claude is working with files matching the specified patterns.
---
paths:
- "src/api/**/*.ts"
---
# API Development Rules
- All API endpoints must include input validation
- Use the standard error response format
- Include OpenAPI documentation comments
Rules without a paths field are loaded unconditionally and apply to all files. Path-scoped rules trigger when Claude reads files matching the pattern, not on every tool use.
Use glob patterns in the paths field to match files by extension, directory, or any combination:
| Pattern | Matches |
|---|---|
**/*.ts |
All TypeScript files in any directory |
src/**/* |
All files under src/ directory |
*.md |
Markdown files in the project root |
src/components/*.tsx |
React components in a specific directory |
You can specify multiple patterns and use brace expansion to match multiple extensions in one pattern:
---
paths:
- "src/**/*.{ts,tsx}"
- "lib/**/*.ts"
- "tests/**/*.test.ts"
---
The .claude/rules/ directory supports symlinks, so you can maintain a shared set of rules and link them into multiple projects. Symlinks are resolved and loaded normally, and circular symlinks are detected and handled gracefully.
This example links both a shared directory and an individual file:
ln -s ~/shared-claude-rules .claude/rules/shared
ln -s ~/company-standards/security.md .claude/rules/security.md
Personal rules in ~/.claude/rules/ apply to every project on your machine. Use them for preferences that aren't project-specific:
~/.claude/rules/
├── preferences.md # Your personal coding preferences
└── workflows.md # Your preferred workflows
User-level rules are loaded before project rules, giving project rules higher priority.
For organizations deploying Claude Code across teams, you can centralize instructions and control which CLAUDE.md files are loaded.
Organizations can deploy a centrally managed CLAUDE.md that applies to all users on a machine. This file cannot be excluded by individual settings.
/Library/Application Support/ClaudeCode/CLAUDE.md/etc/claude-code/CLAUDE.mdC:\Program Files\ClaudeCode\CLAUDE.mdUse MDM, Group Policy, Ansible, or similar tools to distribute the file across developer machines. See managed settings for other organization-wide configuration options.
A managed CLAUDE.md and managed settings serve different purposes. Use settings for technical enforcement and CLAUDE.md for behavioral guidance:
| Concern | Configure in |
|---|---|
| Block specific tools, commands, or file paths | Managed settings: permissions.deny |
| Enforce sandbox isolation | Managed settings: sandbox.enabled |
| Environment variables and API provider routing | Managed settings: env |
| Authentication method and organization lock | Managed settings: forceLoginMethod, forceLoginOrgUUID |
| Code style and quality guidelines | Managed CLAUDE.md |
| Data handling and compliance reminders | Managed CLAUDE.md |
| Behavioral instructions for Claude | Managed CLAUDE.md |
Settings rules are enforced by the client regardless of what Claude decides to do. CLAUDE.md instructions shape Claude's behavior but are not a hard enforcement layer.
In large monorepos, ancestor CLAUDE.md files may contain instructions that aren't relevant to your work. The claudeMdExcludes setting lets you skip specific files by path or glob pattern.
This example excludes a top-level CLAUDE.md and a rules directory from a parent folder. Add it to .claude/settings.local.json so the exclusion stays local to your machine:
{
"claudeMdExcludes": [
"**/monorepo/CLAUDE.md",
"/home/user/monorepo/other-team/.claude/rules/**"
]
}
Patterns are matched against absolute file paths using glob syntax. You can configure claudeMdExcludes at any settings layer: user, project, local, or managed policy. Arrays merge across layers.
Managed policy CLAUDE.md files cannot be excluded. This ensures organization-wide instructions always apply regardless of individual settings.
Auto memory lets Claude accumulate knowledge across sessions without you writing anything. Claude saves notes for itself as it works: build commands, debugging insights, architecture notes, code style preferences, and workflow habits. Claude doesn't save something every session. It decides what's worth remembering based on whether the information would be useful in a future conversation.
Note
Auto memory requires Claude Code v2.1.59 or later. Check your version with claude --version.
Auto memory is on by default. To toggle it, open /memory in a session and use the auto memory toggle, or set autoMemoryEnabled in your project settings:
{
"autoMemoryEnabled": false
}
To disable auto memory via environment variable, set CLAUDE_CODE_DISABLE_AUTO_MEMORY=1.
Each project gets its own memory directory at ~/.claude/projects/<project>/memory/. The <project> path is derived from the git repository, so all worktrees and subdirectories within the same repo share one auto memory directory. Outside a git repo, the project root is used instead.
To store auto memory in a different location, set autoMemoryDirectory in your user or local settings:
{
"autoMemoryDirectory": "~/my-custom-memory-dir"
}
This setting is accepted from policy, local, and user settings. It is not accepted from project settings (.claude/settings.json) to prevent a shared project from redirecting auto memory writes to sensitive locations.
The directory contains a MEMORY.md entrypoint and optional topic files:
~/.claude/projects/<project>/memory/
├── MEMORY.md # Concise index, loaded into every session
├── debugging.md # Detailed notes on debugging patterns
├── api-conventions.md # API design decisions
└── ... # Any other topic files Claude creates
MEMORY.md acts as an index of the memory directory. Claude reads and writes files in this directory throughout your session, using MEMORY.md to keep track of what's stored where.
Auto memory is machine-local. All worktrees and subdirectories within the same git repository share one auto memory directory. Files are not shared across machines or cloud environments.
The first 200 lines of MEMORY.md, or the first 25KB, whichever comes first, are loaded at the start of every conversation. Content beyond that threshold is not loaded at session start. Claude keeps MEMORY.md concise by moving detailed notes into separate topic files.
This limit applies only to MEMORY.md. CLAUDE.md files are loaded in full regardless of length, though shorter files produce better adherence.
Topic files like debugging.md or patterns.md are not loaded at startup. Claude reads them on demand using its standard file tools when it needs the information.
Claude reads and writes memory files during your session. When you see "Writing memory" or "Recalled memory" in the Claude Code interface, Claude is actively updating or reading from ~/.claude/projects/<project>/memory/.
Auto memory files are plain markdown you can edit or delete at any time. Run /memory to browse and open memory files from within a session.
/memoryThe /memory command lists all CLAUDE.md, CLAUDE.local.md, and rules files loaded in your current session, lets you toggle auto memory on or off, and provides a link to open the auto memory folder. Select any file to open it in your editor.
When you ask Claude to remember something, like "always use pnpm, not npm" or "remember that the API tests require a local Redis instance," Claude saves it to auto memory. To add instructions to CLAUDE.md instead, ask Claude directly, like "add this to CLAUDE.md," or edit the file yourself via /memory.
These are the most common issues with CLAUDE.md and auto memory, along with steps to debug them.
CLAUDE.md content is delivered as a user message after the system prompt, not as part of the system prompt itself. Claude reads it and tries to follow it, but there's no guarantee of strict compliance, especially for vague or conflicting instructions.
To debug:
/memory to verify your CLAUDE.md and CLAUDE.local.md files are being loaded. If a file isn't listed, Claude can't see it.For instructions you want at the system prompt level, use --append-system-prompt. This must be passed every invocation, so it's better suited to scripts and automation than interactive use.
Tip
Use the InstructionsLoaded hook to log exactly which instruction files are loaded, when they load, and why. This is useful for debugging path-specific rules or lazy-loaded files in subdirectories.
Run /memory and select the auto memory folder to browse what Claude has saved. Everything is plain markdown you can read, edit, or delete.
Files over 200 lines consume more context and may reduce adherence. Move detailed content into separate files referenced with @path imports (see Import additional files), or split your instructions across .claude/rules/ files.
/compactProject-root CLAUDE.md survives compaction: after /compact, Claude re-reads it from disk and re-injects it into the session. Nested CLAUDE.md files in subdirectories are not re-injected automatically; they reload the next time Claude reads a file in that subdirectory.
If an instruction disappeared after compaction, it was either given only in conversation or lives in a nested CLAUDE.md that hasn't reloaded yet. Add conversation-only instructions to CLAUDE.md to make them persist. See What survives compaction for the full breakdown.
See Write effective instructions for guidance on size, structure, and specificity.
Control whether Claude asks before editing files or running commands. Cycle modes with Shift+Tab in the CLI or use the mode selector in VS Code, Desktop, and claude.ai.
When Claude wants to edit a file, run a shell command, or make a network request, it pauses and asks you to approve the action. Permission modes control how often that pause happens. The mode you pick shapes the flow of a session: default mode has you review each action as it comes, while looser modes let Claude work in longer uninterrupted stretches and report back when done. Pick more oversight for sensitive work, or fewer interruptions when you trust the direction.
Each mode makes a different tradeoff between convenience and oversight. The table below shows what Claude can do without a permission prompt in each mode.
| Mode | What runs without asking | Best for |
|---|---|---|
default |
Reads only | Getting started, sensitive work |
acceptEdits |
Reads, file edits, and common filesystem commands (mkdir, touch, mv, cp, etc.) |
Iterating on code you're reviewing |
plan |
Reads only | Exploring a codebase before changing it |
auto |
Everything, with background safety checks | Long tasks, reducing prompt fatigue |
dontAsk |
Only pre-approved tools | Locked-down CI and scripts |
bypassPermissions |
Everything except protected paths | Isolated containers and VMs only |
Regardless of mode, writes to protected paths are never auto-approved, guarding repository state and Claude's own configuration against accidental corruption.
Modes set the baseline. Layer permission rules on top to pre-approve or block specific tools in any mode except bypassPermissions, which skips the permission layer entirely.
You can switch modes mid-session, at startup, or as a persistent default. The mode is set through these controls, not by asking Claude in chat. Select your interface below to see how to change it.
During a session: press Shift+Tab to cycle default → acceptEdits → plan. The current mode appears in the status bar. Not every mode is in the default cycle:
auto: appears after you opt in with --enable-auto-mode or the persisted equivalent in settingsbypassPermissions: appears after you start with --permission-mode bypassPermissions, --dangerously-skip-permissions, or --allow-dangerously-skip-permissions; the --allow- variant adds the mode to the cycle without activating itdontAsk: never appears in the cycle; set it with --permission-mode dontAskEnabled optional modes slot in after plan, with bypassPermissions first and auto last. If you have both enabled, you will cycle through bypassPermissions on the way to auto.
At startup: pass the mode as a flag.
claude --permission-mode plan
As a default: set defaultMode in settings.
{
"permissions": {
"defaultMode": "acceptEdits"
}
}
The same --permission-mode flag works with -p for non-interactive runs.
During a session: click the mode indicator at the bottom of the prompt box.
As a default: set claudeCode.initialPermissionMode in VS Code settings, or use the Claude Code extension settings panel.
The mode indicator shows these labels, mapped to the mode each one applies:
| UI label | Mode |
|---|---|
| Ask before edits | default |
| Edit automatically | acceptEdits |
| Plan mode | plan |
| Auto mode | auto |
| Bypass permissions | bypassPermissions |
Auto mode appears in the mode indicator after you enable Allow dangerously skip permissions in the extension settings, but it stays unavailable until your account meets every requirement listed in the auto mode section. The claudeCode.initialPermissionMode setting does not accept auto; to start in auto mode by default, set defaultMode in your Claude Code settings.json instead.
Bypass permissions also requires the Allow dangerously skip permissions toggle before it appears in the mode indicator.
See the VS Code guide for extension-specific details.
The JetBrains plugin runs Claude Code in the IDE terminal, so switching modes works the same as in the CLI: press Shift+Tab to cycle, or pass --permission-mode when launching.
Use the mode selector next to the send button. Auto and Bypass permissions appear only after you enable them in Desktop settings. See the Desktop guide.
Use the mode dropdown next to the prompt box on claude.ai/code or in the mobile app. Permission prompts appear in claude.ai for approval. Which modes appear depends on where the session runs:
For Remote Control, you can also set the starting mode when launching the host:
claude remote-control --permission-mode acceptEdits
acceptEdits mode lets Claude create and edit files in your working directory without prompting. The status bar shows ⏵⏵ accept edits on while this mode is active.
In addition to file edits, acceptEdits mode auto-approves common filesystem Bash commands: mkdir, touch, rm, rmdir, mv, cp, and sed. These commands are also auto-approved when prefixed with safe environment variables such as LANG=C or NO_COLOR=1, or process wrappers such as timeout, nice, or nohup. Like file edits, auto-approval applies only to paths inside your working directory or additionalDirectories. Paths outside that scope, writes to protected paths, and all other Bash commands still prompt.
Use acceptEdits when you want to review changes in your editor or via git diff after the fact rather than approving each edit inline. Press Shift+Tab once from default mode to enter it, or start with it directly:
claude --permission-mode acceptEdits
Plan mode tells Claude to research and propose changes without making them. Claude reads files, runs shell commands to explore, and writes a plan, but does not edit your source. Permission prompts still apply the same as default mode.
Enter plan mode by pressing Shift+Tab or prefixing a single prompt with /plan. You can also start in plan mode from the CLI:
claude --permission-mode plan
Press Shift+Tab again to leave plan mode without approving a plan.
When the plan is ready, Claude presents it and asks how to proceed. From that prompt you can:
Each approve option also offers to clear the planning context first.
Note
Auto mode requires Claude Code v2.1.83 or later.
Auto mode lets Claude execute without permission prompts. A separate classifier model reviews actions before they run, blocking anything that escalates beyond your request, targets unrecognized infrastructure, or appears driven by hostile content Claude read.
Warning
Auto mode is a research preview. It reduces prompts but does not guarantee safety. Use it for tasks where you trust the general direction, not as a replacement for review on sensitive operations.
Auto mode is available only when your account meets all of these requirements:
permissions.disableAutoMode to "disable" in managed settings.If Claude Code reports auto mode as unavailable, one of these requirements is unmet; this is not a transient outage.
Once enabled, start with the flag and auto joins the Shift+Tab cycle:
claude --enable-auto-mode
The classifier trusts your working directory and your repo's configured remotes. Everything else is treated as external until you configure trusted infrastructure.
Blocked by default:
curl | bashmainAllowed by default:
.env and sending credentials to their matching APIRun claude auto-mode defaults to see the full rule lists. If routine actions get blocked, an administrator can add trusted repos, buckets, and services via the autoMode.environment setting: see Configure the auto mode classifier.
Each denied action shows a notification and appears in /permissions under the Recently denied tab, where you can press r to retry it with a manual approval.
If the classifier blocks an action 3 times in a row or 20 times total, auto mode pauses and Claude Code resumes prompting. Approving the prompted action resumes auto mode. These thresholds are not configurable. Any allowed action resets the consecutive counter, while the total counter persists for the session and resets only when its own limit triggers a fallback.
In non-interactive mode with the -p flag, repeated blocks abort the session since there is no user to prompt.
Repeated blocks usually mean the classifier is missing context about your infrastructure. Use /feedback to report false positives, or have an administrator configure trusted infrastructure.
Each action goes through a fixed decision order. The first matching step wins:
On entering auto mode, broad allow rules that grant arbitrary code execution are dropped:
Bash(*)Bash(python*)Agent allow rulesNarrow rules like Bash(npm test) carry over. Dropped rules are restored when you leave auto mode.
The classifier sees user messages, tool calls, and your CLAUDE.md content. Tool results are stripped, so hostile content in a file or web page cannot manipulate it directly. A separate server-side probe scans incoming tool results and flags suspicious content before Claude reads it. For more on how these layers work together, see the auto mode announcement and the engineering deep dive.
The classifier checks subagent work at three points:
permissionMode in the subagent's frontmatter is ignored.The classifier currently runs on Claude Sonnet 4.6 regardless of your main session model. Classifier calls count toward your token usage. Each check sends a portion of the transcript plus the pending action, adding a round-trip before execution. Reads and working-directory edits outside protected paths skip the classifier, so the overhead comes mainly from shell commands and network operations.
dontAsk mode auto-denies every tool that is not explicitly allowed. Only actions matching your permissions.allow rules can execute; explicit ask rules are also denied rather than prompting. This makes the mode fully non-interactive for CI pipelines or restricted environments where you pre-define exactly what Claude may do.
Set it at startup with the flag:
claude --permission-mode dontAsk
bypassPermissions mode disables permission prompts and safety checks so tool calls execute immediately. Writes to protected paths are the only actions that still prompt. Only use this mode in isolated environments like containers, VMs, or devcontainers without internet access, where Claude Code cannot damage your host system.
You cannot enter bypassPermissions from a session that was started without one of the enabling flags; restart with one to enable it:
claude --permission-mode bypassPermissions
The --dangerously-skip-permissions flag is equivalent.
Warning
bypassPermissions offers no protection against prompt injection or unintended actions. For background safety checks without prompts, use auto mode instead. Administrators can block this mode by setting permissions.disableBypassPermissionsMode to "disable" in managed settings.
Writes to a small set of paths are never auto-approved, in every mode. This prevents accidental corruption of repository state and Claude's own configuration. In default, acceptEdits, plan, and bypassPermissions these writes prompt; in auto they route to the classifier; in dontAsk they are denied.
Protected directories:
.git.vscode.idea.husky.claude, except for .claude/commands, .claude/agents, .claude/skills, and .claude/worktrees where Claude routinely creates contentProtected files:
.gitconfig, .gitmodules.bashrc, .bash_profile, .zshrc, .zprofile, .profile.ripgreprc.mcp.json, .claude.jsonPreToolUse and PermissionRequest hooks-p flagStep-by-step guides for exploring codebases, fixing bugs, refactoring, testing, and other everyday tasks with Claude Code.
This page covers practical workflows for everyday development: exploring unfamiliar code, debugging, refactoring, writing tests, creating PRs, and managing sessions. Each section includes example prompts you can adapt to your own projects. For higher-level patterns and tips, see Best practices.
Suppose you've just joined a new project and need to understand its structure quickly.
cd /path/to/project
claude
give me an overview of this codebase
explain the main architecture patterns used here
what are the key data models?
how is authentication handled?
Tip
Tips:
Suppose you need to locate code related to a specific feature or functionality.
find the files that handle user authentication
how do these authentication files work together?
trace the login process from front-end to database
Tip
Tips:
Suppose you've encountered an error message and need to find and fix its source.
I'm seeing an error when I run npm test
suggest a few ways to fix the @ts-ignore in user.ts
update user.ts to add the null check you suggested
Tip
Tips:
Suppose you need to update old code to use modern patterns and practices.
find deprecated API usage in our codebase
suggest how to refactor utils.js to use modern JavaScript features
refactor utils.js to use ES2024 features while maintaining the same behavior
run tests for the refactored code
Tip
Tips:
Suppose you want to use specialized AI subagents to handle specific tasks more effectively.
/agents
This shows all available subagents and lets you create new ones.
Claude Code automatically delegates appropriate tasks to specialized subagents:
review my recent code changes for security issues
run all tests and fix any failures
use the code-reviewer subagent to check the auth module
have the debugger subagent investigate why users can't log in
/agents
Then select "Create New subagent" and follow the prompts to define:
code-reviewer, api-designer).Tip
Tips:
.claude/agents/ for team sharingdescription fields to enable automatic delegationPlan Mode instructs Claude to create a plan by analyzing the codebase with read-only operations, perfect for exploring codebases, planning complex changes, or reviewing code safely. In Plan Mode, Claude uses AskUserQuestion to gather requirements and clarify your goals before proposing a plan.
Turn on Plan Mode during a session
You can switch into Plan Mode during a session using Shift+Tab to cycle through permission modes.
If you are in Normal Mode, Shift+Tab first switches into Auto-Accept Mode, indicated by ⏵⏵ accept edits on at the bottom of the terminal. A subsequent Shift+Tab will switch into Plan Mode, indicated by ⏸ plan mode on.
Start a new session in Plan Mode
To start a new session in Plan Mode, use the --permission-mode plan flag:
claude --permission-mode plan
Run "headless" queries in Plan Mode
You can also run a query in Plan Mode directly with -p (that is, in "headless mode"):
claude --permission-mode plan -p "Analyze the authentication system and suggest improvements"
claude --permission-mode plan
I need to refactor our authentication system to use OAuth2. Create a detailed migration plan.
Claude analyzes the current implementation and create a comprehensive plan. Refine with follow-ups:
What about backward compatibility?
How should we handle database migration?
Tip
Press Ctrl+G to open the plan in your default text editor, where you can edit it directly before Claude proceeds.
When you accept a plan, Claude automatically names the session from the plan content. The name appears on the prompt bar and in the session picker. If you've already set a name with --name or /rename, accepting a plan won't overwrite it.
// .claude/settings.json
{
"permissions": {
"defaultMode": "plan"
}
}
See settings documentation for more configuration options.
Suppose you need to add tests for uncovered code.
find functions in NotificationsService.swift that are not covered by tests
add tests for the notification service
add test cases for edge conditions in the notification service
run the new tests and fix any failures
Claude can generate tests that follow your project's existing patterns and conventions. When asking for tests, be specific about what behavior you want to verify. Claude examines your existing test files to match the style, frameworks, and assertion patterns already in use.
For comprehensive coverage, ask Claude to identify edge cases you might have missed. Claude can analyze your code paths and suggest tests for error conditions, boundary values, and unexpected inputs that are easy to overlook.
You can create pull requests by asking Claude directly ("create a pr for my changes"), or guide Claude through it step-by-step:
summarize the changes I've made to the authentication module
create a pr
enhance the PR description with more context about the security improvements
When you create a PR using gh pr create, the session is automatically linked to that PR. You can resume it later with claude --from-pr <number>.
Tip
Review Claude's generated PR before submitting and ask Claude to highlight potential risks or considerations.
Suppose you need to add or update documentation for your code.
find functions without proper JSDoc comments in the auth module
add JSDoc comments to the undocumented functions in auth.js
improve the generated documentation with more context and examples
check if the documentation follows our project standards
Tip
Tips:
Suppose you need to work with images in your codebase, and you want Claude's help analyzing image content.
You can use any of these methods:
What does this image show?
Describe the UI elements in this screenshot
Are there any problematic elements in this diagram?
Here's a screenshot of the error. What's causing it?
This is our current database schema. How should we modify it for the new feature?
Generate CSS to match this design mockup
What HTML structure would recreate this component?
Tip
Tips:
[Image #1]), Cmd+Click (Mac) or Ctrl+Click (Windows/Linux) the link to open the image in your default viewerUse @ to quickly include files or directories without waiting for Claude to read them.
Explain the logic in @src/utils/auth.js
This includes the full content of the file in the conversation.
What's the structure of @src/components?
This provides a directory listing with file information.
Show me the data from @github:repos/owner/repo/issues
This fetches data from connected MCP servers using the format @server:resource. See MCP resources for details.
Tip
Tips:
CLAUDE.md in the file's directory and parent directories to contextExtended thinking is enabled by default, giving Claude space to reason through complex problems step-by-step before responding. This reasoning is visible in verbose mode, which you can toggle on with Ctrl+O.
Additionally, Opus 4.6 and Sonnet 4.6 support adaptive reasoning: instead of a fixed thinking token budget, the model dynamically allocates thinking based on your effort level setting. Extended thinking and adaptive reasoning work together to give you control over how deeply Claude reasons before responding.
Extended thinking is particularly valuable for complex architectural decisions, challenging bugs, multi-step implementation planning, and evaluating tradeoffs between different approaches.
Note
Phrases like "think", "think hard", and "think more" are interpreted as regular prompt instructions and don't allocate thinking tokens.
Thinking is enabled by default, but you can adjust or disable it.
| Scope | How to configure | Details |
|---|---|---|
| Effort level | Run /effort, adjust in /model, or set CLAUDE_CODE_EFFORT_LEVEL |
Control thinking depth for Opus 4.6 and Sonnet 4.6. See Adjust effort level |
ultrathink keyword |
Include "ultrathink" anywhere in your prompt | Sets effort to high for that turn on Opus 4.6 and Sonnet 4.6. Useful for one-off tasks requiring deep reasoning without permanently changing your effort setting |
| Toggle shortcut | Press Option+T (macOS) or Alt+T (Windows/Linux) |
Toggle thinking on/off for the current session (all models). May require terminal configuration to enable Option key shortcuts |
| Global default | Use /config to toggle thinking mode |
Sets your default across all projects (all models). Saved as alwaysThinkingEnabled in ~/.claude/settings.json |
| Limit token budget | Set MAX_THINKING_TOKENS environment variable |
Limit the thinking budget to a specific number of tokens. On Opus 4.6 and Sonnet 4.6, only 0 applies unless adaptive reasoning is disabled. Example: export MAX_THINKING_TOKENS=10000 |
To view Claude's thinking process, press Ctrl+O to toggle verbose mode and see the internal reasoning displayed as gray italic text.
Extended thinking controls how much internal reasoning Claude performs before responding. More thinking provides more space to explore solutions, analyze edge cases, and self-correct mistakes.
With Opus 4.6 and Sonnet 4.6, thinking uses adaptive reasoning: the model dynamically allocates thinking tokens based on the effort level you select. This is the recommended way to tune the tradeoff between speed and reasoning depth.
With older models, thinking uses a fixed token budget drawn from your output allocation. The budget varies by model; see MAX_THINKING_TOKENS for per-model ceilings. You can limit the budget with that environment variable, or disable thinking entirely via /config or the Option+T/Alt+T toggle.
On Opus 4.6 and Sonnet 4.6, adaptive reasoning controls thinking depth, so MAX_THINKING_TOKENS only applies when set to 0 to disable thinking, or when CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1 reverts these models to the fixed budget. See environment variables.
Warning
You're charged for all thinking tokens used even when thinking summaries are redacted. In interactive mode, thinking appears as a collapsed stub by default. Set showThinkingSummaries: true in settings.json to show full summaries.
When starting Claude Code, you can resume a previous session:
claude --continue continues the most recent conversation in the current directoryclaude --resume opens a conversation picker or resumes by nameclaude --from-pr 123 resumes sessions linked to a specific pull requestFrom inside an active session, use /resume to switch to a different conversation.
Sessions are stored per project directory. The /resume picker shows interactive sessions from the same git repository, including worktrees. When you select a session from another worktree of the same repository, Claude Code resumes it directly without requiring you to switch directories first. Sessions created by claude -p or SDK invocations do not appear in the picker, but you can still resume one by passing its session ID or custom name to claude --resume <session-id-or-name>. Custom names set with --name or /rename are accepted in addition to session IDs.
Give sessions descriptive names to find them later. This is a best practice when working on multiple tasks or features.
Name a session at startup with -n:
claude -n auth-refactor
Or use /rename during a session, which also shows the name on the prompt bar:
/rename auth-refactor
You can also rename any session from the picker: run /resume, navigate to a session, and press R.
From the command line:
claude --resume auth-refactor
Or from inside an active session:
/resume auth-refactor
The /resume command (or claude --resume without arguments) opens an interactive session picker with these features:
Keyboard shortcuts in the picker:
| Shortcut | Action |
|---|---|
↑ / ↓ |
Navigate between sessions |
→ / ← |
Expand or collapse grouped sessions |
Enter |
Select and resume the highlighted session |
P |
Preview the session content |
R |
Rename the highlighted session |
/ |
Search to filter sessions |
A |
Toggle between current directory and all projects |
B |
Filter to sessions from your current git branch |
Esc |
Exit the picker or search mode |
Session organization:
The picker displays sessions with helpful metadata:
Forked sessions (created with /branch, /rewind, or --fork-session) are grouped together under their root session, making it easier to find related conversations.
Tip
Tips:
/rename when starting work on a distinct task: it's much easier to find "payment-integration" than "explain this function" later--continue for quick access to your most recent conversation in the current directory--resume session-name when you know which session you need--resume (without a name) when you need to browse and selectclaude --continue --print "prompt" to resume in non-interactive modeP in the picker to preview a session before resuming itHow it works:
When working on multiple tasks at once, you need each Claude session to have its own copy of the codebase so changes don't collide. Git worktrees solve this by creating separate working directories that each have their own files and branch, while sharing the same repository history and remote connections. This means you can have Claude working on a feature in one worktree while fixing a bug in another, without either session interfering with the other.
Use the --worktree (-w) flag to create an isolated worktree and start Claude in it. The value you pass becomes the worktree directory name and branch name:
# Start Claude in a worktree named "feature-auth"
# Creates .claude/worktrees/feature-auth/ with a new branch
claude --worktree feature-auth
# Start another session in a separate worktree
claude --worktree bugfix-123
If you omit the name, Claude generates a random one automatically:
# Auto-generates a name like "bright-running-fox"
claude --worktree
Worktrees are created at <repo>/.claude/worktrees/<name> and branch from the default remote branch, which is where origin/HEAD points. The worktree branch is named worktree-<name>.
The base branch is not configurable through a Claude Code flag or setting. origin/HEAD is a reference stored in your local .git directory that Git set once when you cloned. If the repository's default branch later changes on GitHub or GitLab, your local origin/HEAD keeps pointing at the old one, and worktrees will branch from there. To re-sync your local reference with whatever the remote currently considers its default:
git remote set-head origin -a
This is a standard Git command that only updates your local .git directory. Nothing on the remote server changes. If you want worktrees to base off a specific branch rather than the remote's default, set it explicitly with git remote set-head origin your-branch-name.
For full control over how worktrees are created, including choosing a different base per invocation, configure a WorktreeCreate hook. The hook replaces Claude Code's default git worktree logic entirely, so you can fetch and branch from whatever ref you need.
You can also ask Claude to "work in a worktree" or "start a worktree" during a session, and it will create one automatically.
Subagents can also use worktree isolation to work in parallel without conflicts. Ask Claude to "use worktrees for your agents" or configure it in a custom subagent by adding isolation: worktree to the agent's frontmatter. Each subagent gets its own worktree that is automatically cleaned up when the subagent finishes without changes.
When you exit a worktree session, Claude handles cleanup based on whether you made changes:
Subagent worktrees orphaned by a crash or an interrupted parallel run are removed automatically at startup once they are older than your cleanupPeriodDays setting, provided they have no uncommitted changes, no untracked files, and no unpushed commits. Worktrees you create with --worktree are never removed by this sweep.
To clean up worktrees outside of a Claude session, use manual worktree management.
Tip
Add .claude/worktrees/ to your .gitignore to prevent worktree contents from appearing as untracked files in your main repository.
Git worktrees are fresh checkouts, so they don't include untracked files like .env or .env.local from your main repository. To automatically copy these files when Claude creates a worktree, add a .worktreeinclude file to your project root.
The file uses .gitignore syntax to list which files to copy. Only files that match a pattern and are also gitignored get copied, so tracked files are never duplicated.
.env
.env.local
config/secrets.json
This applies to worktrees created with --worktree, subagent worktrees, and parallel sessions in.
For more control over worktree location and branch configuration, create worktrees with Git directly. This is useful when you need to check out a specific existing branch or place the worktree outside the repository.
# Create a worktree with a new branch
git worktree add ../project-feature-a -b feature-a
# Create a worktree with an existing branch
git worktree add ../project-bugfix bugfix-123
# Start Claude in the worktree
cd ../project-feature-a && claude
# Clean up when done
git worktree list
git worktree remove ../project-feature-a
Learn more in the official Git worktree documentation.
Tip
Remember to initialize your development environment in each new worktree according to your project's setup. Depending on your stack, this might include running dependency installation (npm install, yarn), setting up virtual environments, or following your project's standard setup process.
Worktree isolation works with git by default. For other version control systems like SVN, Perforce, or Mercurial, configure WorktreeCreate and WorktreeRemove hooks to provide custom worktree creation and cleanup logic. When configured, these hooks replace the default git behavior when you use --worktree, so .worktreeinclude is not processed. Copy any local configuration files inside your hook script instead.
For automated coordination of parallel sessions with shared tasks and messaging, see agent teams.
When you kick off a long-running task and switch to another window, you can set up desktop notifications so you know when Claude finishes or needs your input. This uses the Notification hook event, which fires whenever Claude is waiting for permission, idle and ready for a new prompt, or completing authentication.
Open ~/.claude/settings.json and add a Notification hook that calls your platform's native notification command:
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
}
]
}
]
}
}
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "notify-send 'Claude Code' 'Claude Code needs your attention'"
}
]
}
]
}
}
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "powershell.exe -Command \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')\""
}
]
}
]
}
}
If your settings file already has a hooks key, merge the Notification entry into it rather than overwriting. You can also ask Claude to write the hook for you by describing what you want in the CLI.
By default the hook fires on all notification types. To fire only for specific events, set the matcher field to one of these values:
| Matcher | Fires when |
|---|---|
permission_prompt |
Claude needs you to approve a tool use |
idle_prompt |
Claude is done and waiting for your next prompt |
auth_success |
Authentication completes |
elicitation_dialog |
Claude is asking you a question |
Type /hooks and select Notification to confirm the hook appears. Selecting it shows the command that will run. To test it end-to-end, ask Claude to run a command that requires permission and switch away from the terminal, or ask Claude to trigger a notification directly.
For the complete event schema and notification types, see the Notification reference.
Suppose you want to use Claude Code as a linter or code reviewer.
Add Claude to your build script:
// package.json
{
...
"scripts": {
...
"lint:claude": "claude -p 'you are a linter. please look at the changes vs. main and report any issues related to typos. report the filename and line number on one line, and a description of the issue on the second line. do not return any other text.'"
}
}
Tip
Tips:
Suppose you want to pipe data into Claude, and get back data in a structured format.
Pipe data through Claude:
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt
Tip
Tips:
--output-format for structured outputSuppose you need Claude's output in a specific format, especially when integrating Claude Code into scripts or other tools.
cat data.txt | claude -p 'summarize this data' --output-format text > summary.txt
This outputs just Claude's plain text response (default behavior).
cat code.py | claude -p 'analyze this code for bugs' --output-format json > analysis.json
This outputs a JSON array of messages with metadata including cost and duration.
cat log.txt | claude -p 'parse this log file for errors' --output-format stream-json
This outputs a series of JSON objects in real-time as Claude processes the request. Each message is a valid JSON object, but the entire output is not valid JSON if concatenated.
Tip
Tips:
--output-format text for simple integrations where you just need Claude's response--output-format json when you need the full conversation log--output-format stream-json for real-time output of each conversation turnSuppose you want Claude to handle a task automatically on a recurring basis, like reviewing open PRs every morning, auditing dependencies weekly, or checking for CI failures overnight.
Pick a scheduling option based on where you want the task to run:
| Option | Where it runs | Best for |
|---|---|---|
| Cloud scheduled tasks | Anthropic-managed infrastructure | Tasks that should run even when your computer is off. Configure at claude.ai/code. |
| Desktop scheduled tasks | Your machine, via the desktop app | Tasks that need direct access to local files, tools, or uncommitted changes. |
| GitHub Actions | Your CI pipeline | Tasks tied to repo events like opened PRs, or cron schedules that should live alongside your workflow config. |
/loop |
The current CLI session | Quick polling while a session is open. Tasks are cancelled when you exit. |
Tip
When writing prompts for scheduled tasks, be explicit about what success looks like and what to do with results. The task runs autonomously, so it can't ask clarifying questions. For example: "Review open PRs labeled needs-review, leave inline comments on any issues, and post a summary in the #eng-reviews Slack channel."
Claude has built-in access to its documentation and can answer questions about its own features and limitations.
can Claude Code create pull requests?
how does Claude Code handle permissions?
what skills are available?
how do I use MCP with Claude Code?
how do I configure Claude Code for Amazon Bedrock?
what are the limitations of Claude Code?
Note
Claude provides documentation-based answers to these questions. For hands-on demonstrations, run /powerup for interactive lessons with animated demos, or refer to the specific workflow sections above.
Tip
Tips:
Tips and patterns for getting the most out of Claude Code, from configuring your environment to scaling across parallel sessions.
Claude Code is an agentic coding environment. Unlike a chatbot that answers questions and waits, Claude Code can read your files, run commands, make changes, and autonomously work through problems while you watch, redirect, or step away entirely.
This changes how you work. Instead of writing code yourself and asking Claude to review it, you describe what you want and Claude figures out how to build it. Claude explores, plans, and implements.
But this autonomy still comes with a learning curve. Claude works within certain constraints you need to understand.
This guide covers patterns that have proven effective across Anthropic's internal teams and for engineers using Claude Code across various codebases, languages, and environments. For how the agentic loop works under the hood, see How Claude Code works.
Most best practices are based on one constraint: Claude's context window fills up fast, and performance degrades as it fills.
Claude's context window holds your entire conversation, including every message, every file Claude reads, and every command output. However, this can fill up fast. A single debugging session or codebase exploration might generate and consume tens of thousands of tokens.
This matters since LLM performance degrades as context fills. When the context window is getting full, Claude may start "forgetting" earlier instructions or making more mistakes. The context window is the most important resource to manage. To see how a session fills up in practice, watch an interactive walkthrough of what loads at startup and what each file read costs. Track context usage continuously with a custom status line, and see Reduce token usage for strategies on reducing token usage.
Tip
Include tests, screenshots, or expected outputs so Claude can check itself. This is the single highest-leverage thing you can do.
Claude performs dramatically better when it can verify its own work, like run tests, compare screenshots, and validate outputs.
Without clear success criteria, it might produce something that looks right but actually doesn't work. You become the only feedback loop, and every mistake requires your attention.
| Strategy | Before | After |
|---|---|---|
| Provide verification criteria | "implement a function that validates email addresses" | "write a validateEmail function. example test cases: user@example.com is true, invalid is false, user@.com is false. run the tests after implementing" |
| Verify UI changes visually | "make the dashboard look better" | "[paste screenshot] implement this design. take a screenshot of the result and compare it to the original. list differences and fix them" |
| Address root causes, not symptoms | "the build is failing" | "the build fails with this error: [paste error]. fix it and verify the build succeeds. address the root cause, don't suppress the error" |
UI changes can be verified using the Claude in Chrome extension. It opens new tabs in your browser, tests the UI, and iterates until the code works.
Your verification can also be a test suite, a linter, or a Bash command that checks output. Invest in making your verification rock-solid.
Tip
Separate research and planning from implementation to avoid solving the wrong problem.
Letting Claude jump straight to coding can produce code that solves the wrong problem. Use Plan Mode to separate exploration from execution.
The recommended workflow has four phases:
Enter Plan Mode. Claude reads files and answers questions without making changes.
read /src/auth and understand how we handle sessions and login.
also look at how we manage environment variables for secrets.
Ask Claude to create a detailed implementation plan.
I want to add Google OAuth. What files need to change?
What's the session flow? Create a plan.
Press Ctrl+G to open the plan in your text editor for direct editing before Claude proceeds.
Switch back to Normal Mode and let Claude code, verifying against its plan.
implement the OAuth flow from your plan. write tests for the
callback handler, run the test suite and fix any failures.
Ask Claude to commit with a descriptive message and create a PR.
commit with a descriptive message and open a PR
Note
Plan Mode is useful, but also adds overhead.
For tasks where the scope is clear and the fix is small (like fixing a typo, adding a log line, or renaming a variable) ask Claude to do it directly.
Planning is most useful when you're uncertain about the approach, when the change modifies multiple files, or when you're unfamiliar with the code being modified. If you could describe the diff in one sentence, skip the plan.
Tip
The more precise your instructions, the fewer corrections you'll need.
Claude can infer intent, but it can't read your mind. Reference specific files, mention constraints, and point to example patterns.
| Strategy | Before | After |
|---|---|---|
| Scope the task. Specify which file, what scenario, and testing preferences. | "add tests for foo.py" | "write a test for foo.py covering the edge case where the user is logged out. avoid mocks." |
| Point to sources. Direct Claude to the source that can answer a question. | "why does ExecutionFactory have such a weird api?" | "look through ExecutionFactory's git history and summarize how its api came to be" |
| Reference existing patterns. Point Claude to patterns in your codebase. | "add a calendar widget" | "look at how existing widgets are implemented on the home page to understand the patterns. HotDogWidget.php is a good example. follow the pattern to implement a new calendar widget that lets the user select a month and paginate forwards/backwards to pick a year. build from scratch without libraries other than the ones already used in the codebase." |
| Describe the symptom. Provide the symptom, the likely location, and what "fixed" looks like. | "fix the login bug" | "users report that login fails after session timeout. check the auth flow in src/auth/, especially token refresh. write a failing test that reproduces the issue, then fix it" |
Vague prompts can be useful when you're exploring and can afford to course-correct. A prompt like "what would you improve in this file?" can surface things you wouldn't have thought to ask about.
Tip
Use @ to reference files, paste screenshots/images, or pipe data directly.
You can provide rich data to Claude in several ways:
@ instead of describing where code lives. Claude reads the file before responding./permissions to allowlist frequently-used domains.cat error.log | claude to send file contents directly.A few setup steps make Claude Code significantly more effective across all your sessions. For a full overview of extension features and when to use each one, see Extend Claude Code.
Tip
Run /init to generate a starter CLAUDE.md file based on your current project structure, then refine over time.
CLAUDE.md is a special file that Claude reads at the start of every conversation. Include Bash commands, code style, and workflow rules. This gives Claude persistent context it can't infer from code alone.
The /init command analyzes your codebase to detect build systems, test frameworks, and code patterns, giving you a solid foundation to refine.
There's no required format for CLAUDE.md files, but keep it short and human-readable. For example:
# Code style
- Use ES modules (import/export) syntax, not CommonJS (require)
- Destructure imports when possible (eg. import { foo } from 'bar')
# Workflow
- Be sure to typecheck when you're done making a series of code changes
- Prefer running single tests, and not the whole test suite, for performance
CLAUDE.md is loaded every session, so only include things that apply broadly. For domain knowledge or workflows that are only relevant sometimes, use skills instead. Claude loads them on demand without bloating every conversation.
Keep it concise. For each line, ask: "Would removing this cause Claude to make mistakes?" If not, cut it. Bloated CLAUDE.md files cause Claude to ignore your actual instructions!
| ✅ Include | ❌ Exclude |
|---|---|
| Bash commands Claude can't guess | Anything Claude can figure out by reading code |
| Code style rules that differ from defaults | Standard language conventions Claude already knows |
| Testing instructions and preferred test runners | Detailed API documentation (link to docs instead) |
| Repository etiquette (branch naming, PR conventions) | Information that changes frequently |
| Architectural decisions specific to your project | Long explanations or tutorials |
| Developer environment quirks (required env vars) | File-by-file descriptions of the codebase |
| Common gotchas or non-obvious behaviors | Self-evident practices like "write clean code" |
If Claude keeps doing something you don't want despite having a rule against it, the file is probably too long and the rule is getting lost. If Claude asks you questions that are answered in CLAUDE.md, the phrasing might be ambiguous. Treat CLAUDE.md like code: review it when things go wrong, prune it regularly, and test changes by observing whether Claude's behavior actually shifts.
You can tune instructions by adding emphasis (e.g., "IMPORTANT" or "YOU MUST") to improve adherence. Check CLAUDE.md into git so your team can contribute. The file compounds in value over time.
CLAUDE.md files can import additional files using @path/to/import syntax:
See @README.md for project overview and @package.json for available npm commands.
# Additional Instructions
- Git workflow: @docs/git-instructions.md
- Personal overrides: @~/.claude/my-project-instructions.md
You can place CLAUDE.md files in several locations:
~/.claude/CLAUDE.md): applies to all Claude sessions./CLAUDE.md): check into git to share with your team./CLAUDE.local.md): personal project-specific notes; add this file to your .gitignore so it isn't shared with your teamroot/CLAUDE.md and root/foo/CLAUDE.md are pulled in automaticallyTip
Use auto mode to let a classifier handle approvals, /permissions to allowlist specific commands, or /sandbox for OS-level isolation. Each reduces interruptions while keeping you in control.
By default, Claude Code requests permission for actions that might modify your system: file writes, Bash commands, MCP tools, etc. This is safe but tedious. After the tenth approval you're not really reviewing anymore, you're just clicking through. There are three ways to reduce these interruptions:
npm run lint or git commitRead more about permission modes, permission rules, and sandboxing.
Tip
Tell Claude Code to use CLI tools like gh, aws, gcloud, and sentry-cli when interacting with external services.
CLI tools are the most context-efficient way to interact with external services. If you use GitHub, install the gh CLI. Claude knows how to use it for creating issues, opening pull requests, and reading comments. Without gh, Claude can still use the GitHub API, but unauthenticated requests often hit rate limits.
Claude is also effective at learning CLI tools it doesn't already know. Try prompts like Use 'foo-cli-tool --help' to learn about foo tool, then use it to solve A, B, C.
Tip
Run claude mcp add to connect external tools like Notion, Figma, or your database.
With MCP servers, you can ask Claude to implement features from issue trackers, query databases, analyze monitoring data, integrate designs from Figma, and automate workflows.
Tip
Use hooks for actions that must happen every time with zero exceptions.
Hooks run scripts automatically at specific points in Claude's workflow. Unlike CLAUDE.md instructions which are advisory, hooks are deterministic and guarantee the action happens.
Claude can write hooks for you. Try prompts like "Write a hook that runs eslint after every file edit" or "Write a hook that blocks writes to the migrations folder." Edit .claude/settings.json directly to configure hooks by hand, and run /hooks to browse what's configured.
Tip
Create SKILL.md files in .claude/skills/ to give Claude domain knowledge and reusable workflows.
Skills extend Claude's knowledge with information specific to your project, team, or domain. Claude applies them automatically when relevant, or you can invoke them directly with /skill-name.
Create a skill by adding a directory with a SKILL.md to .claude/skills/:
---
name: api-conventions
description: REST API design conventions for our services
---
# API Conventions
- Use kebab-case for URL paths
- Use camelCase for JSON properties
- Always include pagination for list endpoints
- Version APIs in the URL path (/v1/, /v2/)
Skills can also define repeatable workflows you invoke directly:
---
name: fix-issue
description: Fix a GitHub issue
disable-model-invocation: true
---
Analyze and fix the GitHub issue: $ARGUMENTS.
1. Use `gh issue view` to get the issue details
2. Understand the problem described in the issue
3. Search the codebase for relevant files
4. Implement the necessary changes to fix the issue
5. Write and run tests to verify the fix
6. Ensure code passes linting and type checking
7. Create a descriptive commit message
8. Push and create a PR
Run /fix-issue 1234 to invoke it. Use disable-model-invocation: true for workflows with side effects that you want to trigger manually.
Tip
Define specialized assistants in .claude/agents/ that Claude can delegate to for isolated tasks.
Subagents run in their own context with their own set of allowed tools. They're useful for tasks that read many files or need specialized focus without cluttering your main conversation.
---
name: security-reviewer
description: Reviews code for security vulnerabilities
tools: Read, Grep, Glob, Bash
model: opus
---
You are a senior security engineer. Review code for:
- Injection vulnerabilities (SQL, XSS, command injection)
- Authentication and authorization flaws
- Secrets or credentials in code
- Insecure data handling
Provide specific line references and suggested fixes.
Tell Claude to use subagents explicitly: "Use a subagent to review this code for security issues."
Tip
Run /plugin to browse the marketplace. Plugins add skills, tools, and integrations without configuration.
Plugins bundle skills, hooks, subagents, and MCP servers into a single installable unit from the community and Anthropic. If you work with a typed language, install a code intelligence plugin to give Claude precise symbol navigation and automatic error detection after edits.
For guidance on choosing between skills, subagents, hooks, and MCP, see Extend Claude Code.
The way you communicate with Claude Code significantly impacts the quality of results.
Tip
Ask Claude questions you'd ask a senior engineer.
When onboarding to a new codebase, use Claude Code for learning and exploration. You can ask Claude the same sorts of questions you would ask another engineer:
async move { ... } do on line 134 of foo.rs?CustomerOnboardingFlowImpl handle?foo instead of bar on line 333?Using Claude Code this way is an effective onboarding workflow, improving ramp-up time and reducing load on other engineers. No special prompting required: ask questions directly.
Tip
For larger features, have Claude interview you first. Start with a minimal prompt and ask Claude to interview you using the AskUserQuestion tool.
Claude asks about things you might not have considered yet, including technical implementation, UI/UX, edge cases, and tradeoffs.
I want to build [brief description]. Interview me in detail using the AskUserQuestion tool.
Ask about technical implementation, UI/UX, edge cases, concerns, and tradeoffs. Don't ask obvious questions, dig into the hard parts I might not have considered.
Keep interviewing until we've covered everything, then write a complete spec to SPEC.md.
Once the spec is complete, start a fresh session to execute it. The new session has clean context focused entirely on implementation, and you have a written spec to reference.
Conversations are persistent and reversible. Use this to your advantage!
Tip
Correct Claude as soon as you notice it going off track.
The best results come from tight feedback loops. Though Claude occasionally solves problems perfectly on the first attempt, correcting it quickly generally produces better solutions faster.
Esc: stop Claude mid-action with the Esc key. Context is preserved, so you can redirect.Esc + Esc or /rewind: press Esc twice or run /rewind to open the rewind menu and restore previous conversation and code state, or summarize from a selected message."Undo that": have Claude revert its changes./clear: reset context between unrelated tasks. Long sessions with irrelevant context can reduce performance.If you've corrected Claude more than twice on the same issue in one session, the context is cluttered with failed approaches. Run /clear and start fresh with a more specific prompt that incorporates what you learned. A clean session with a better prompt almost always outperforms a long session with accumulated corrections.
Tip
Run /clear between unrelated tasks to reset context.
Claude Code automatically compacts conversation history when you approach context limits, which preserves important code and decisions while freeing space.
During long sessions, Claude's context window can fill with irrelevant conversation, file contents, and commands. This can reduce performance and sometimes distract Claude.
/clear frequently between tasks to reset the context window entirely/compact <instructions>, like /compact Focus on the API changesEsc + Esc or /rewind, select a message checkpoint, and choose Summarize from here. This condenses messages from that point forward while keeping earlier context intact."When compacting, always preserve the full list of modified files and any test commands" to ensure critical context survives summarization/btw. The answer appears in a dismissible overlay and never enters conversation history, so you can check a detail without growing context.Tip
Delegate research with "use subagents to investigate X". They explore in a separate context, keeping your main conversation clean for implementation.
Since context is your fundamental constraint, subagents are one of the most powerful tools available. When Claude researches a codebase it reads lots of files, all of which consume your context. Subagents run in separate context windows and report back summaries:
Use subagents to investigate how our authentication system handles token
refresh, and whether we have any existing OAuth utilities I should reuse.
The subagent explores the codebase, reads relevant files, and reports back with findings, all without cluttering your main conversation.
You can also use subagents for verification after Claude implements something:
use a subagent to review this code for edge cases
Tip
Every action Claude makes creates a checkpoint. You can restore conversation, code, or both to any previous checkpoint.
Claude automatically checkpoints before changes. Double-tap Escape or run /rewind to open the rewind menu. You can restore conversation only, restore code only, restore both, or summarize from a selected message. See Checkpointing for details.
Instead of carefully planning every move, you can tell Claude to try something risky. If it doesn't work, rewind and try a different approach. Checkpoints persist across sessions, so you can close your terminal and still rewind later.
Warning
Checkpoints only track changes made by Claude, not external processes. This isn't a replacement for git.
Tip
Run claude --continue to pick up where you left off, or --resume to choose from recent sessions.
Claude Code saves conversations locally. When a task spans multiple sessions, you don't have to re-explain the context:
claude --continue # Resume the most recent conversation
claude --resume # Select from recent conversations
Use /rename to give sessions descriptive names like "oauth-migration" or "debugging-memory-leak" so you can find them later. Treat sessions like branches: different workstreams can have separate, persistent contexts.
Once you're effective with one Claude, multiply your output with parallel sessions, non-interactive mode, and fan-out patterns.
Everything so far assumes one human, one Claude, and one conversation. But Claude Code scales horizontally. The techniques in this section show how you can get more done.
Tip
Use claude -p "prompt" in CI, pre-commit hooks, or scripts. Add --output-format stream-json for streaming JSON output.
With claude -p "your prompt", you can run Claude non-interactively, without a session. Non-interactive mode is how you integrate Claude into CI pipelines, pre-commit hooks, or any automated workflow. The output formats let you parse results programmatically: plain text, JSON, or streaming JSON.
# One-off queries
claude -p "Explain what this project does"
# Structured output for scripts
claude -p "List all API endpoints" --output-format json
# Streaming for real-time processing
claude -p "Analyze this log file" --output-format stream-json
Tip
Run multiple Claude sessions in parallel to speed up development, run isolated experiments, or start complex workflows.
There are three main ways to run parallel sessions:
Beyond parallelizing work, multiple sessions enable quality-focused workflows. A fresh context improves code review since Claude won't be biased toward code it just wrote.
For example, use a Writer/Reviewer pattern:
| Session A (Writer) | Session B (Reviewer) |
|---|---|
Implement a rate limiter for our API endpoints |
|
Review the rate limiter implementation in @src/middleware/rateLimiter.ts. Look for edge cases, race conditions, and consistency with our existing middleware patterns. |
|
Here's the review feedback: [Session B output]. Address these issues. |
You can do something similar with tests: have one Claude write tests, then another write code to pass them.
Tip
Loop through tasks calling claude -p for each. Use --allowedTools to scope permissions for batch operations.
For large migrations or analyses, you can distribute work across many parallel Claude invocations:
Have Claude list all files that need migrating (e.g., list all 2,000 Python files that need migrating)
for file in $(cat files.txt); do
claude -p "Migrate $file from React to Vue. Return OK or FAIL." \
--allowedTools "Edit,Bash(git commit *)"
done
Refine your prompt based on what goes wrong with the first 2-3 files, then run on the full set. The --allowedTools flag restricts what Claude can do, which matters when you're running unattended.
You can also integrate Claude into existing data/processing pipelines:
claude -p "<your prompt>" --output-format json | your_command
Use --verbose for debugging during development, and turn it off in production.
For uninterrupted execution with background safety checks, use auto mode. A classifier model reviews commands before they run, blocking scope escalation, unknown infrastructure, and hostile-content-driven actions while letting routine work proceed without prompts.
claude --permission-mode auto -p "fix all lint errors"
For non-interactive runs with the -p flag, auto mode aborts if the classifier repeatedly blocks actions, since there is no user to fall back to. See when auto mode falls back for thresholds.
These are common mistakes. Recognizing them early saves time:
Fix:
/clearbetween unrelated tasks.
Fix: After two failed corrections,
/clearand write a better initial prompt incorporating what you learned.
Fix: Ruthlessly prune. If Claude already does something correctly without the instruction, delete it or convert it to a hook.
Fix: Always provide verification (tests, scripts, screenshots). If you can't verify it, don't ship it.
Fix: Scope investigations narrowly or use subagents so the exploration doesn't consume your main context.
The patterns in this guide aren't set in stone. They're starting points that work well in general, but might not be optimal for every situation.
Sometimes you should let context accumulate because you're deep in one complex problem and the history is valuable. Sometimes you should skip planning and let Claude figure it out because the task is exploratory. Sometimes a vague prompt is exactly right because you want to see how Claude interprets the problem before constraining it.
Pay attention to what works. When Claude produces great output, notice what you did: the prompt structure, the context you provided, the mode you were in. When Claude struggles, ask why. Was the context too noisy? The prompt too vague? The task too big for one pass?
Over time, you'll develop intuition that no guide can capture. You'll know when to be specific and when to be open-ended, when to plan and when to explore, when to clear context and when to let it accumulate.
Choose where to run Claude Code and what to connect it to. Compare the CLI, Desktop, VS Code, JetBrains, web, mobile, and integrations like Chrome, Slack, and CI/CD.
Claude Code runs the same underlying engine everywhere, but each surface is tuned for a different way of working. This page helps you pick the right platform for your workflow and connect the tools you already use.
Choose a platform based on how you like to work and where your project lives.
| Platform | Best for | What you get |
|---|---|---|
| CLI | Terminal workflows, scripting, remote servers | Full feature set, Agent SDK, computer use on macOS (Pro and Max), third-party providers |
| VS Code | Working inside VS Code without switching to a terminal | Inline diffs, integrated terminal, file context |
| JetBrains | Working inside IntelliJ, PyCharm, WebStorm, or other JetBrains IDEs | Diff viewer, selection sharing, terminal session |
| Web | Long-running tasks that don't need much steering, or work that should continue when you're offline | Anthropic-managed cloud, continues after you disconnect |
| Mobile | Starting and monitoring tasks while away from your computer | Cloud sessions from the Claude app for iOS and Android, Remote Control for local sessions, Dispatch to Desktop on Pro and Max |
The CLI is the most complete surface for terminal-native work: scripting, third-party providers, and the Agent SDK are CLI-only. Desktop and the IDE extensions trade some CLI-only features for visual review and tighter editor integration. The web runs in Anthropic's cloud, so tasks keep going after you disconnect. Mobile is a thin client into those same cloud sessions or into a local session via Remote Control, and can send tasks to Desktop with Dispatch.
You can mix surfaces on the same project. Configuration, project memory, and MCP servers are shared across the local surfaces.
Integrations let Claude work with services outside your codebase.
| Integration | What it does | Use it for |
|---|---|---|
| Chrome | Controls your browser with your logged-in sessions | Testing web apps, filling forms, automating sites without an API |
| GitHub Actions | Runs Claude in your CI pipeline | Automated PR reviews, issue triage, scheduled maintenance |
| GitLab CI/CD | Same as GitHub Actions for GitLab | CI-driven automation on GitLab |
| Code Review | Reviews every PR automatically | Catching bugs before human review |
| Slack | Responds to @Claude mentions in your channels |
Turning bug reports into pull requests from team chat |
For integrations not listed here, MCP servers and connectors let you connect almost anything: Linear, Notion, Google Drive, or your own internal APIs.
Claude Code offers several ways to work when you're not at your terminal. They differ in what triggers the work, where Claude runs, and how much you need to set up.
| Trigger | Claude runs on | Setup | Best for | |
|---|---|---|---|---|
| Dispatch | Message a task from the Claude mobile app | Your machine (Desktop) | Pair the mobile app with Desktop | Delegating work while you're away, minimal setup |
| Remote Control | Drive a running session from claude.ai/code or the Claude mobile app | Your machine (CLI or VS Code) | Run claude remote-control |
Steering in-progress work from another device |
| Channels | Push events from a chat app like Telegram or Discord, or your own server | Your machine (CLI) | Install a channel plugin or build your own | Reacting to external events like CI failures or chat messages |
| Slack | Mention @Claude in a team channel |
Anthropic cloud | Install the Slack app with Claude Code on the web enabled | PRs and reviews from team chat |
| Scheduled tasks | Set a schedule | CLI, Desktop, or cloud | Pick a frequency | Recurring automation like daily reviews |
If you're not sure where to start, install the CLI and run it in a project directory. If you'd rather not use a terminal, Desktop gives you the same engine with a graphical interface.
Continue a local Claude Code session from your phone, tablet, or any browser using Remote Control. Works with claude.ai/code and the Claude mobile app.
Note
Remote Control is available on all plans. On Team and Enterprise, it is off by default until an admin enables the Remote Control toggle in Claude Code admin settings.
Remote Control connects claude.ai/code or the Claude app for iOS and Android to a Claude Code session running on your machine. Start a task at your desk, then pick it up from your phone on the couch or a browser on another computer.
When you start a Remote Control session on your machine, Claude keeps running locally the entire time, so nothing moves to the cloud. With Remote Control you can:
Unlike Claude Code on the web, which runs on cloud infrastructure, Remote Control sessions run directly on your machine and interact with your local filesystem. The web and mobile interfaces are just a window into that local session.
Note
Remote Control requires Claude Code v2.1.51 or later. Check your version with claude --version.
This page covers setup, how to start and connect to sessions, and how Remote Control compares to Claude Code on the web.
Before using Remote Control, confirm that your environment meets these conditions:
claude and use /login to sign in through claude.ai if you haven't already.claude in your project directory at least once to accept the workspace trust dialog.You can start a Remote Control session from the CLI or the VS Code extension. The CLI offers three invocation modes; VS Code uses the /remote-control command.
Navigate to your project directory and run:
claude remote-control
The process stays running in your terminal in server mode, waiting for remote connections. It displays a session URL you can use to connect from another device, and you can press spacebar to show a QR code for quick access from your phone. While a remote session is active, the terminal shows connection status and tool activity.
Available flags:
| Flag | Description |
|---|---|
--name "My Project" |
Set a custom session title visible in the session list at claude.ai/code. |
--remote-control-session-name-prefix <prefix> |
Prefix for auto-generated session names when no explicit name is set. Defaults to your machine's hostname, producing names like myhost-graceful-unicorn. Set CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX for the same effect. |
--spawn <mode> |
How the server creates sessions. • same-dir (default): all sessions share the current working directory, so they can conflict if editing the same files.• worktree: each on-demand session gets its own git worktree. Requires a git repository.• session: single-session mode. Serves exactly one session and rejects additional connections. Set at startup only.Press w at runtime to toggle between same-dir and worktree. |
--capacity <N> |
Maximum number of concurrent sessions. Default is 32. Cannot be used with --spawn=session. |
--verbose |
Show detailed connection and session logs. |
--sandbox / --no-sandbox |
Enable or disable sandboxing for filesystem and network isolation. Off by default. |
To start a normal interactive Claude Code session with Remote Control enabled, use the --remote-control flag (or --rc):
claude --remote-control
Optionally pass a name for the session:
claude --remote-control "My Project"
This gives you a full interactive session in your terminal that you can also control from claude.ai or the Claude app. Unlike claude remote-control (server mode), you can type messages locally while the session is also available remotely.
If you're already in a Claude Code session and want to continue it remotely, use the /remote-control (or /rc) command:
/remote-control
Pass a name as an argument to set a custom session title:
/remote-control My Project
This starts a Remote Control session that carries over your current conversation history and displays a session URL and QR code you can use to connect from another device. The --verbose, --sandbox, and --no-sandbox flags are not available with this command.
In the Claude Code VS Code extension, type /remote-control or /rc in the prompt box, or open the command menu with / and select it. Requires Claude Code v2.1.79 or later.
/remote-control
A banner appears above the prompt box showing connection status. Once connected, click Open in browser in the banner to go directly to the session, or find it in the session list at claude.ai/code. The session URL is also posted in the conversation.
To disconnect, click the close icon on the banner or run /remote-control again.
Unlike the CLI, the VS Code command does not accept a name argument or display a QR code. The session title is derived from your conversation history or first prompt.
Once a Remote Control session is active, you have a few ways to connect from another device:
claude remote-control, press spacebar to toggle the QR code display.The remote session title is chosen in this order:
--name, --remote-control, or /remote-control/renamemyhost-graceful-unicorn, where myhost is your machine's hostname or the prefix you set with --remote-control-session-name-prefixIf you didn't set an explicit name, the title updates to reflect your prompt once you send one.
If the environment already has an active session, you'll be asked whether to continue it or start a new one.
If you don't have the Claude app yet, use the /mobile command inside Claude Code to display a download QR code for iOS or Android.
By default, Remote Control only activates when you explicitly run claude remote-control, claude --remote-control, or /remote-control. To enable it automatically for every interactive session, run /config inside Claude Code and set Enable Remote Control for all sessions to true. Set it back to false to disable.
With this setting on, each interactive Claude Code process registers one remote session. If you run multiple instances, each one gets its own environment and session. To run multiple concurrent sessions from a single process, use server mode instead.
Your local Claude Code session makes outbound HTTPS requests only and never opens inbound ports on your machine. When you start Remote Control, it registers with the Anthropic API and polls for work. When you connect from another device, the server routes messages between the web or mobile client and your local session over a streaming connection.
All traffic travels through the Anthropic API over TLS, the same transport security as any Claude Code session. The connection uses multiple short-lived credentials, each scoped to a single purpose and expiring independently.
Remote Control and Claude Code on the web both use the claude.ai/code interface. The key difference is where the session runs: Remote Control executes on your machine, so your local MCP servers, tools, and project configuration stay available. Claude Code on the web executes in Anthropic-managed cloud infrastructure.
Use Remote Control when you're in the middle of local work and want to keep going from another device. Use Claude Code on the web when you want to kick off a task without any local setup, work on a repo you don't have cloned, or run multiple tasks in parallel.
claude process, the session ends.claude remote-control again to start a new session.You're not authenticated with a claude.ai account. Run claude auth login and choose the claude.ai option. If ANTHROPIC_API_KEY is set in your environment, unset it first.
You're authenticated with a long-lived token from claude setup-token or the CLAUDE_CODE_OAUTH_TOKEN environment variable. These tokens are limited to inference-only and cannot establish Remote Control sessions. Run claude auth login to authenticate with a full-scope session token instead.
Your cached account information is stale or incomplete. Run claude auth login to refresh it.
The eligibility check can fail with certain environment variables present:
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC or DISABLE_TELEMETRY: unset them and try again.CLAUDE_CODE_USE_BEDROCK, CLAUDE_CODE_USE_VERTEX, or CLAUDE_CODE_USE_FOUNDRY: Remote Control requires claude.ai authentication and does not work with third-party providers.If none of these are set, run /logout then /login to refresh.
This error has three distinct causes. Run /status first to see which login method and subscription you're using.
/login and choose the claude.ai option. If ANTHROPIC_API_KEY is set in your environment, unset it.Claude Code could not obtain a short-lived credential from the Anthropic API to establish the connection. Re-run with --verbose to see the full error:
claude remote-control --verbose
Common causes:
claude and use /login to authenticate with your claude.ai account. API key authentication is not supported for Remote Control.Session creation failed — see debug log, the failure happened earlier in setup. Check that your subscription is active.Claude Code offers several ways to work when you're not at your terminal. They differ in what triggers the work, where Claude runs, and how much you need to set up.
| Trigger | Claude runs on | Setup | Best for | |
|---|---|---|---|---|
| Dispatch | Message a task from the Claude mobile app | Your machine (Desktop) | Pair the mobile app with Desktop | Delegating work while you're away, minimal setup |
| Remote Control | Drive a running session from claude.ai/code or the Claude mobile app | Your machine (CLI or VS Code) | Run claude remote-control |
Steering in-progress work from another device |
| Channels | Push events from a chat app like Telegram or Discord, or your own server | Your machine (CLI) | Install a channel plugin or build your own | Reacting to external events like CI failures or chat messages |
| Slack | Mention @Claude in a team channel |
Anthropic cloud | Install the Slack app with Claude Code on the web enabled | PRs and reviews from team chat |
| Scheduled tasks | Set a schedule | CLI, Desktop, or cloud | Pick a frequency | Recurring automation like daily reviews |
/login and manage credentials for claude.aiclaude remote-controlConnect Claude Code to your Chrome browser to test web apps, debug with console logs, automate form filling, and extract data from web pages.
Claude Code integrates with the Claude in Chrome browser extension to give you browser automation capabilities from the CLI or the VS Code extension. Build your code, then test and debug in the browser without switching contexts.
Claude opens new tabs for browser tasks and shares your browser's login state, so it can access any site you're already signed into. Browser actions run in a visible Chrome window in real time. When Claude encounters a login page or CAPTCHA, it pauses and asks you to handle it manually.
Note
Chrome integration is in beta and currently works with Google Chrome and Microsoft Edge. It is not yet supported on Brave, Arc, or other Chromium-based browsers. WSL (Windows Subsystem for Linux) is also not supported.
With Chrome connected, you can chain browser actions with coding tasks in a single workflow:
Before using Claude Code with Chrome, you need:
Note
Chrome integration is not available through third-party providers like Amazon Bedrock, Google Cloud Vertex AI, or Microsoft Foundry. If you access Claude exclusively through a third-party provider, you need a separate claude.ai account to use this feature.
Start Claude Code with the --chrome flag:
claude --chrome
You can also enable Chrome from within an existing session by running /chrome.
This example navigates to a page, interacts with it, and reports what it finds, all from your terminal or editor:
Go to code.claude.com/docs, click on the search box,
type "hooks", and tell me what results appear
Run /chrome at any time to check the connection status, manage permissions, or reconnect the extension.
For VS Code, see browser automation in VS Code.
To avoid passing --chrome each session, run /chrome and select "Enabled by default".
In the VS Code extension, Chrome is available whenever the Chrome extension is installed. No additional flag is needed.
Note
Enabling Chrome by default in the CLI increases context usage since browser tools are always loaded. If you notice increased context consumption, disable this setting and use --chrome only when needed.
Site-level permissions are inherited from the Chrome extension. Manage permissions in the Chrome extension settings to control which sites Claude can browse, click, and type on.
These examples show common ways to combine browser actions with coding tasks. Run /mcp and select claude-in-chrome to see the full list of available browser tools.
When developing a web app, ask Claude to verify your changes work correctly:
I just updated the login form validation. Can you open localhost:3000,
try submitting the form with invalid data, and check if the error
messages appear correctly?
Claude navigates to your local server, interacts with the form, and reports what it observes.
Claude can read console output to help diagnose problems. Tell Claude what patterns to look for rather than asking for all console output, since logs can be verbose:
Open the dashboard page and check the console for any errors when
the page loads.
Claude reads the console messages and can filter for specific patterns or error types.
Speed up repetitive data entry tasks:
I have a spreadsheet of customer contacts in contacts.csv. For each row,
go to the CRM at crm.example.com, click "Add Contact", and fill in the
name, email, and phone fields.
Claude reads your local file, navigates the web interface, and enters the data for each record.
Use Claude to write directly in your documents without API setup:
Draft a project update based on the recent commits and add it to my
Google Doc at docs.google.com/document/d/abc123
Claude opens the document, clicks into the editor, and types the content. This works with any web app you're logged into: Gmail, Notion, Sheets, and more.
Pull structured information from websites:
Go to the product listings page and extract the name, price, and
availability for each item. Save the results as a CSV file.
Claude navigates to the page, reads the content, and compiles the data into a structured format.
Coordinate tasks across multiple websites:
Check my calendar for meetings tomorrow, then for each meeting with
an external attendee, look up their company website and add a note
about what they do.
Claude works across tabs to gather information and complete the workflow.
Create shareable recordings of browser interactions:
Record a GIF showing how to complete the checkout flow, from adding
an item to the cart through to the confirmation page.
Claude records the interaction sequence and saves it as a GIF file.
If Claude Code shows "Chrome extension not detected":
chrome://extensionsclaude --version/chrome and select "Reconnect extension" to re-establish the connectionThe first time you enable Chrome integration, Claude Code installs a native messaging host configuration file. Chrome reads this file on startup, so if the extension isn't detected on your first attempt, restart Chrome to pick up the new configuration.
If the connection still fails, verify the host configuration file exists at:
For Chrome:
~/Library/Application Support/Google/Chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json~/.config/google-chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.jsonHKCU\Software\Google\Chrome\NativeMessagingHosts\ in the Windows RegistryFor Edge:
~/Library/Application Support/Microsoft Edge/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json~/.config/microsoft-edge/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.jsonHKCU\Software\Microsoft\Edge\NativeMessagingHosts\ in the Windows RegistryIf Claude's browser commands stop working:
chrome://extensionsThe Chrome extension's service worker can go idle during extended sessions, which breaks the connection. If browser tools stop working after a period of inactivity, run /chrome and select "Reconnect extension".
On Windows, you may encounter:
These are the most frequently encountered errors and how to resolve them:
| Error | Cause | Fix |
|---|---|---|
| "Browser extension is not connected" | Native messaging host cannot reach the extension | Restart Chrome and Claude Code, then run /chrome to reconnect |
| "Extension not detected" | Chrome extension is not installed or is disabled | Install or enable the extension in chrome://extensions |
| "No tab available" | Claude tried to act before a tab was ready | Ask Claude to create a new tab and retry |
| "Receiving end does not exist" | Extension service worker went idle | Run /chrome and select "Reconnect extension" |
--chromeEnable computer use in the Claude Code CLI so Claude can open apps, click, type, and see your screen on macOS. Test native apps, debug visual issues, and automate GUI-only tools without leaving your terminal.
Note
{/* plan-availability: feature=computer-use plans=pro,max */}
Computer use is a research preview on macOS that requires a Pro or Max plan. It is not available on Team or Enterprise plans. It requires Claude Code v2.1.85 or later and an interactive session, so it is not available in non-interactive mode with the -p flag.
Computer use lets Claude open apps, control your screen, and work on your machine the way you would. From the CLI, Claude can compile a Swift app, launch it, click through every button, and screenshot the result, all in the same conversation where it wrote the code.
This page covers how computer use works in the CLI.
Computer use handles tasks that require a GUI: anything you'd normally have to leave the terminal and do by hand.
Claude has several ways to interact with an app or service. Computer use is the broadest and slowest, so Claude tries the most precise tool first:
Screen control is reserved for things nothing else can reach: native apps, simulators, and tools without an API.
Computer use is available as a built-in MCP server called computer-use. It's off by default until you enable it.
In an interactive Claude Code session, run:
/mcp
Find computer-use in the server list. It shows as disabled.
Select computer-use and choose Enable. The setting persists per project, so you only do this once for each project where you want computer use.
The first time Claude tries to use your computer, you'll see a prompt to grant two macOS permissions:
The prompt includes links to open the relevant System Settings pane. Grant both, then select Try again in the prompt. macOS may require you to restart Claude Code after granting Screen Recording.
After setup, ask Claude to do something that needs the GUI:
Build the app target, launch it, and click through each tab to make
sure nothing crashes. Screenshot any error states you find.
Enabling the computer-use server doesn't grant Claude access to every app on your machine. The first time Claude needs a specific app in a session, a prompt appears in your terminal showing:
Choose Allow for this session or Deny. Approvals last for the current session. You can approve multiple apps at once when Claude requests them together.
Apps with broad reach show an extra warning in the prompt so you know what approving them grants:
| Warning | Applies to |
|---|---|
| Equivalent to shell access | Terminal, iTerm, VS Code, Warp, and other terminals and IDEs |
| Can read or write any file | Finder |
| Can change system settings | System Settings |
These apps aren't blocked. The warning lets you decide whether the task warrants that level of access.
Claude's level of control also varies by app category: browsers and trading platforms are view-only, terminals and IDEs are click-only, and everything else gets full control. See app permissions in Desktop for the complete tier breakdown.
Understanding the flow helps you anticipate what Claude will do and how to intervene.
Computer use holds a machine-wide lock while active. If another Claude Code session is already using your computer, new attempts fail with a message telling you which session holds the lock. Finish or exit that session first.
When Claude starts controlling your screen, other visible apps are hidden so Claude interacts with only the approved apps. Your terminal window stays visible and is excluded from screenshots, so you can watch the session and Claude never sees its own output.
When Claude finishes the turn, hidden apps are restored automatically.
Claude Code downscales every screenshot before sending it to the model. You don't need to lower your display resolution or resize windows on Retina or other high-resolution displays. A 16-inch MacBook Pro at native Retina resolution captures at 3456×2234 and downscales to roughly 1372×887, preserving aspect ratio.
There is no setting to change the target size. If on-screen text or controls are too small for Claude to read after downscaling, increase their size in the app rather than changing your display resolution.
When Claude acquires the lock, a macOS notification appears: "Claude is using your computer · press Esc to stop." Press Esc anywhere to abort the current action immediately, or press Ctrl+C in the terminal. Either way, Claude releases the lock, unhides your apps, and returns control to you.
A second notification appears when Claude is done.
Warning
Unlike the sandboxed Bash tool, computer use runs on your actual desktop with access to the apps you approve. Claude checks each action and flags potential prompt injection from on-screen content, but the trust boundary is different. See the computer use safety guide for best practices.
The built-in guardrails reduce risk without requiring configuration:
Esc key aborts computer use from anywhere, and the key press is consumed so prompt injection can't use it to dismiss dialogs.These examples show common ways to combine computer use with coding tasks.
After making changes to a macOS or iOS app, have Claude compile and verify in one pass:
Build the MenuBarStats target, launch it, open the preferences window,
and verify the interval slider updates the label. Screenshot the
preferences window when you're done.
Claude runs xcodebuild, launches the app, interacts with the UI, and reports what it finds.
When a visual bug only appears at certain window sizes, let Claude find it:
The settings modal clips its footer on narrow windows. Resize the app
window down until you can reproduce it, screenshot the clipped state,
then check the CSS for the modal container.
Claude resizes the window, captures the broken state, and reads the relevant stylesheets.
Drive the iOS Simulator without writing XCTest:
Open the iOS Simulator, launch the app, tap through the onboarding
screens, and tell me if any screen takes more than a second to load.
Claude controls the simulator the same way you would with a mouse.
Another Claude Code session holds the lock. Finish the task in that session or exit it. If the other session crashed, the lock is released automatically when Claude detects the process is no longer running.
macOS sometimes requires a restart of the requesting process after you grant Screen Recording. Quit Claude Code completely and start a new session. If the prompt persists, open System Settings > Privacy & Security > Screen Recording and confirm your terminal app is listed and enabled.
computer-use doesn't appear in /mcpThe server only appears on eligible setups. Check that:
claude --version to check./status to confirm your subscription.-p flag.Install and configure the Claude Code extension for VS Code. Get AI coding assistance with inline diffs, @-mentions, plan review, and keyboard shortcuts.

The VS Code extension provides a native graphical interface for Claude Code, integrated directly into your IDE. This is the recommended way to use Claude Code in VS Code.
With the extension, you can review and edit Claude's plans before accepting them, auto-accept edits as they're made, @-mention files with specific line ranges from your selection, access conversation history, and open multiple conversations in separate tabs or windows.
Before installing, make sure you have:
Tip
The extension includes the CLI (command-line interface), which you can access from VS Code's integrated terminal for advanced features. See VS Code extension vs. Claude Code CLI for details.
Click the link for your IDE to install directly:
Or in VS Code, press Cmd+Shift+X (Mac) or Ctrl+Shift+X (Windows/Linux) to open the Extensions view, search for "Claude Code", and click Install.
Note
If the extension doesn't appear after installation, restart VS Code or run "Developer: Reload Window" from the Command Palette.
Once installed, you can start using Claude Code through the VS Code interface:
Throughout VS Code, the Spark icon indicates Claude Code: <img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/vs-code-spark-icon.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=3ca45e00deadec8c8f4b4f807da94505" alt="Spark icon" style={{display: "inline", height: "0.85em", verticalAlign: "middle"}} width="16" height="16" data-path="images/vs-code-spark-icon.svg" />
The quickest way to open Claude is to click the Spark icon in the Editor Toolbar (top-right corner of the editor). The icon only appears when you have a file open.
<img src="https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=eb4540325d94664c51776dbbfec4cf02" alt="VS Code editor showing the Spark icon in the Editor Toolbar" width="2796" height="734" data-path="images/vs-code-editor-icon.png" />
Other ways to open Claude Code:
Cmd+Shift+P (Mac) or Ctrl+Shift+P (Windows/Linux), type "Claude Code", and select an option like "Open in New Tab"You can drag the Claude panel to reposition it anywhere in VS Code. See Customize your workflow for details.
The first time you open the panel, a sign-in screen appears. Click Sign in and complete authorization in your browser.
If you see Not logged in · Please run /login later, the extension reopens the sign-in screen automatically. If it doesn't appear, reload the window from the Command Palette with Developer: Reload Window.
If you have ANTHROPIC_API_KEY set in your shell but still see the sign-in prompt, VS Code may not have inherited your shell environment. Launch VS Code from a terminal with code . so it inherits your environment variables, or sign in with your Claude account instead.
After you sign in, a Learn Claude Code checklist appears. Work through each item by clicking Show me, or dismiss it with the X. To reopen it later, uncheck Hide Onboarding in VS Code settings under Extensions → Claude Code.
Ask Claude to help with your code or files, whether that's explaining how something works, debugging an issue, or making changes.
Tip
Claude automatically sees your selected text. Press Option+K (Mac) / Alt+K (Windows/Linux) to also insert an @-mention reference (like @file.ts#5-10) into your prompt.
Here's an example of asking about a particular line in a file:
<img src="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=ede3ed8d8d5f940e01c5de636d009cfd" alt="VS Code editor with lines 2-3 selected in a Python file, and the Claude Code panel showing a question about those lines with an @-mention reference" width="3288" height="1876" data-path="images/vs-code-send-prompt.png" />
When Claude wants to edit a file, it shows a side-by-side comparison of the original and proposed changes, then asks for permission. You can accept, reject, or tell Claude what to do instead.
<img src="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=e005f9b41c541c5c7c59c082f7c4841c" alt="VS Code showing a diff of Claude's proposed changes with a permission prompt asking whether to make the edit" width="3292" height="1876" data-path="images/vs-code-edits.png" />
For more ideas on what you can do with Claude Code, see Common workflows.
Tip
Run "Claude Code: Open Walkthrough" from the Command Palette for a guided tour of the basics.
The prompt box supports several features:
claudeCode.initialPermissionMode./ or type / to open the command menu. Options include attaching files, switching models, toggling extended thinking, viewing plan usage (/usage), and starting a Remote Control session (/remote-control). The Customize section provides access to MCP servers, hooks, memory, permissions, and plugins. Items with a terminal icon open in the integrated terminal./compact manually./). See Extended thinking for details.Shift+Enter to add a new line without sending. This also works in the "Other" free-text input of question dialogs.Use @-mentions to give Claude context about specific files or folders. When you type @ followed by a file or folder name, Claude reads that content and can answer questions about it or make changes to it. Claude Code supports fuzzy matching, so you can type partial names to find what you need:
> Explain the logic in @auth (fuzzy matches auth.js, AuthService.ts, etc.)
> What's in @src/components/ (include a trailing slash for folders)
For large PDFs, you can ask Claude to read specific pages instead of the whole file: a single page, a range like pages 1-10, or an open-ended range like page 3 onward.
When you select text in the editor, Claude can see your highlighted code automatically. The prompt box footer shows how many lines are selected. Press Option+K (Mac) / Alt+K (Windows/Linux) to insert an @-mention with the file path and line numbers (e.g., @app.ts#5-10). Click the selection indicator to toggle whether Claude can see your highlighted text - the eye-slash icon means the selection is hidden from Claude.
You can also hold Shift while dragging files into the prompt box to add them as attachments. Click the X on any attachment to remove it from context.
Click the dropdown at the top of the Claude Code panel to access your conversation history. You can search by keyword or browse by time (Today, Yesterday, Last 7 days, etc.). Click any conversation to resume it with the full message history. New sessions receive AI-generated titles based on your first message. Hover over a session to reveal rename and remove actions: rename to give it a descriptive title, or remove to delete it from the list. For more on resuming sessions, see Common workflows.
If you use Claude Code on the web, you can resume those remote sessions directly in VS Code. This requires signing in with Claude.ai Subscription, not Anthropic Console.
Click the Past Conversations dropdown at the top of the Claude Code panel.
The dialog shows two tabs: Local and Remote. Click Remote to see sessions from claude.ai.
Browse or search your remote sessions. Click any session to download it and continue the conversation locally.
Note
Only web sessions started with a GitHub repository appear in the Remote tab. Resuming loads the conversation history locally; changes are not synced back to claude.ai.
Once you're up and running, you can reposition the Claude panel, run multiple sessions, or switch to terminal mode.
You can drag the Claude panel to reposition it anywhere in VS Code. Grab the panel's tab or title bar and drag it to:
Tip
Use the sidebar for your main Claude session and open additional tabs for side tasks. Claude remembers your preferred location. The Activity Bar sessions list icon is separate from the Claude panel: the sessions list is always visible in the Activity Bar, while the Claude panel icon only appears there when the panel is docked to the left sidebar.
Use Open in New Tab or Open in New Window from the Command Palette to start additional conversations. Each conversation maintains its own history and context, allowing you to work on different tasks in parallel.
When using tabs, a small colored dot on the spark icon indicates status: blue means a permission request is pending, orange means Claude finished while the tab was hidden.
By default, the extension opens a graphical chat panel. If you prefer the CLI-style interface, open the Use Terminal setting and check the box.
You can also open VS Code settings (Cmd+, on Mac or Ctrl+, on Windows/Linux), go to Extensions → Claude Code, and check Use Terminal.
The VS Code extension includes a graphical interface for installing and managing plugins. Type /plugins in the prompt box to open the Manage plugins interface.
The plugin dialog shows two tabs: Plugins and Marketplaces.
In the Plugins tab:
When you install a plugin, choose the installation scope:
Switch to the Marketplaces tab to add or remove plugin sources:
After making changes, a banner prompts you to restart Claude Code to apply the updates.
Note
Plugin management in VS Code uses the same CLI commands under the hood. Plugins and marketplaces you configure in the extension are also available in the CLI, and vice versa.
For more about the plugin system, see Plugins and Plugin marketplaces.
Connect Claude to your Chrome browser to test web apps, debug with console logs, and automate browser workflows without leaving VS Code. This requires the Claude in Chrome extension version 1.0.36 or higher.
Type @browser in the prompt box followed by what you want Claude to do:
@browser go to localhost:3000 and check the console for errors
You can also open the attachment menu to select specific browser tools like opening a new tab or reading page content.
Claude opens new tabs for browser tasks and shares your browser's login state, so it can access any site you're already signed into.
For setup instructions, the full list of capabilities, and troubleshooting, see Use Claude Code with Chrome.
Open the Command Palette (Cmd+Shift+P on Mac or Ctrl+Shift+P on Windows/Linux) and type "Claude Code" to see all available VS Code commands for the Claude Code extension.
Some shortcuts depend on which panel is "focused" (receiving keyboard input). When your cursor is in a code file, the editor is focused. When your cursor is in Claude's prompt box, Claude is focused. Use Cmd+Esc / Ctrl+Esc to toggle between them.
Note
These are VS Code commands for controlling the extension. Not all built-in Claude Code commands are available in the extension. See VS Code extension vs. Claude Code CLI for details.
| Command | Shortcut | Description |
|---|---|---|
| Focus Input | Cmd+Esc (Mac) / Ctrl+Esc (Windows/Linux) |
Toggle focus between editor and Claude |
| Open in Side Bar | - | Open Claude in the left sidebar |
| Open in Terminal | - | Open Claude in terminal mode |
| Open in New Tab | Cmd+Shift+Esc (Mac) / Ctrl+Shift+Esc (Windows/Linux) |
Open a new conversation as an editor tab |
| Open in New Window | - | Open a new conversation in a separate window |
| New Conversation | Cmd+N (Mac) / Ctrl+N (Windows/Linux) |
Start a new conversation. Requires Claude to be focused and enableNewConversationShortcut set to true |
| Insert @-Mention Reference | Option+K (Mac) / Alt+K (Windows/Linux) |
Insert a reference to the current file and selection (requires editor to be focused) |
| Show Logs | - | View extension debug logs |
| Logout | - | Sign out of your Anthropic account |
The extension registers a URI handler at vscode://anthropic.claude-code/open. Use it to open a new Claude Code tab from your own tooling: a shell alias, a browser bookmarklet, or any script that can open a URL. If VS Code isn't already running, opening the URL launches it first. If VS Code is already running, the URL opens in whichever window is currently focused.
Invoke the handler with your operating system's URL opener. On macOS:
open "vscode://anthropic.claude-code/open"
Use xdg-open on Linux or start on Windows.
The handler accepts two optional query parameters:
| Parameter | Description |
|---|---|
prompt |
Text to pre-fill in the prompt box. Must be URL-encoded. The prompt is pre-filled but not submitted automatically. |
session |
A session ID to resume instead of starting a new conversation. The session must belong to the workspace currently open in VS Code. If the session isn't found, a fresh conversation starts instead. If the session is already open in a tab, that tab is focused. To capture a session ID programmatically, see Continue conversations. |
For example, to open a tab pre-filled with "review my changes":
vscode://anthropic.claude-code/open?prompt=review%20my%20changes
The extension has two types of settings:
Cmd+, (Mac) or Ctrl+, (Windows/Linux), then go to Extensions → Claude Code. You can also type / and select General Config to open settings.~/.claude/settings.json: shared between the extension and CLI. Use for allowed commands, environment variables, hooks, and MCP servers. See Settings for details.Tip
Add "$schema": "https://json.schemastore.org/claude-code-settings.json" to your settings.json to get autocomplete and inline validation for all available settings directly in VS Code.
| Setting | Default | Description |
|---|---|---|
useTerminal |
false |
Launch Claude in terminal mode instead of graphical panel |
initialPermissionMode |
default |
Controls approval prompts for new conversations: default, plan, acceptEdits, or bypassPermissions. See permission modes. |
preferredLocation |
panel |
Where Claude opens: sidebar (right) or panel (new tab) |
autosave |
true |
Auto-save files before Claude reads or writes them |
useCtrlEnterToSend |
false |
Use Ctrl/Cmd+Enter instead of Enter to send prompts |
enableNewConversationShortcut |
false |
Enable Cmd/Ctrl+N to start a new conversation |
hideOnboarding |
false |
Hide the onboarding checklist (graduation cap icon) |
respectGitIgnore |
true |
Exclude .gitignore patterns from file searches |
usePythonEnvironment |
true |
Activate the workspace's Python environment when running Claude. Requires the Python extension. |
environmentVariables |
[] |
Set environment variables for the Claude process. Use Claude Code settings instead for shared config. |
disableLoginPrompt |
false |
Skip authentication prompts (for third-party provider setups) |
allowDangerouslySkipPermissions |
false |
Adds Auto mode and Bypass permissions to the mode selector. Auto mode has plan, admin, model, and provider requirements, so it may remain unavailable even with this toggle on. Use Bypass permissions only in sandboxes with no internet access. |
claudeProcessWrapper |
- | Executable path used to launch the Claude process |
Claude Code is available as both a VS Code extension (graphical panel) and a CLI (command-line interface in the terminal). Some features are only available in the CLI. If you need a CLI-only feature, run claude in VS Code's integrated terminal.
| Feature | CLI | VS Code Extension |
|---|---|---|
| Commands and skills | All | Subset (type / to see available) |
| MCP server config | Yes | Partial (add servers via CLI; manage existing servers with /mcp in the chat panel) |
| Checkpoints | Yes | Yes |
! bash shortcut |
Yes | No |
| Tab completion | Yes | No |
The VS Code extension supports checkpoints, which track Claude's file edits and let you rewind to a previous state. Hover over any message to reveal the rewind button, then choose from three options:
For full details on how checkpoints work and their limitations, see Checkpointing.
To use the CLI while staying in VS Code, open the integrated terminal (Ctrl+` on Windows/Linux or Cmd+` on Mac) and run claude. The CLI automatically integrates with your IDE for features like diff viewing and diagnostic sharing.
If using an external terminal, run /ide inside Claude Code to connect it to VS Code.
The extension and CLI share the same conversation history. To continue an extension conversation in the CLI, run claude --resume in the terminal. This opens an interactive picker where you can search for and select your conversation.
Reference terminal output in your prompts using @terminal:name where name is the terminal's title. This lets Claude see command output, error messages, or logs without copy-pasting.
When Claude runs long-running commands, the extension shows progress in the status bar. However, visibility for background tasks is limited compared to the CLI. For better visibility, have Claude output the command so you can run it in VS Code's integrated terminal.
MCP (Model Context Protocol) servers give Claude access to external tools, databases, and APIs.
To add an MCP server, open the integrated terminal (Ctrl+` or Cmd+`) and run:
claude mcp add --transport http github https://api.githubcopilot.com/mcp/
Once configured, ask Claude to use the tools (e.g., "Review PR #456").
To manage MCP servers without leaving VS Code, type /mcp in the chat panel. The MCP management dialog lets you enable or disable servers, reconnect to a server, and manage OAuth authentication. See the MCP documentation for available servers.
Claude Code integrates with git to help with version control workflows directly in VS Code. Ask Claude to commit changes, create pull requests, or work across branches.
Claude can stage changes, write commit messages, and create pull requests based on your work:
> commit my changes with a descriptive message
> create a pr for this feature
> summarize the changes I've made to the auth module
When creating pull requests, Claude generates descriptions based on the actual code changes and can add context about testing or implementation decisions.
Use the --worktree (-w) flag to start Claude in an isolated worktree with its own files and branch:
claude --worktree feature-auth
Each worktree maintains independent file state while sharing git history. This prevents Claude instances from interfering with each other when working on different tasks. For more details, see Run parallel sessions with Git worktrees.
By default, Claude Code connects directly to Anthropic's API. If your organization uses Amazon Bedrock, Google Vertex AI, or Microsoft Foundry to access Claude, configure the extension to use your provider instead:
Open the Disable Login Prompt setting and check the box.
You can also open VS Code settings (Cmd+, on Mac or Ctrl+, on Windows/Linux), search for "Claude Code login", and check Disable Login Prompt.
Follow the setup guide for your provider:
These guides cover configuring your provider in ~/.claude/settings.json, which ensures your settings are shared between the VS Code extension and the CLI.
Your code stays private. Claude Code processes your code to provide assistance but does not use it to train models. For details on data handling and how to opt out of logging, see Data and privacy.
With auto-edit permissions enabled, Claude Code can modify VS Code configuration files (like settings.json or tasks.json) that VS Code may execute automatically. To reduce risk when working with untrusted code:
When the extension is active, it runs a local MCP server that the CLI connects to automatically. This is how the CLI opens diffs in VS Code's native diff viewer, reads your current selection for @-mentions, and — when you're working in a Jupyter notebook — asks VS Code to execute cells.
The server is named ide and is hidden from /mcp because there's nothing to configure. If your organization uses a PreToolUse hook to allowlist MCP tools, though, you'll need to know it exists.
Transport and authentication. The server binds to 127.0.0.1 on a random high port and is not reachable from other machines. Each extension activation generates a fresh random auth token that the CLI must present to connect. The token is written to a lock file under ~/.claude/ide/ with 0600 permissions in a 0700 directory, so only the user running VS Code can read it.
Tools exposed to the model. The server hosts a dozen tools, but only two are visible to the model. The rest are internal RPC the CLI uses for its own UI — opening diffs, reading selections, saving files — and are filtered out before the tool list reaches Claude.
| Tool name (as seen by hooks) | What it does | Writes? |
|---|---|---|
mcp__ide__getDiagnostics |
Returns language-server diagnostics — the errors and warnings in VS Code's Problems panel. Optionally scoped to one file. | No |
mcp__ide__executeCode |
Runs Python code in the active Jupyter notebook's kernel. See confirmation flow below. | Yes |
Jupyter execution always asks first. mcp__ide__executeCode can't run anything silently. On each call, the code is inserted as a new cell at the end of the active notebook, VS Code scrolls it into view, and a native Quick Pick asks you to Execute or Cancel. Cancelling — or dismissing the picker with Esc — returns an error to Claude and nothing runs. The tool also refuses outright when there's no active notebook, when the Jupyter extension (ms-toolsai.jupyter) isn't installed, or when the kernel isn't Python.
Note
The Quick Pick confirmation is separate from PreToolUse hooks. An allowlist entry for mcp__ide__executeCode lets Claude propose running a cell; the Quick Pick inside VS Code is what lets it actually run.
The Spark icon appears in the Editor Toolbar (top-right of editor) when you have a file open. If you don't see it:
Alternatively, click "✱ Claude Code" in the Status Bar (bottom-right corner). This works even without a file open. You can also use the Command Palette (Cmd+Shift+P / Ctrl+Shift+P) and type "Claude Code".
If Claude Code isn't responding to your prompts:
claude from the terminal to see if you get more detailed error messagesIf problems persist, file an issue on GitHub with details about the error.
To uninstall the Claude Code extension:
Cmd+Shift+X on Mac or Ctrl+Shift+X on Windows/Linux)To also remove extension data and reset all settings:
rm -rf ~/.vscode/globalStorage/anthropic.claude-code
For additional help, see the troubleshooting guide.
Now that you have Claude Code set up in VS Code:
/mcp in the chat panel.Use Claude Code with JetBrains IDEs including IntelliJ, PyCharm, WebStorm, and more
Claude Code integrates with JetBrains IDEs through a dedicated plugin, providing features like interactive diff viewing, selection context sharing, and more.
The Claude Code plugin works with most JetBrains IDEs, including:
Cmd+Esc (Mac) or Ctrl+Esc (Windows/Linux) to open Claude Code directly from your editor, or click the Claude Code button in the UICmd+Option+K (Mac) or Alt+Ctrl+K (Linux/Windows) to insert file references (for example, @File#L1-99)Find and install the Claude Code plugin from the JetBrains marketplace and restart your IDE.
If you haven't installed Claude Code yet, see our quickstart guide for installation instructions.
Note
After installing the plugin, you may need to restart your IDE completely for it to take effect.
Run claude from your IDE's integrated terminal, and all integration features will be active.
Use the /ide command in any external terminal to connect Claude Code to your JetBrains IDE and activate all features:
claude
/ide
If you want Claude to have access to the same files as your IDE, start Claude Code from the same directory as your IDE project root.
Configure IDE integration through Claude Code's settings:
claude/config commandauto for automatic IDE detectionConfigure the Claude Code plugin by going to Settings → Tools → Claude Code [Beta]:
claude, /usr/local/bin/claude, or npx @anthropic-ai/claude-code)Tip
For WSL users: Set wsl -d Ubuntu -- bash -lic "claude" as your Claude command (replace Ubuntu with your WSL distribution name)
If the ESC key doesn't interrupt Claude Code operations in JetBrains terminals:
This allows the ESC key to properly interrupt Claude Code operations.
Warning
When using JetBrains Remote Development, you must install the plugin in the remote host via Settings → Plugin (Host).
The plugin must be installed on the remote host, not on your local client machine.
Warning
WSL users may need additional configuration for IDE detection to work properly. See our WSL troubleshooting guide for detailed setup instructions.
WSL configuration may require:
If clicking the Claude icon shows "command not found":
npm list -g @anthropic-ai/claude-codeWhen Claude Code runs in a JetBrains IDE with auto-edit permissions enabled, it may be able to modify IDE configuration files that can be automatically executed by your IDE. This may increase the risk of running Claude Code in auto-edit mode and allow bypassing Claude Code's permission prompts for bash execution.
When running in JetBrains IDEs, consider:
For additional help, see our troubleshooting guide.
Delegate coding tasks directly from your Slack workspace
Claude Code in Slack brings the power of Claude Code directly into your Slack workspace. When you mention @Claude with a coding task, Claude automatically detects the intent and creates a Claude Code session on the web, allowing you to delegate development work without leaving your team conversations.
This integration is built on the existing Claude for Slack app but adds intelligent routing to Claude Code on the web for coding-related requests.
Before using Claude Code in Slack, ensure you have the following:
| Requirement | Details |
|---|---|
| Claude Plan | Pro, Max, Team, or Enterprise with Claude Code access (premium seats or Chat + Claude Code seats) |
| Claude Code on the web | Access to Claude Code on the web must be enabled |
| GitHub Account | Connected to Claude Code on the web with at least one repository authenticated |
| Slack Authentication | Your Slack account linked to your Claude account via the Claude app |
A workspace administrator must install the Claude app from the Slack App Marketplace. Visit the Slack App Marketplace and click "Add to Slack" to begin the installation process.
After the app is installed, authenticate your individual Claude account:
Ensure your Claude Code on the web is properly configured:
After connecting your accounts, configure how Claude handles your messages in Slack. Navigate to the Claude App Home in Slack to find the Routing Mode setting.
| Mode | Behavior |
|---|---|
| Code only | Claude routes all @mentions to Claude Code sessions. Best for teams using Claude in Slack exclusively for development tasks. |
| Code + Chat | Claude analyzes each message and intelligently routes between Claude Code (for coding tasks) and Claude Chat (for writing, analysis, and general questions). Best for teams who want a single @Claude entry point for all types of work. |
Note
In Code + Chat mode, if Claude routes a message to Chat but you wanted a coding session, you can click "Retry as Code" to create a Claude Code session instead. Similarly, if it's routed to Code but you wanted a Chat session, you can choose that option in that thread.
Claude is not automatically added to any channels after installation. To use Claude in a channel, invite it by typing /invite @Claude in that channel. Claude can only respond to @mentions in channels where it has been added.
When you mention @Claude in a Slack channel or thread, Claude automatically analyzes your message to determine if it's a coding task. If Claude detects coding intent, it will route your request to Claude Code on the web instead of responding as a regular chat assistant.
You can also explicitly tell Claude to handle a request as a coding task, even if it doesn't automatically detect it.
Note
Claude Code in Slack only works in channels (public or private). It does not work in direct messages (DMs).
From threads: When you @mention Claude in a thread, it gathers context from all messages in that thread to understand the full conversation.
From channels: When mentioned directly in a channel, Claude looks at recent channel messages for relevant context.
This context helps Claude understand the problem, select the appropriate repository, and inform its approach to the task.
Warning
When @Claude is invoked in Slack, Claude is given access to the conversation context to better understand your request. Claude may follow directions from other messages in the context, so users should make sure to only use Claude in trusted Slack conversations.
The App Home tab shows your connection status and allows you to connect or disconnect your Claude account from Slack.
Claude automatically selects a repository based on context from your Slack conversation. If multiple repositories could apply, Claude may display a dropdown allowing you to choose the correct one.
| Access Type | Requirement |
|---|---|
| Claude Code Sessions | Each user runs sessions under their own Claude account |
| Usage & Rate Limits | Sessions count against the individual user's plan limits |
| Repository Access | Users can only access repositories they've personally connected |
| Session History | Sessions appear in your Claude Code history on claude.ai/code |
Slack workspace administrators control whether the Claude app is available in their workspace:
| Control | Description |
|---|---|
| App installation | Workspace admins decide whether to install the Claude app from the Slack App Marketplace |
| Enterprise Grid distribution | For Enterprise Grid organizations, organization admins can control which workspaces have access to the Claude app |
| App removal | Removing the app from a workspace immediately revokes access for all users in that workspace |
Claude is not automatically added to any channels after installation. Users must explicitly invite Claude to channels where they want to use it:
/invite @Claude in any channel to add Claude to that channelThis channel-based model allows teams to restrict Claude Code usage to specific channels, providing an additional layer of access control beyond workspace-level permissions.
In Slack: You'll see status updates, completion summaries, and action buttons. The full transcript is preserved and always accessible.
On the web: The complete Claude Code session with full conversation history, all code changes, file operations, and the ability to continue the session or create pull requests.
For Enterprise and Team accounts, sessions created from Claude in Slack are automatically visible to the organization. See Claude Code on the Web sharing for more details.
Use Slack when: Context already exists in a Slack discussion, you want to kick off a task asynchronously, or you're collaborating with teammates who need visibility.
Use the web directly when: You need to upload files, want real-time interaction during development, or are working on longer, more complex tasks.
Run Claude Code in the cloud from your browser or phone. Connect a GitHub repository, submit a task, and review the PR without local setup.
Note
Claude Code on the web is in research preview for Pro, Max, and Team users, and for Enterprise users with premium seats or Chat + Claude Code seats.
Claude Code on the web runs on Anthropic-managed cloud infrastructure instead of your machine. Submit tasks from claude.ai/code in your browser or the Claude mobile app.
You'll need a GitHub repository to get started. Claude clones it into an isolated virtual machine, makes changes, and pushes a branch for you to review. Sessions persist across devices, so a task you start on your laptop is ready to review from your phone later.
Claude Code on the web works well for:
For work that needs your local config, tools, or environment, running Claude Code locally or using Remote Control is a better fit.
When you submit a task:
The session doesn't close when the branch is pushed. PR creation and further edits all happen within the same conversation.
Claude Code behaves the same everywhere. What changes is where code executes and whether your local config is available. offers both local and cloud sessions, so its answers below depend on which you choose:
| On the web | Remote Control | Terminal CLI | |
|---|---|---|---|
| Code runs on | Anthropic cloud VM | Your machine | Your machine |
| You chat from | claude.ai or mobile app | claude.ai or mobile app | Your terminal |
| Uses your local config | No, repo only | Yes | Yes |
| Requires GitHub | Yes, or bundle a local repo via --remote |
No | No |
| Keeps running if you disconnect | Yes | While terminal stays open | No |
| Permission modes | Auto accept edits, Plan | Ask, Auto accept edits, Plan | All modes |
| Network access | Configurable per environment | Your machine's network | Your machine's network |
See the terminal quickstart or Remote Control docs to set those up.
Setup is a one-time process. If you already use the GitHub CLI, you can do this from your terminal instead of the browser.
Go to claude.ai/code and sign in with your Anthropic account.
After signing in, claude.ai/code prompts you to connect GitHub. Follow the prompt to install the Claude GitHub App and grant it access to your repositories. Cloud sessions work with existing GitHub repositories, so to start a new project, create an empty repository on GitHub first.
After connecting GitHub, you'll be prompted to create a cloud environment. The environment controls what network access Claude has during sessions and what runs when a new session is created. See Installed tools for what's available without any configuration.
The form has these fields:
Trusted, allows connections to common package registries like npm, PyPI, and RubyGems while blocking general internet access..env format. Don't wrap values in quotes, since quotes are stored as part of the value. These are visible to anyone who can edit this environment.apt install -y gh, or to start services your project needs. See Setup scripts for examples and debugging tips.For a first project, leave the defaults and click Create environment. You can edit it later or create additional environments for different projects.
If you already use the GitHub CLI (gh), you can set up Claude Code on the web without opening a browser. This requires the Claude Code CLI. /web-setup reads your local gh token, links it to your Claude account, and creates a default cloud environment if you don't have one.
Note
Organizations with Zero Data Retention enabled cannot use /web-setup or other cloud session features. If the GitHub CLI isn't installed or authenticated, /web-setup opens the browser onboarding flow instead.
In your shell, authenticate the GitHub CLI if you haven't already:
gh auth login
In the Claude Code CLI, run /login to sign in with your claude.ai account. Skip this step if you're already signed in.
In the Claude Code CLI, run:
/web-setup
This syncs your gh token to your Claude account. If you don't have a cloud environment yet, /web-setup creates one with Trusted network access and no setup script. You can edit the environment or add variables afterward. Once /web-setup completes, you can start cloud sessions from your terminal with --remote or set up recurring tasks with /schedule.
With GitHub connected and an environment created, you're ready to submit tasks.
From claude.ai/code or the Code tab in the Claude mobile app, click the repository selector below the input box and choose a repository for Claude to work in. Each repository shows a branch selector. Change it to start Claude from a feature branch instead of the default. You can add multiple repositories to work across them in one session.
The mode dropdown next to the input defaults to Auto accept edits, where Claude makes changes and pushes a branch without stopping for approval. Switch to Plan mode if you want Claude to propose an approach and wait for your go-ahead before editing files. Cloud sessions don't offer Ask permissions, Auto mode, or Bypass permissions. See Permission modes for the full list.
Type a description of what you want and press Enter. Be specific:
tests/test_auth.py" is better than "fix tests"Claude clones the repositories, runs your setup script if configured, and starts working. Each task gets its own session and its own branch, so you don't need to wait for one to finish before starting another.
When Claude finishes, review the changes, leave feedback on specific lines, and keep going until the diff looks right.
A diff indicator shows lines added and removed across the session, for example +42 -18. Select it to open the diff view, with a file list on the left and changes on the right.
Select any line in the diff, type your feedback, and press Enter. Comments queue up until you send your next message, then they're bundled with it. Claude sees "at src/auth.ts:47, don't catch the error here" alongside your main instruction, so you don't have to describe where the problem is.
When the diff looks right, select Create PR at the top of the diff view. You can open it as a full PR, a draft, or jump to GitHub's compose page with a generated title and description.
The session stays live after the PR is created. Paste CI failure output or reviewer comments into the chat and ask Claude to address them. To have Claude monitor the PR automatically, see Auto-fix pull requests.
The Claude GitHub App needs explicit access to each repository you want to use. On github.com, open Settings → Applications → Claude → Configure and verify your repo is listed under Repository access. Private repositories need the same authorization as public ones.
Cloud sessions require a connected GitHub account. Connect via the browser flow above, or run /web-setup from your terminal if you use the GitHub CLI. If you'd rather not connect GitHub at all, see Remote Control to run Claude Code on your own machine and monitor it from the web.
Enterprise organizations may need an admin to enable Claude Code on the web. Contact your Anthropic account team.
/web-setup returns "Unknown command"/web-setup runs inside the Claude Code CLI, not your shell. Launch claude first, then type /web-setup at the prompt.
If you typed it inside Claude Code and still see the error, your CLI is older than v2.1.80 or you're authenticated with an API key or third-party provider instead of a claude.ai subscription. Run claude update, then /login to sign in with your claude.ai account.
--remote or ultraplanRemote-session features create a default cloud environment automatically if you don't have one. If you see "Could not create a cloud environment", automatic creation failed. {/* max-version: 2.1.100 */}If you see "No cloud environment available", your CLI predates automatic creation. In either case, run /web-setup in the Claude Code CLI to create one manually, or visit claude.ai/code and follow the Create your environment step above.
The setup script exited with a non-zero status, which blocks the session from starting. Common causes:
Trusted covers most package managers; None blocks them all.To debug, add set -x at the top of the script to see which command failed. For non-critical commands, append || true so they don't block session start.
This is by design. Closing the tab or navigating away doesn't stop the session. It continues running in the background until Claude finishes the current task, then idles. From the sidebar, you can archive a session to hide it from your list, or delete it to remove it permanently.
Now that you can submit and review tasks, these pages cover what comes next: starting cloud sessions from your terminal, scheduling recurring work, and giving Claude standing instructions.
/mobile shows a QR code.Configure cloud environments, setup scripts, network access, and Docker in Anthropic's sandbox. Move sessions between web and terminal with `--remote` and `--teleport`.
Note
Claude Code on the web is in research preview for Pro, Max, and Team users, and for Enterprise users with premium seats or Chat + Claude Code seats.
Claude Code on the web runs tasks on Anthropic-managed cloud infrastructure at claude.ai/code. Sessions persist even if you close your browser, and you can monitor them from the Claude mobile app.
Tip
New to Claude Code on the web? Start with Get started to connect your GitHub account and submit your first task.
This page covers:
--remote and --teleportCloud sessions need access to your GitHub repositories to clone code and push branches. You can grant access in two ways:
| Method | How it works | Best for |
|---|---|---|
| GitHub App | Install the Claude GitHub App on specific repositories during web onboarding. Access is scoped per repository. | Teams that want explicit per-repo authorization |
/web-setup |
Run /web-setup in your terminal to sync your local gh CLI token to your Claude account. Access matches whatever your gh token can see. |
Individual developers who already use gh |
Either method works. /schedule checks for either form of access and prompts you to run /web-setup if neither is configured. See Connect from your terminal for the /web-setup walkthrough.
The GitHub App is required for Auto-fix, which uses the App to receive PR webhooks. If you connect with /web-setup and later want Auto-fix, install the App on those repositories.
Team and Enterprise admins can disable /web-setup with the Quick web setup toggle at claude.ai/admin-settings/claude-code.
Note
Organizations with Zero Data Retention enabled cannot use /web-setup or other cloud session features.
Each session runs in a fresh Anthropic-managed VM with your repository cloned. This section covers what's available when a session starts and how to customize it.
Cloud sessions start from a fresh clone of your repository. Anything committed to the repo is available. Anything you've installed or configured only on your own machine is not.
| Available in cloud sessions | Why | |
|---|---|---|
Your repo's CLAUDE.md |
Yes | Part of the clone |
Your repo's .claude/settings.json hooks |
Yes | Part of the clone |
Your repo's .mcp.json MCP servers |
Yes | Part of the clone |
Your repo's .claude/rules/ |
Yes | Part of the clone |
Your repo's .claude/skills/, .claude/agents/, .claude/commands/ |
Yes | Part of the clone |
Plugins declared in .claude/settings.json |
Yes | Installed at session start from the marketplace you declared. Requires network access to reach the marketplace source |
Your user ~/.claude/CLAUDE.md |
No | Lives on your machine, not in the repo |
| Plugins enabled only in your user settings | No | User-scoped enabledPlugins lives in ~/.claude/settings.json. Declare them in the repo's .claude/settings.json instead |
MCP servers you added with claude mcp add |
No | Those write to your local user config, not the repo. Declare the server in .mcp.json instead |
| Static API tokens and credentials | No | No dedicated secrets store exists yet. See below |
| Interactive auth like AWS SSO | No | Not supported. SSO requires browser-based login that can't run in a cloud session |
To make configuration available in cloud sessions, commit it to the repo. A dedicated secrets store is not yet available. Both environment variables and setup scripts are stored in the environment configuration, visible to anyone who can edit that environment. If you need secrets in a cloud session, add them as environment variables with that visibility in mind.
Cloud sessions come with common language runtimes, build tools, and databases pre-installed. The table below summarizes what's included by category.
| Category | Included |
|---|---|
| Python | Python 3.x with pip, poetry, uv, black, mypy, pytest, ruff |
| Node.js | 20, 21, and 22 via nvm, with npm, yarn, pnpm, bun¹, eslint, prettier, chromedriver |
| Ruby | 3.1, 3.2, 3.3 with gem, bundler, rbenv |
| PHP | 8.4 with Composer |
| Java | OpenJDK 21 with Maven and Gradle |
| Go | latest stable with module support |
| Rust | rustc and cargo |
| C/C++ | GCC, Clang, cmake, ninja, conan |
| Docker | docker, dockerd, docker compose |
| Databases | PostgreSQL 16, Redis 7.0 |
| Utilities | git, jq, yq, ripgrep, tmux, vim, nano |
¹ Bun is installed but has known proxy compatibility issues for package fetching.
For exact versions, ask Claude to run check-tools in a cloud session. This command only exists in cloud sessions.
Cloud sessions include built-in GitHub tools that let Claude read issues, list pull requests, fetch diffs, and post comments without any setup. These tools authenticate through the GitHub proxy using whichever method you configured under GitHub authentication options, so your token never enters the container.
The gh CLI is not pre-installed. If you need a gh command the built-in tools don't cover, like gh release or gh workflow run, install and authenticate it yourself:
Add apt update && apt install -y gh to your setup script.
Add a GH_TOKEN environment variable to your environment settings with a GitHub personal access token. gh reads GH_TOKEN automatically, so no gh auth login step is needed.
Claude runs tests as part of working on a task. Ask for it in your prompt, like "fix the failing tests in tests/" or "run pytest after each change." Test runners like pytest, jest, and cargo test work out of the box since they're pre-installed.
PostgreSQL and Redis are pre-installed but not running by default. Start each one in a setup script or ask Claude to start it during the session:
service postgresql start
service redis-server start
Docker is available for running containerized services. Network access to pull images follows your environment's access level.
To add packages that aren't pre-installed, use a setup script so they're available at session start. You can also ask Claude to install packages during the session, but those installs don't persist across sessions.
Cloud sessions run with approximate resource ceilings that may change over time:
Tasks requiring significantly more memory, such as large build jobs or memory-intensive tests, may fail or be terminated. For workloads beyond these limits, use Remote Control to run Claude Code on your own hardware.
Environments control network access, environment variables, and the setup script that runs before a session starts. See Installed tools for what's available without any configuration. You can manage environments from the web interface or the terminal:
| Action | How |
|---|---|
| Add an environment | Select the current environment to open the selector, then select Add environment. The dialog includes name, network access level, environment variables, and setup script. |
| Edit an environment | Select the settings icon to the right of the environment name. |
| Archive an environment | Open the environment for editing and select Archive. Archived environments are hidden from the selector but existing sessions keep running. |
Set the default for --remote |
Run /remote-env in your terminal. If you have a single environment, this command shows your current configuration. /remote-env only selects the default; add, edit, and archive environments from the web interface. |
Environment variables use .env format with one KEY=value pair per line. Don't wrap values in quotes, since quotes are stored as part of the value.
NODE_ENV=development
LOG_LEVEL=debug
DATABASE_URL=postgres://localhost:5432/myapp
A setup script is a Bash script that runs when a new cloud session starts, before Claude Code launches. Use setup scripts to install dependencies, configure tools, or fetch anything the session needs that isn't pre-installed.
Scripts run as root on Ubuntu 24.04, so apt install and most language package managers work.
To add a setup script, open the environment settings dialog and enter your script in the Setup script field.
This example installs the gh CLI, which isn't pre-installed:
#!/bin/bash
apt update && apt install -y gh
Setup scripts run only when creating a new session. They are skipped when resuming an existing session.
If the script exits non-zero, the session fails to start. Append || true to non-critical commands to avoid blocking the session on an intermittent install failure.
Note
Setup scripts that install packages need network access to reach registries. The default Trusted network access allows connections to common package registries including npm, PyPI, RubyGems, and crates.io. Scripts will fail to install packages if your environment uses None network access.
Use a setup script to install things the cloud needs but your laptop already has, like a language runtime or CLI tool. Use a SessionStart hook for project setup that should run everywhere, cloud and local, like npm install.
Both run at the start of a session, but they belong to different places:
| Setup scripts | SessionStart hooks | |
|---|---|---|
| Attached to | The cloud environment | Your repository |
| Configured in | Cloud environment UI | .claude/settings.json in your repo |
| Runs | Before Claude Code launches, on new sessions only | After Claude Code launches, on every session including resumed |
| Scope | Cloud environments only | Both local and cloud |
SessionStart hooks can also be defined in your user-level ~/.claude/settings.json locally, but user-level settings don't carry over to cloud sessions. In the cloud, only hooks committed to the repo run.
To install dependencies only in cloud sessions, add a SessionStart hook to your repo's .claude/settings.json:
{
"hooks": {
"SessionStart": [
{
"matcher": "startup|resume",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/scripts/install_pkgs.sh"
}
]
}
]
}
}
Create the script at scripts/install_pkgs.sh and make it executable with chmod +x. The CLAUDE_CODE_REMOTE environment variable is set to true in cloud sessions, so you can use it to skip local execution:
#!/bin/bash
if [ "$CLAUDE_CODE_REMOTE" != "true" ]; then
exit 0
fi
npm install
pip install -r requirements.txt
exit 0
SessionStart hooks have some limitations in cloud sessions:
CLAUDE_CODE_REMOTE environment variable as shown above.To persist environment variables for subsequent Bash commands, write to the file at $CLAUDE_ENV_FILE. See SessionStart hooks for details.
Custom environment images and snapshots are not yet supported.
Network access controls outbound connections from the cloud environment. Each environment specifies one access level, and you can extend it with custom allowed domains. The default is Trusted, which allows package registries and other allowlisted domains.
Choose an access level when you create or edit an environment:
| Level | Outbound connections |
|---|---|
| None | No outbound network access |
| Trusted | Allowlisted domains only: package registries, GitHub, cloud SDKs |
| Full | Any domain |
| Custom | Your own allowlist, optionally including the defaults |
GitHub operations use a separate proxy that is independent of this setting.
To allow domains that aren't in the Trusted list, select Custom in the environment's network access settings. An Allowed domains field appears. Enter one domain per line:
api.example.com
*.internal.example.com
registry.example.com
Use *. for wildcard subdomain matching. Check Also include default list of common package managers to keep the Trusted domains alongside your custom entries, or leave it unchecked to allow only what you list.
For security, all GitHub operations go through a dedicated proxy service that transparently handles all git interactions. Inside the sandbox, the git client authenticates using a custom-built scoped credential. This proxy:
Environments run behind an HTTP/HTTPS network proxy for security and abuse prevention purposes. All outbound internet traffic passes through this proxy, which provides:
When using Trusted network access, the following domains are allowed by default. Domains marked with * indicate wildcard subdomain matching, so *.gcr.io allows any subdomain of gcr.io.
These workflows require the Claude Code CLI signed in to the same claude.ai account. You can start new cloud sessions from your terminal, or pull cloud sessions into your terminal to continue locally. Cloud sessions persist even if you close your laptop, and you can monitor them from anywhere including the Claude mobile app.
Note
From the CLI, session handoff is one-way: you can pull cloud sessions into your terminal with --teleport, but you can't push an existing terminal session to the web. The --remote flag creates a new cloud session for your current repository. provides a Continue in menu that can send a local session to the web.
Start a cloud session from the command line with the --remote flag:
claude --remote "Fix the authentication bug in src/auth/login.ts"
This creates a new cloud session on claude.ai. The session clones your current directory's GitHub remote at your current branch, so push first if you have local commits, since the VM clones from GitHub rather than your machine. --remote works with a single repository at a time. The task runs in the cloud while you continue working locally.
Note
--remote creates cloud sessions. --remote-control is unrelated: it exposes a local CLI session for monitoring from the web. See Remote Control.
Use /tasks in the Claude Code CLI to check progress, or open the session on claude.ai or the Claude mobile app to interact directly. From there you can steer Claude, provide feedback, or answer questions just like any other conversation.
Plan locally, execute remotely: for complex tasks, start Claude in plan mode to collaborate on the approach, then send work to the cloud:
claude --permission-mode plan
In plan mode, Claude reads files, runs commands to explore, and proposes a plan without editing source code. Once you're satisfied, save the plan to the repo, commit, and push so the cloud VM can clone it. Then start a cloud session for autonomous execution:
claude --remote "Execute the migration plan in docs/migration-plan.md"
This pattern gives you control over the strategy while letting Claude execute autonomously in the cloud.
Plan in the cloud with ultraplan: to draft and review the plan itself in a web session, use ultraplan. Claude generates the plan on Claude Code on the web while you keep working, then you comment on sections in your browser and choose to execute remotely or send the plan back to your terminal.
Run tasks in parallel: each --remote command creates its own cloud session that runs independently. You can start multiple tasks and they'll all run simultaneously in separate sessions:
claude --remote "Fix the flaky test in auth.spec.ts"
claude --remote "Update the API documentation"
claude --remote "Refactor the logger to use structured output"
Monitor all sessions with /tasks in the Claude Code CLI. When a session completes, you can create a PR from the web interface or teleport the session to your terminal to continue working.
When you run claude --remote from a repository that isn't connected to GitHub, Claude Code bundles your local repository and uploads it directly to the cloud session. The bundle includes your full repository history across all branches, plus any uncommitted changes to tracked files.
This fallback activates automatically when GitHub access isn't available. To force it even when GitHub is connected, set CCR_FORCE_BUNDLE=1:
CCR_FORCE_BUNDLE=1 claude --remote "Run the test suite and fix any failures"
Bundled repositories must meet these limits:
git add on files you want the cloud session to seePull a cloud session into your terminal using any of these:
--teleport: from the command line, run claude --teleport for an interactive session picker, or claude --teleport <session-id> to resume a specific session directly. If you have uncommitted changes, you'll be prompted to stash them first./teleport: inside an existing CLI session, run /teleport (or /tp) to open the same session picker without restarting Claude Code./tasks: run /tasks to see your background sessions, then press t to teleport into oneWhen you teleport a session, Claude verifies you're in the correct repository, fetches and checks out the branch from the cloud session, and loads the full conversation history into your terminal.
--teleport is distinct from --resume. --resume reopens a conversation from this machine's local history and doesn't list cloud sessions; --teleport pulls a cloud session and its branch.
Teleport checks these requirements before resuming a session. If any requirement isn't met, you'll see an error or be prompted to resolve the issue.
| Requirement | Details |
|---|---|
| Clean git state | Your working directory must have no uncommitted changes. Teleport prompts you to stash changes if needed. |
| Correct repository | You must run --teleport from a checkout of the same repository, not a fork. |
| Branch available | The branch from the cloud session must have been pushed to the remote. Teleport automatically fetches and checks it out. |
| Same account | You must be authenticated to the same claude.ai account used in the cloud session. |
--teleport is unavailableTeleport requires claude.ai subscription authentication. If you're authenticated via API key, Bedrock, Vertex AI, or Microsoft Foundry, run /login to sign in with your claude.ai account instead. If you're already signed in via claude.ai and --teleport is still unavailable, your organization may have disabled cloud sessions.
Sessions appear in the sidebar at claude.ai/code. From there you can review changes, share with teammates, archive finished work, or delete sessions permanently.
Cloud sessions support built-in commands that produce text output. Commands that open an interactive terminal picker, like /model or /config, are not available.
For context management specifically:
| Command | Works in cloud sessions | Notes |
|---|---|---|
/compact |
Yes | Summarizes the conversation to free up context. Accepts optional focus instructions like /compact keep the test output |
/context |
Yes | Shows what's currently in the context window |
/clear |
No | Start a new session from the sidebar instead |
Auto-compaction runs automatically when the context window approaches capacity, the same as in the CLI. To trigger it earlier, set CLAUDE_AUTOCOMPACT_PCT_OVERRIDE in your environment variables. For example, CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=70 compacts at 70% capacity instead of the default ~95%. To change the effective window size for compaction calculations, use CLAUDE_CODE_AUTO_COMPACT_WINDOW.
Subagents work the same way they do locally. Claude can spawn them with the Task tool to offload research or parallel work into a separate context window, keeping the main conversation lighter. Subagents defined in your repo's .claude/agents/ are picked up automatically. Agent teams are off by default but can be enabled by adding CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 to your environment variables.
Each session shows a diff indicator with lines added and removed, like +42 -18. Select it to open the diff view, leave inline comments on specific lines, and send them to Claude with your next message. See Review and iterate for the full walkthrough including PR creation. To have Claude monitor the PR for CI failures and review comments automatically, see Auto-fix pull requests.
To share a session, toggle its visibility according to the account types below. After that, share the session link as-is. Recipients see the latest state when they open the link, but their view doesn't update in real time.
For Enterprise and Team accounts, the two visibility options are Private and Team. Team visibility makes the session visible to other members of your claude.ai organization. Repository access verification is enabled by default, based on the GitHub account connected to the recipient's account. Your account's display name is visible to all recipients with access. Claude in Slack sessions are automatically shared with Team visibility.
For Max and Pro accounts, the two visibility options are Private and Public. Public visibility makes the session visible to any user logged into claude.ai.
Check your session for sensitive content before sharing. Sessions may contain code and credentials from private GitHub repositories. Repository access verification is not enabled by default.
To require recipients to have repository access, or to hide your name from shared sessions, go to Settings > Claude Code > Sharing settings.
You can archive sessions to keep your session list organized. Archived sessions are hidden from the default session list but can be viewed by filtering for archived sessions.
To archive a session, hover over the session in the sidebar and select the archive icon.
Deleting a session permanently removes the session and its data. This action cannot be undone. You can delete a session in two ways:
You will be asked to confirm before a session is deleted.
Claude can watch a pull request and automatically respond to CI failures and review comments. Claude subscribes to GitHub activity on the PR, and when a check fails or a reviewer leaves a comment, Claude investigates and pushes a fix if one is clear.
Note
Auto-fix requires the Claude GitHub App to be installed on your repository. If you haven't already, install it from the GitHub App page or when prompted during setup.
There are a few ways to turn on auto-fix depending on where the PR came from and what device you're using:
/autofix-pr while on the PR's branch. Claude Code detects the open PR with gh, spawns a web session, and turns on auto-fix in one stepWhen auto-fix is active, Claude receives GitHub events for the PR including new review comments and CI check failures. For each event, Claude investigates and decides how to proceed:
Claude may reply to review comment threads on GitHub as part of resolving them. These replies are posted using your GitHub account, so they appear under your username, but each reply is labeled as coming from Claude Code so reviewers know it was written by the agent and not by you directly.
Warning
If your repository uses comment-triggered automation such as Atlantis, Terraform Cloud, or custom GitHub Actions that run on issue_comment events, be aware that Claude can reply on your behalf, which can trigger those workflows. Review your repository's automation before enabling auto-fix, and consider disabling auto-fix for repositories where a PR comment can deploy infrastructure or run privileged operations.
Each cloud session is separated from your machine and from other sessions through several layers:
Before relying on cloud sessions for a workflow, account for these constraints:
Start a plan from your CLI, draft it on Claude Code on the web, then execute it remotely or back in your terminal
Note
Ultraplan is in research preview and requires Claude Code v2.1.91 or later. Behavior and capabilities may change based on feedback.
Ultraplan hands a planning task from your local CLI to a Claude Code on the web session running in plan mode. Claude drafts the plan in the cloud while you keep working in your terminal. When the plan is ready, you open it in your browser to comment on specific sections, ask for revisions, and choose where to execute it.
This is useful when you want a richer review surface than the terminal offers:
Ultraplan requires a Claude Code on the web account and a GitHub repository. Because it runs on Anthropic's cloud infrastructure, it is not available when using Amazon Bedrock, Google Cloud Vertex AI, or Microsoft Foundry. The cloud session runs in your account's default cloud environment. If you don't have a cloud environment yet, ultraplan creates one automatically when it first launches.
From your local CLI session, you can launch ultraplan in three ways:
/ultraplan followed by your promptultraplan anywhere in a normal promptFor example, to plan a service migration with the command:
/ultraplan migrate the auth service from sessions to JWTs
The command and keyword paths open a confirmation dialog before launching. The local plan path skips this dialog because that selection already serves as confirmation. If Remote Control is active, it disconnects when ultraplan starts because both features occupy the claude.ai/code interface and only one can be connected at a time.
After the cloud session launches, your CLI's prompt input shows a status indicator while the remote session works:
| Status | Meaning |
|---|---|
◇ ultraplan |
Claude is researching your codebase and drafting the plan |
◇ ultraplan needs your input |
Claude has a clarifying question; open the session link to respond |
◆ ultraplan ready |
The plan is ready to review in your browser |
Run /tasks and select the ultraplan entry to open a detail view with the session link, agent activity, and a Stop ultraplan action. Stopping archives the cloud session and clears the indicator; nothing is saved to your terminal.
When the status changes to ◆ ultraplan ready, open the session link to view the plan on claude.ai. The plan appears in a dedicated review view:
When you ask Claude to address your comments, it revises the plan and presents an updated draft. You can iterate as many times as needed before choosing where to execute.
When the plan looks right, you choose from the browser whether Claude implements it in the same cloud session or sends it back to your waiting terminal.
Select Approve Claude's plan and start coding in your browser to have Claude implement it in the same Claude Code on the web session. Your terminal shows a confirmation, the status indicator clears, and the work continues in the cloud. When the implementation finishes, review the diff and create a pull request from the web interface.
Select Approve plan and teleport back to terminal in your browser to implement the plan locally with full access to your environment. This option appears when the session was launched from your CLI and the terminal is still polling. The web session is archived so it doesn't continue working in parallel.
Your terminal shows the plan in a dialog titled Ultraplan approved with three options:
If you start a new session, Claude prints a claude --resume command at the top so you can return to your previous conversation later.
Schedule recurring Claude Code tasks on a cron-like interval. Automate PR reviews, dependency audits, and CI triage in cloud sessions.
A scheduled task runs a prompt on a recurring cadence using Anthropic-managed infrastructure. Tasks keep working even when your computer is off.
A few examples of recurring work you can automate:
Scheduled tasks are available to all Claude Code on the web users, including Pro, Max, Team, and Enterprise.
Claude Code offers three ways to schedule recurring work:
| Cloud | Desktop | /loop |
|
|---|---|---|---|
| Runs on | Anthropic cloud | Your machine | Your machine |
| Requires machine on | No | Yes | Yes |
| Requires open session | No | No | Yes |
| Persistent across restarts | Yes | Yes | No (session-scoped) |
| Access to local files | No (fresh clone) | Yes | Yes |
| MCP servers | Connectors configured per task | Config files and connectors | Inherits from session |
| Permission prompts | No (runs autonomously) | Configurable per task | Inherits from session |
| Customizable schedule | Via /schedule in the CLI |
Yes | Yes |
| Minimum interval | 1 hour | 1 minute | 1 minute |
Tip
Use cloud tasks for work that should run reliably without your machine. Use Desktop tasks when you need access to local files and tools. Use /loop for quick polling during a session.
You can create a scheduled task from three places:
/schedule in any session. Claude walks you through the setup conversationally. You can also pass a description directly, like /schedule daily PR review at 9am.The web and Desktop entry points open a form. The CLI collects the same information through a guided conversation.
The steps below walk through the web interface.
Visit claude.ai/code/scheduled and click New scheduled task.
Give the task a descriptive name and write the prompt Claude runs each time. The prompt is the most important part: the task runs autonomously, so the prompt must be self-contained and explicit about what to do and what success looks like.
The prompt input includes a model selector. Claude uses this model for each run of the task.
Add one or more GitHub repositories for Claude to work in. Each repository is cloned at the start of a run, starting from the default branch. Claude creates claude/-prefixed branches for its changes. To allow pushes to any branch, enable Allow unrestricted branch pushes for that repository.
Select a cloud environment for the task. Environments control what the cloud session has access to:
A Default environment is available out of the box. To use a custom environment, create one before creating the task.
Pick how often the task runs from the frequency options. The default is daily at 9:00 AM in your local time zone. Tasks may run a few minutes after their scheduled time due to stagger.
If the preset options don't fit your needs, pick the closest one and update the schedule from the CLI with /schedule update to set a specific schedule.
All of your connected MCP connectors are included by default. Remove any that the task doesn't need. Connectors give Claude access to external services like Slack, Linear, or Google Drive during each run.
Click Create. The task appears in the scheduled tasks list and runs automatically at the next scheduled time. Each run creates a new session alongside your other sessions, where you can see what Claude did, review changes, and create a pull request. To trigger a run immediately, click Run now from the task's detail page.
The schedule picker offers preset frequencies that handle time zone conversion for you. Pick a time in your local zone and the task runs at that wall-clock time regardless of where the cloud infrastructure is located.
Note
Tasks may run a few minutes after their scheduled time. The offset is consistent for each task.
| Frequency | Description |
|---|---|
| Hourly | Runs every hour. |
| Daily | Runs once per day at the time you specify. Defaults to 9:00 AM local time. |
| Weekdays | Same as Daily but skips Saturday and Sunday. |
| Weekly | Runs once per week on the day and time you specify. |
For custom intervals like every 2 hours or first of each month, pick the closest preset and update the schedule from the CLI with /schedule update to set a specific cron expression. The minimum interval is 1 hour. Expressions that fire more frequently, such as */30 * * * *, are rejected.
Scheduled tasks need GitHub access to clone repositories. When you create a task from the CLI with /schedule, Claude checks whether your account has GitHub connected and prompts you to run /web-setup if it doesn't. See GitHub authentication options for the two ways to grant access.
Each repository you add is cloned on every run. Claude starts from the repository's default branch unless your prompt specifies otherwise.
By default, Claude can only push to branches prefixed with claude/. This prevents scheduled tasks from accidentally modifying protected or long-lived branches.
To remove this restriction for a specific repository, enable Allow unrestricted branch pushes for that repository when creating or editing the task.
Scheduled tasks can use your connected MCP connectors to read from and write to external services during each run. For example, a task that triages support requests might read from a Slack channel and create issues in Linear.
When you create a task, all of your currently connected connectors are included by default. Remove any that aren't needed to limit which tools Claude has access to during the run. You can also add connectors directly from the task form.
To manage or add connectors outside of the task form, visit Settings > Connectors on claude.ai or use /schedule update in the CLI.
Each task runs in a cloud environment that controls network access, environment variables, and setup scripts. Configure environments before creating a task to give Claude access to APIs, install dependencies, or restrict network scope. See cloud environment for the full setup guide.
Click a task in the Scheduled list to open its detail page. The detail page shows the task's repositories, connectors, prompt, schedule, and a list of past runs.
Click any run to open it as a full session. From there you can see what Claude did, review changes, create a pull request, or continue the conversation. Each run session works like any other session: use the dropdown menu next to the session title to rename, archive, or delete it.
From the task detail page you can:
You can also manage tasks from the CLI with /schedule. Run /schedule list to see all tasks, /schedule update to change a task, or /schedule run to trigger one immediately.
/loop and CLI scheduled tasks: lightweight scheduling within a CLI sessionSet up automated PR reviews that catch logic errors, security vulnerabilities, and regressions using multi-agent analysis of your full codebase
Note
Code Review is in research preview, available for Team and Enterprise subscriptions. It is not available for organizations with Zero Data Retention enabled.
Code Review analyzes your GitHub pull requests and posts findings as inline comments on the lines of code where it found issues. A fleet of specialized agents examine the code changes in the context of your full codebase, looking for logic errors, security vulnerabilities, broken edge cases, and subtle regressions.
Findings are tagged by severity and don't approve or block your PR, so existing review workflows stay intact. You can tune what Claude flags by adding a CLAUDE.md or REVIEW.md file to your repository.
To run Claude in your own CI infrastructure instead of this managed service, see GitHub Actions or GitLab CI/CD. For repositories on a self-hosted GitHub instance, see GitHub Enterprise Server.
This page covers:
@claude review and @claude review onceCLAUDE.md and REVIEW.mdOnce an admin enables Code Review for your organization, reviews trigger when a PR opens, on every push, or when manually requested, depending on the repository's configured behavior. Commenting @claude review starts reviews on a PR in any mode.
When a review runs, multiple agents analyze the diff and surrounding code in parallel on Anthropic infrastructure. Each agent looks for a different class of issue, then a verification step checks candidates against actual code behavior to filter out false positives. The results are deduplicated, ranked by severity, and posted as inline comments on the specific lines where issues were found. If no issues are found, Claude posts a short confirmation comment on the PR.
Reviews scale in cost with PR size and complexity, completing in 20 minutes on average. Admins can monitor review activity and spend via the analytics dashboard.
Each finding is tagged with a severity level:
| Marker | Severity | Meaning |
|---|---|---|
| 🔴 | Important | A bug that should be fixed before merging |
| 🟡 | Nit | A minor issue, worth fixing but not blocking |
| 🟣 | Pre-existing | A bug that exists in the codebase but was not introduced by this PR |
Findings include a collapsible extended reasoning section you can expand to understand why Claude flagged the issue and how it verified the problem.
Each review comment from Claude arrives with 👍 and 👎 already attached so both buttons appear in the GitHub UI for one-click rating. Click 👍 if the finding was useful or 👎 if it was wrong or noisy. Anthropic collects reaction counts after the PR merges and uses them to tune the reviewer. Reactions do not trigger a re-review or change anything on the PR.
Replying to an inline comment does not prompt Claude to respond or update the PR. To act on a finding, fix the code and push. If the PR is subscribed to push-triggered reviews, the next run resolves the thread when the issue is fixed. To request a fresh review without pushing, comment @claude review once as a top-level PR comment.
Beyond the inline review comments, each review populates the Claude Code Review check run that appears alongside your CI checks. Expand its Details link to see a summary of every finding in one place, sorted by severity:
| Severity | File:Line | Issue |
|---|---|---|
| 🔴 Important | src/auth/session.ts:142 |
Token refresh races with logout, leaving stale sessions active |
| 🟡 Nit | src/auth/session.ts:88 |
parseExpiry silently returns 0 on malformed input |
Each finding also appears as an annotation in the Files changed tab, marked directly on the relevant diff lines. Important findings render with a red marker, nits with a yellow warning, and pre-existing bugs with a gray notice. Annotations and the severity table are written to the check run independently of inline review comments, so they remain available even if GitHub rejects an inline comment on a line that moved.
The check run always completes with a neutral conclusion so it never blocks merging through branch protection rules. If you want to gate merges on Code Review findings, read the severity breakdown from the check run output in your own CI. The last line of the Details text is a machine-readable comment your workflow can parse with gh and jq:
gh api repos/OWNER/REPO/check-runs/CHECK_RUN_ID \
--jq '.output.text | split("bughunter-severity: ")[1] | split(" -->")[0] | fromjson'
This returns a JSON object with counts per severity, for example {"normal": 2, "nit": 1, "pre_existing": 0}. The normal key holds the count of Important findings; a non-zero value means Claude found at least one bug worth fixing before merge.
By default, Code Review focuses on correctness: bugs that would break production, not formatting preferences or missing test coverage. You can expand what it checks by adding guidance files to your repository.
An admin enables Code Review once for the organization and selects which repositories to include.
Go to claude.ai/admin-settings/claude-code and find the Code Review section. You need admin access to your Claude organization and permission to install GitHub Apps in your GitHub organization.
Click Setup. This begins the GitHub App installation flow.
Follow the prompts to install the Claude GitHub App to your GitHub organization. The app requests these repository permissions:
Code Review uses read access to contents and write access to pull requests. The broader permission set also supports GitHub Actions if you enable that later.
Choose which repositories to enable for Code Review. If you don't see a repository, make sure you gave the Claude GitHub App access to it during installation. You can add more repositories later.
After setup completes, the Code Review section shows your repositories in a table. For each repository, use the Review Behavior dropdown to choose when reviews run:
@claude review or @claude review once on a PR; @claude review also subscribes the PR to reviews on subsequent pushesReviewing on every push runs the most reviews and costs the most. Manual mode is useful for high-traffic repos where you want to opt specific PRs into review, or to only start reviewing your PRs once they're ready.
The repositories table also shows the average cost per review for each repo based on recent activity. Use the row actions menu to turn Code Review on or off per repository, or to remove a repository entirely.
To verify setup, open a test PR. If you chose an automatic trigger, a check run named Claude Code Review appears within a few minutes. If you chose Manual, comment @claude review on the PR to start the first review. If no check run appears, confirm the repository is listed in your admin settings and the Claude GitHub App has access to it.
Two comment commands start a review on demand. Both work regardless of the repository's configured trigger, so you can use them to opt specific PRs into review in Manual mode or to get an immediate re-review in other modes.
| Command | What it does |
|---|---|
@claude review |
Starts a review and subscribes the PR to push-triggered reviews going forward |
@claude review once |
Starts a single review without subscribing the PR to future pushes |
Use @claude review once when you want feedback on the current state of a PR but don't want every subsequent push to incur a review. This is useful for long-running PRs with frequent pushes, or when you want a one-off second opinion without changing the PR's review behavior.
For either command to trigger a review:
once on the same line if you're using the one-shot formUnlike automatic triggers, manual triggers run on draft PRs, since an explicit request signals you want the review now regardless of draft status.
If a review is already running on that PR, the request is queued until the in-progress review completes. You can monitor progress via the check run on the PR.
Code Review reads two files from your repository to guide what it flags. Both are additive on top of the default correctness checks:
CLAUDE.md: shared project instructions that Claude Code uses for all tasks, not just reviews. Use it when guidance also applies to interactive Claude Code sessions.REVIEW.md: review-only guidance, read exclusively during code reviews. Use it for rules that are strictly about what to flag or skip during review and would clutter your general CLAUDE.md.Code Review reads your repository's CLAUDE.md files and treats newly-introduced violations as nit-level findings. This works bidirectionally: if your PR changes code in a way that makes a CLAUDE.md statement outdated, Claude flags that the docs need updating too.
Claude reads CLAUDE.md files at every level of your directory hierarchy, so rules in a subdirectory's CLAUDE.md apply only to files under that path. See the memory documentation for more on how CLAUDE.md works.
For review-specific guidance that you don't want applied to general Claude Code sessions, use REVIEW.md instead.
Add a REVIEW.md file to your repository root for review-specific rules. Use it to encode:
/gen/"Example REVIEW.md:
# Code Review Guidelines
## Always check
- New API endpoints have corresponding integration tests
- Database migrations are backward-compatible
- Error messages don't leak internal details to users
## Style
- Prefer `match` statements over chained `isinstance` checks
- Use structured logging, not f-string interpolation in log calls
## Skip
- Generated files under `src/gen/`
- Formatting-only changes in `*.lock` files
Claude auto-discovers REVIEW.md at the repository root. No configuration needed.
Go to claude.ai/analytics/code-review to see Code Review activity across your organization. The dashboard shows:
| Section | What it shows |
|---|---|
| PRs reviewed | Daily count of pull requests reviewed over the selected time range |
| Cost weekly | Weekly spend on Code Review |
| Feedback | Count of review comments that were auto-resolved because a developer addressed the issue |
| Repository breakdown | Per-repo counts of PRs reviewed and comments resolved |
The repositories table in admin settings also shows average cost per review for each repo.
Code Review is billed based on token usage. Each review averages $15-25 in cost, scaling with PR size, codebase complexity, and how many issues require verification. Code Review usage is billed separately through extra usage and does not count against your plan's included usage.
The review trigger you choose affects total cost:
@claude review on a PRIn any mode, commenting @claude review opts the PR into push-triggered reviews, so additional cost accrues per push after that comment. To run a single review without subscribing to future pushes, comment @claude review once instead.
Costs appear on your Anthropic bill regardless of whether your organization uses AWS Bedrock or Google Vertex AI for other Claude Code features. To set a monthly spend cap for Code Review, go to claude.ai/admin-settings/usage and configure the limit for the Claude Code Review service.
Monitor spend via the weekly cost chart in analytics or the per-repo average cost column in admin settings.
Review runs are best-effort. A failed run never blocks your PR, but it also doesn't retry on its own. This section covers how to recover from a failed run and where to look when the check run reports issues you can't find.
When the review infrastructure hits an internal error or exceeds its time limit, the check run completes with a title of Code review encountered an error or Code review timed out. The conclusion is still neutral, so nothing blocks your merge, but no findings are posted.
To run the review again, comment @claude review once on the PR. This starts a fresh review without subscribing the PR to future pushes. If the PR is already subscribed to push-triggered reviews, pushing a new commit also starts a new review.
The Re-run button in GitHub's Checks tab does not retrigger Code Review. Use the comment command or a new push instead.
If the check run title says issues were found but you don't see inline review comments on the diff, look in these other locations where findings are surfaced:
Code Review is designed to work alongside the rest of Claude Code. If you want to run reviews locally before opening a PR, need a self-hosted setup, or want to go deeper on how CLAUDE.md shapes Claude's behavior across tools, these pages are good next stops:
code-review plugin for running on-demand reviews locally before pushingCLAUDE.md files work across Claude CodeLearn about integrating Claude Code into your development workflow with Claude Code GitHub Actions
Claude Code GitHub Actions brings AI-powered automation to your GitHub workflow. With a simple @claude mention in any PR or issue, Claude can analyze your code, create pull requests, implement features, and fix bugs - all while following your project's standards. For automatic reviews posted on every PR without a trigger, see GitHub Code Review.
Note
Claude Code GitHub Actions is built on top of the Claude Agent SDK, which enables programmatic integration of Claude Code into your applications. You can use the SDK to build custom automation workflows beyond GitHub Actions.
Info
Claude Opus 4.6 is now available. Claude Code GitHub Actions default to Sonnet. To use Opus 4.6, configure the model parameter to use claude-opus-4-6.
CLAUDE.md guidelines and existing code patternsClaude Code provides a powerful GitHub Action that transforms how you work with code:
This GitHub Action allows you to run Claude Code within your GitHub Actions workflows. You can use this to build any custom workflow on top of Claude Code.
The easiest way to set up this action is through Claude Code in the terminal. Just open claude and run /install-github-app.
This command will guide you through setting up the GitHub app and required secrets.
Note
If the /install-github-app command fails or you prefer manual setup, please follow these manual setup instructions:
Install the Claude GitHub app to your repository: https://github.com/apps/claude
The Claude GitHub app requires the following repository permissions:
For more details on security and permissions, see the security documentation.
Add ANTHROPIC_API_KEY to your repository secrets (Learn how to use secrets in GitHub Actions)
Copy the workflow file from examples/claude.yml into your repository's .github/workflows/
Tip
After completing either the quickstart or manual setup, test the action by tagging @claude in an issue or PR comment.
Warning
Claude Code GitHub Actions v1.0 introduces breaking changes that require updating your workflow files in order to upgrade to v1.0 from the beta version.
If you're currently using the beta version of Claude Code GitHub Actions, we recommend that you update your workflows to use the GA version. The new version simplifies configuration while adding powerful new features like automatic mode detection.
All beta users must make these changes to their workflow files in order to upgrade:
@beta to @v1mode: "tag" or mode: "agent" (now auto-detected)direct_prompt with promptmax_turns, model, custom_instructions, etc. to claude_args| Old Beta Input | New v1.0 Input |
|---|---|
mode |
(Removed - auto-detected) |
direct_prompt |
prompt |
override_prompt |
prompt with GitHub variables |
custom_instructions |
claude_args: --append-system-prompt |
max_turns |
claude_args: --max-turns |
model |
claude_args: --model |
allowed_tools |
claude_args: --allowedTools |
disallowed_tools |
claude_args: --disallowedTools |
claude_env |
settings JSON format |
Beta version:
- uses: anthropics/claude-code-action@beta
with:
mode: "tag"
direct_prompt: "Review this PR for security issues"
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
custom_instructions: "Follow our coding standards"
max_turns: "10"
model: "claude-sonnet-4-6"
GA version (v1.0):
- uses: anthropics/claude-code-action@v1
with:
prompt: "Review this PR for security issues"
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
claude_args: |
--append-system-prompt "Follow our coding standards"
--max-turns 10
--model claude-sonnet-4-6
Tip
The action now automatically detects whether to run in interactive mode (responds to @claude mentions) or automation mode (runs immediately with a prompt) based on your configuration.
Claude Code GitHub Actions can help you with a variety of tasks. The examples directory contains ready-to-use workflows for different scenarios.
name: Claude Code
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
jobs:
claude:
runs-on: ubuntu-latest
steps:
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# Responds to @claude mentions in comments
name: Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
prompt: "Review this pull request for code quality, correctness, and security. Analyze the diff, then post your findings as review comments."
claude_args: "--max-turns 5"
name: Daily Report
on:
schedule:
- cron: "0 9 * * *"
jobs:
report:
runs-on: ubuntu-latest
steps:
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
prompt: "Generate a summary of yesterday's commits and open issues"
claude_args: "--model opus"
In issue or PR comments:
@claude implement this feature based on the issue description
@claude how should I implement user authentication for this endpoint?
@claude fix the TypeError in the user dashboard component
Claude will automatically analyze the context and respond appropriately.
Create a CLAUDE.md file in your repository root to define code style guidelines, review criteria, project-specific rules, and preferred patterns. This file guides Claude's understanding of your project standards.
Warning
Never commit API keys directly to your repository.
For comprehensive security guidance including permissions, authentication, and best practices, see the Claude Code Action security documentation.
Always use GitHub Secrets for API keys:
ANTHROPIC_API_KEYanthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}Always use GitHub Secrets (for example, ${{ secrets.ANTHROPIC_API_KEY }}) rather than hardcoding API keys directly in your workflow files.
Use issue templates to provide context, keep your CLAUDE.md concise and focused, and configure appropriate timeouts for your workflows.
When using Claude Code GitHub Actions, be aware of the associated costs:
GitHub Actions costs:
API costs:
Cost optimization tips:
@claude commands to reduce unnecessary API calls--max-turns in claude_args to prevent excessive iterationsThe Claude Code Action v1 simplifies configuration with unified parameters:
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
prompt: "Your instructions here" # Optional
claude_args: "--max-turns 5" # Optional CLI arguments
Key features:
prompt for all instructionsclaude_argsVisit the examples directory for complete workflow files.
Tip
When responding to issue or PR comments, Claude automatically responds to @claude mentions. For other events, use the prompt parameter to provide instructions.
For enterprise environments, you can use Claude Code GitHub Actions with your own cloud infrastructure. This approach gives you control over data residency and billing while maintaining the same functionality.
Before setting up Claude Code GitHub Actions with cloud providers, you need:
For best control and security when using 3P providers like Vertex AI or Bedrock, we recommend creating your own GitHub App:
.pem fileAPP_PRIVATE_KEY with the contents of the .pem fileAPP_ID with your GitHub App's IDNote
This app will be used with the actions/create-github-app-token action to generate authentication tokens in your workflows.
Alternative for Claude API or if you don't want to setup your own Github app: Use the official Anthropic app:
Choose your cloud provider and set up secure authentication:
Configure AWS to allow GitHub Actions to authenticate securely without storing credentials.
Security Note: Use repository-specific configurations and grant only the minimum required permissions.
Required Setup:
Enable Amazon Bedrock:
Set up GitHub OIDC Identity Provider:
https://token.actions.githubusercontent.comsts.amazonaws.comCreate IAM Role for GitHub Actions:
token.actions.githubusercontent.comAmazonBedrockFullAccess policyRequired Values:
After setup, you'll need:
Tip
OIDC is more secure than using static AWS access keys because credentials are temporary and automatically rotated.
See AWS documentation for detailed OIDC setup instructions.
Configure Google Cloud to allow GitHub Actions to authenticate securely without storing credentials.
Security Note: Use repository-specific configurations and grant only the minimum required permissions.
Required Setup:
Enable APIs in your Google Cloud project:
Create Workload Identity Federation resources:
https://token.actions.githubusercontent.comCreate a Service Account:
Vertex AI User roleConfigure IAM bindings:
Required Values:
After setup, you'll need:
Tip
Workload Identity Federation eliminates the need for downloadable service account keys, improving security.
For detailed setup instructions, consult the Google Cloud Workload Identity Federation documentation.
Add the following secrets to your repository (Settings → Secrets and variables → Actions):
For API Authentication:
ANTHROPIC_API_KEY: Your Claude API key from console.anthropic.comFor GitHub App (if using your own app):
APP_ID: Your GitHub App's IDAPP_PRIVATE_KEY: The private key (.pem) contentFor GCP Authentication:
GCP_WORKLOAD_IDENTITY_PROVIDERGCP_SERVICE_ACCOUNTFor GitHub App (if using your own app):
APP_ID: Your GitHub App's IDAPP_PRIVATE_KEY: The private key (.pem) contentFor AWS Authentication:
AWS_ROLE_TO_ASSUMEFor GitHub App (if using your own app):
APP_ID: Your GitHub App's IDAPP_PRIVATE_KEY: The private key (.pem) contentCreate GitHub Actions workflow files that integrate with your cloud provider. The examples below show complete configurations for both AWS Bedrock and Google Vertex AI:
Prerequisites:
Required GitHub secrets:
| Secret Name | Description |
|---|---|
AWS_ROLE_TO_ASSUME |
ARN of the IAM role for Bedrock access |
APP_ID |
Your GitHub App ID (from app settings) |
APP_PRIVATE_KEY |
The private key you generated for your GitHub App |
name: Claude PR Action
permissions:
contents: write
pull-requests: write
issues: write
id-token: write
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
jobs:
claude-pr:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'issues' && contains(github.event.issue.body, '@claude'))
runs-on: ubuntu-latest
env:
AWS_REGION: us-west-2
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Generate GitHub App token
id: app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.APP_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
- name: Configure AWS Credentials (OIDC)
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }}
aws-region: us-west-2
- uses: anthropics/claude-code-action@v1
with:
github_token: ${{ steps.app-token.outputs.token }}
use_bedrock: "true"
claude_args: '--model us.anthropic.claude-sonnet-4-6 --max-turns 10'
Tip
The model ID format for Bedrock includes a region prefix (for example, us.anthropic.claude-sonnet-4-6).
Prerequisites:
Required GitHub secrets:
| Secret Name | Description |
|---|---|
GCP_WORKLOAD_IDENTITY_PROVIDER |
Workload identity provider resource name |
GCP_SERVICE_ACCOUNT |
Service account email with Vertex AI access |
APP_ID |
Your GitHub App ID (from app settings) |
APP_PRIVATE_KEY |
The private key you generated for your GitHub App |
name: Claude PR Action
permissions:
contents: write
pull-requests: write
issues: write
id-token: write
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
jobs:
claude-pr:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'issues' && contains(github.event.issue.body, '@claude'))
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Generate GitHub App token
id: app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.APP_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
- name: Authenticate to Google Cloud
id: auth
uses: google-github-actions/auth@v2
with:
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
- uses: anthropics/claude-code-action@v1
with:
github_token: ${{ steps.app-token.outputs.token }}
trigger_phrase: "@claude"
use_vertex: "true"
claude_args: '--model claude-sonnet-4-5@20250929 --max-turns 10'
env:
ANTHROPIC_VERTEX_PROJECT_ID: ${{ steps.auth.outputs.project_id }}
CLOUD_ML_REGION: us-east5
VERTEX_REGION_CLAUDE_4_5_SONNET: us-east5
Tip
The project ID is automatically retrieved from the Google Cloud authentication step, so you don't need to hardcode it.
Verify the GitHub App is installed correctly, check that workflows are enabled, ensure API key is set in repository secrets, and confirm the comment contains @claude (not /claude).
Ensure you're using the GitHub App or custom app (not Actions user), check workflow triggers include the necessary events, and verify app permissions include CI triggers.
Confirm API key is valid and has sufficient permissions. For Bedrock/Vertex, check credentials configuration and ensure secrets are named correctly in workflows.
The Claude Code Action v1 uses a simplified configuration:
| Parameter | Description | Required |
|---|---|---|
prompt |
Instructions for Claude (plain text or a skill name) | No* |
claude_args |
CLI arguments passed to Claude Code | No |
anthropic_api_key |
Claude API key | Yes** |
github_token |
GitHub token for API access | No |
trigger_phrase |
Custom trigger phrase (default: "@claude") | No |
use_bedrock |
Use AWS Bedrock instead of Claude API | No |
use_vertex |
Use Google Vertex AI instead of Claude API | No |
*Prompt is optional - when omitted for issue/PR comments, Claude responds to trigger phrase
**Required for direct Claude API, not for Bedrock/Vertex
The claude_args parameter accepts any Claude Code CLI arguments:
claude_args: "--max-turns 5 --model claude-sonnet-4-6 --mcp-config /path/to/config.json"
Common arguments:
--max-turns: Maximum conversation turns (default: 10)--model: Model to use (for example, claude-sonnet-4-6)--mcp-config: Path to MCP configuration--allowedTools: Comma-separated list of allowed tools. The --allowed-tools alias also works.--debug: Enable debug outputWhile the /install-github-app command is the recommended approach, you can also:
See the Claude Code Action documentation for detailed guides on authentication, security, and advanced configuration.
You can configure Claude's behavior in two ways:
CLAUDE.md file at the root of your repository. Claude will follow these guidelines when creating PRs and responding to requests. Check out our Memory documentation for more details.prompt parameter in the workflow file to provide workflow-specific instructions. This allows you to customize Claude's behavior for different workflows or tasks.Claude will follow these guidelines when creating PRs and responding to requests.
Connect Claude Code to your self-hosted GitHub Enterprise Server instance for web sessions, code review, and plugin marketplaces.
Note
GitHub Enterprise Server support is available for Team and Enterprise plans.
GitHub Enterprise Server (GHES) support lets your organization use Claude Code with repositories hosted on your self-managed GitHub instance instead of github.com. Once an admin connects your GHES instance, developers can run web sessions, get automated code reviews, and install plugins from internal marketplaces without any per-repository configuration.
For repositories on github.com, see Claude Code on the web and Code Review. To run Claude in your own CI infrastructure, see GitHub Actions.
The table below shows which Claude Code features support GHES and any differences from github.com behavior.
| Feature | GHES support | Notes |
|---|---|---|
| Claude Code on the web | ✅ Supported | Admin connects the GHES instance once; developers use claude --remote or claude.ai/code as usual |
| Code Review | ✅ Supported | Same automated PR reviews as github.com |
| Teleport sessions | ✅ Supported | Move sessions between web and terminal with --teleport |
| Plugin marketplaces | ✅ Supported | Use full git URLs instead of owner/repo shorthand |
| Contribution metrics | ✅ Supported | Delivered via webhooks to the analytics dashboard |
| GitHub Actions | ✅ Supported | Requires manual workflow setup; /install-github-app is github.com only |
| GitHub MCP server | ❌ Not supported | The GitHub MCP server does not work with GHES instances |
An admin connects your GHES instance to Claude Code once. After that, developers in your organization can use GHES repositories without any additional configuration. You need admin access to your Claude organization and permission to create GitHub Apps on your GHES instance.
The guided setup generates a GitHub App manifest and redirects you to your GHES instance to create the app in one click. If your environment blocks the redirect flow, an alternative manual setup is available.
Go to claude.ai/admin-settings/claude-code and find the GitHub Enterprise Server section.
Click Connect. Enter a display name for the connection and your GHES hostname, for example github.example.com. If your GHES instance uses a self-signed or private certificate authority, paste the CA certificate in the optional field.
Click Continue to GitHub Enterprise. Your browser redirects to your GHES instance with a pre-filled app manifest. Review the configuration and click Create GitHub App. GHES redirects you back to Claude with the app credentials stored automatically.
From the GitHub App page on your GHES instance, install the app on the repositories or organizations you want Claude to access. You can start with a subset and add more later.
Return to claude.ai/admin-settings/claude-code and enable Code Review and contribution metrics for your GHES repositories using the same configuration as github.com.
The manifest configures the GitHub App with the permissions and webhook events Claude needs across web sessions, Code Review, and contribution metrics:
| Permission | Access | Used for |
|---|---|---|
| Contents | Read and write | Cloning repositories and pushing branches |
| Pull requests | Read and write | Creating PRs and posting review comments |
| Issues | Read and write | Responding to issue mentions |
| Checks | Read and write | Posting Code Review check runs |
| Actions | Read | Reading CI status for auto-fix |
| Repository hooks | Read and write | Receiving webhooks for contribution metrics |
| Metadata | Read | Required by GitHub for all apps |
The app subscribes to pull_request, issue_comment, pull_request_review_comment, pull_request_review, and check_run events.
If the guided redirect flow is blocked by your network configuration, click Add manually instead of Connect. Create a GitHub App on your GHES instance with the permissions and events above, then enter the app credentials in the form: hostname, OAuth client ID and secret, GitHub App ID, client ID, client secret, webhook secret, and private key.
Your GHES instance must be reachable from Anthropic infrastructure so Claude can clone repositories and post review comments. If your GHES instance is behind a firewall, allowlist the Anthropic API IP addresses.
Once your admin has connected the GHES instance, no developer-side configuration is needed. Claude Code detects your GHES hostname automatically from the git remote in your working directory.
Clone a repository from your GHES instance as you normally would:
git clone git@github.example.com:platform/api-service.git
cd api-service
Then start a web session. Claude detects the GHES host from your git remote and routes the session through your organization's configured instance:
claude --remote "Add retry logic to the payment webhook handler"
The session runs on Anthropic infrastructure, clones your repository from GHES, and pushes changes back to a branch. Monitor progress with /tasks or at claude.ai/code. See Claude Code on the web for the full remote session workflow including diff review, auto-fix, and scheduled tasks.
Pull a web session into your local terminal with claude --teleport. Teleport verifies you're in a checkout of the same GHES repository before fetching the branch and loading the session history. See teleport requirements for details.
Host plugin marketplaces on your GHES instance to distribute internal tooling across your organization. The marketplace structure is identical to github.com-hosted marketplaces; the only difference is how you reference them.
The owner/repo shorthand always resolves to github.com. For GHES-hosted marketplaces, use the full git URL:
/plugin marketplace add git@github.example.com:platform/claude-plugins.git
HTTPS URLs work as well:
/plugin marketplace add https://github.example.com/platform/claude-plugins.git
See Create and distribute a plugin marketplace for the full guide to building marketplaces.
If your organization uses managed settings to restrict which marketplaces developers can add, use the hostPattern source type to allow all marketplaces from your GHES instance without enumerating each repository:
{
"strictKnownMarketplaces": [
{
"source": "hostPattern",
"hostPattern": "^github\\.example\\.com$"
}
]
}
You can also pre-register marketplaces for developers so they appear without manual setup. This example makes an internal tools marketplace available organization-wide:
{
"extraKnownMarketplaces": {
"internal-tools": {
"source": {
"source": "git",
"url": "git@github.example.com:platform/claude-plugins.git"
}
}
}
}
See the strictKnownMarketplaces and extraKnownMarketplaces settings reference for the complete schema.
A few features behave differently on GHES than on github.com. The feature table summarizes support; this section covers the workarounds.
/install-github-app command: follow the admin setup flow on claude.ai instead. If you also want GitHub Actions workflows on GHES, adapt the example workflow manually.gh CLI configured for your GHES host instead. Run gh auth login --hostname github.example.com to authenticate, then Claude can use gh commands in sessions.If claude --remote fails with a clone error, verify that your admin has completed setup for your GHES instance and that the GitHub App is installed on the repository you're working in. Check with your admin that the instance hostname registered in Claude settings matches the hostname in your git remote.
If /plugin marketplace add is blocked for your GHES URL, your organization has restricted marketplace sources. Ask your admin to add a hostPattern entry for your GHES hostname in managed settings.
If reviews or web sessions time out, your GHES instance may not be reachable from Anthropic infrastructure. Confirm your firewall allows inbound connections from the Anthropic API IP addresses.
These pages cover the features referenced throughout this guide in more depth:
Learn about integrating Claude Code into your development workflow with GitLab CI/CD
Info
Claude Code for GitLab CI/CD is currently in beta. Features and functionality may evolve as we refine the experience.
This integration is maintained by GitLab. For support, see the following GitLab issue.
Note
This integration is built on top of the Claude Code CLI and Agent SDK, enabling programmatic use of Claude in your CI/CD jobs and custom automation workflows.
CLAUDE.md guidelines and existing code patterns.gitlab-ci.yml and a masked CI/CD variableClaude Code uses GitLab CI/CD to run AI tasks in isolated jobs and commit results back via MRs:
Event-driven orchestration: GitLab listens for your chosen triggers (for example, a comment that mentions @claude in an issue, MR, or review thread). The job collects context from the thread and repository, builds prompts from that input, and runs Claude Code.
Provider abstraction: Use the provider that fits your environment:
Sandboxed execution: Each interaction runs in a container with strict network and filesystem rules. Claude Code enforces workspace-scoped permissions to constrain writes. Every change flows through an MR so reviewers see the diff and approvals still apply.
Pick regional endpoints to reduce latency and meet data-sovereignty requirements while using existing cloud agreements.
Claude Code enables powerful CI/CD workflows that transform how you work with code:
The fastest way to get started is to add a minimal job to your .gitlab-ci.yml and set your API key as a masked variable.
Add a masked CI/CD variable
ANTHROPIC_API_KEY (masked, protected as needed)Add a Claude job to .gitlab-ci.yml
stages:
- ai
claude:
stage: ai
image: node:24-alpine3.21
# Adjust rules to fit how you want to trigger the job:
# - manual runs
# - merge request events
# - web/API triggers when a comment contains '@claude'
rules:
- if: '$CI_PIPELINE_SOURCE == "web"'
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
variables:
GIT_STRATEGY: fetch
before_script:
- apk update
- apk add --no-cache git curl bash
- curl -fsSL https://claude.ai/install.sh | bash
script:
# Optional: start a GitLab MCP server if your setup provides one
- /bin/gitlab-mcp-server || true
# Use AI_FLOW_* variables when invoking via web/API triggers with context payloads
- echo "$AI_FLOW_INPUT for $AI_FLOW_CONTEXT on $AI_FLOW_EVENT"
- >
claude
-p "${AI_FLOW_INPUT:-'Review this MR and implement the requested changes'}"
--permission-mode acceptEdits
--allowedTools "Bash Read Edit Write mcp__gitlab"
--debug
After adding the job and your ANTHROPIC_API_KEY variable, test by running the job manually from CI/CD → Pipelines, or trigger it from an MR to let Claude propose updates in a branch and open an MR if needed.
Note
To run on AWS Bedrock or Google Vertex AI instead of the Claude API, see the Using with AWS Bedrock & Google Vertex AI section below for authentication and environment setup.
If you prefer a more controlled setup or need enterprise providers:
Configure provider access:
ANTHROPIC_API_KEY as a masked CI/CD variableAdd project credentials for GitLab API operations:
CI_JOB_TOKEN by default, or create a Project Access Token with api scopeGITLAB_ACCESS_TOKEN (masked) if using a PATAdd the Claude job to .gitlab-ci.yml (see examples below)
(Optional) Enable mention-driven triggers:
AI_FLOW_INPUT and AI_FLOW_CONTEXT when a comment contains @claudeIn an issue comment:
@claude implement this feature based on the issue description
Claude analyzes the issue and codebase, writes changes in a branch, and opens an MR for review.
In an MR discussion:
@claude suggest a concrete approach to cache the results of this API call
Claude proposes changes, adds code with appropriate caching, and updates the MR.
In an issue or MR comment:
@claude fix the TypeError in the user dashboard component
Claude locates the bug, implements a fix, and updates the branch or opens a new MR.
For enterprise environments, you can run Claude Code entirely on your cloud infrastructure with the same developer experience.
Before setting up Claude Code with AWS Bedrock, you need:
AWS_ROLE_TO_ASSUME (role ARN)AWS_REGION (Bedrock region)Configure AWS to allow GitLab CI jobs to assume an IAM role via OIDC (no static keys).
Required setup:
Required values to store in CI/CD variables:
AWS_ROLE_TO_ASSUMEAWS_REGIONAdd variables in Settings → CI/CD → Variables:
# For AWS Bedrock:
- AWS_ROLE_TO_ASSUME
- AWS_REGION
Use the AWS Bedrock job example above to exchange the GitLab job token for temporary AWS credentials at runtime.
Before setting up Claude Code with Google Vertex AI, you need:
GCP_WORKLOAD_IDENTITY_PROVIDER (full resource name)GCP_SERVICE_ACCOUNT (service account email)Configure Google Cloud to allow GitLab CI jobs to impersonate a service account via Workload Identity Federation.
Required setup:
Required values to store in CI/CD variables:
GCP_WORKLOAD_IDENTITY_PROVIDERGCP_SERVICE_ACCOUNTAdd variables in Settings → CI/CD → Variables:
# For Google Vertex AI:
- GCP_WORKLOAD_IDENTITY_PROVIDER
- GCP_SERVICE_ACCOUNT
- CLOUD_ML_REGION (for example, us-east5)
Use the Google Vertex AI job example above to authenticate without storing keys.
Below are ready-to-use snippets you can adapt to your pipeline.
stages:
- ai
claude:
stage: ai
image: node:24-alpine3.21
rules:
- if: '$CI_PIPELINE_SOURCE == "web"'
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
variables:
GIT_STRATEGY: fetch
before_script:
- apk update
- apk add --no-cache git curl bash
- curl -fsSL https://claude.ai/install.sh | bash
script:
- /bin/gitlab-mcp-server || true
- >
claude
-p "${AI_FLOW_INPUT:-'Summarize recent changes and suggest improvements'}"
--permission-mode acceptEdits
--allowedTools "Bash Read Edit Write mcp__gitlab"
--debug
# Claude Code will use ANTHROPIC_API_KEY from CI/CD variables
Prerequisites:
Required CI/CD variables:
AWS_ROLE_TO_ASSUME: ARN of the IAM role for Bedrock accessAWS_REGION: Bedrock region (for example, us-west-2)claude-bedrock:
stage: ai
image: node:24-alpine3.21
rules:
- if: '$CI_PIPELINE_SOURCE == "web"'
before_script:
- apk add --no-cache bash curl jq git python3 py3-pip
- pip install --no-cache-dir awscli
- curl -fsSL https://claude.ai/install.sh | bash
# Exchange GitLab OIDC token for AWS credentials
- export AWS_WEB_IDENTITY_TOKEN_FILE="${CI_JOB_JWT_FILE:-/tmp/oidc_token}"
- if [ -n "${CI_JOB_JWT_V2}" ]; then printf "%s" "$CI_JOB_JWT_V2" > "$AWS_WEB_IDENTITY_TOKEN_FILE"; fi
- >
aws sts assume-role-with-web-identity
--role-arn "$AWS_ROLE_TO_ASSUME"
--role-session-name "gitlab-claude-$(date +%s)"
--web-identity-token "file://$AWS_WEB_IDENTITY_TOKEN_FILE"
--duration-seconds 3600 > /tmp/aws_creds.json
- export AWS_ACCESS_KEY_ID="$(jq -r .Credentials.AccessKeyId /tmp/aws_creds.json)"
- export AWS_SECRET_ACCESS_KEY="$(jq -r .Credentials.SecretAccessKey /tmp/aws_creds.json)"
- export AWS_SESSION_TOKEN="$(jq -r .Credentials.SessionToken /tmp/aws_creds.json)"
script:
- /bin/gitlab-mcp-server || true
- >
claude
-p "${AI_FLOW_INPUT:-'Implement the requested changes and open an MR'}"
--permission-mode acceptEdits
--allowedTools "Bash Read Edit Write mcp__gitlab"
--debug
variables:
AWS_REGION: "us-west-2"
Note
Model IDs for Bedrock include region-specific prefixes (for example, us.anthropic.claude-sonnet-4-6). Pass the desired model via your job configuration or prompt if your workflow supports it.
Prerequisites:
Required CI/CD variables:
GCP_WORKLOAD_IDENTITY_PROVIDER: Full provider resource nameGCP_SERVICE_ACCOUNT: Service account emailCLOUD_ML_REGION: Vertex region (for example, us-east5)claude-vertex:
stage: ai
image: gcr.io/google.com/cloudsdktool/google-cloud-cli:slim
rules:
- if: '$CI_PIPELINE_SOURCE == "web"'
before_script:
- apt-get update && apt-get install -y git && apt-get clean
- curl -fsSL https://claude.ai/install.sh | bash
# Authenticate to Google Cloud via WIF (no downloaded keys)
- >
gcloud auth login --cred-file=<(cat <<EOF
{
"type": "external_account",
"audience": "${GCP_WORKLOAD_IDENTITY_PROVIDER}",
"subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
"service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${GCP_SERVICE_ACCOUNT}:generateAccessToken",
"token_url": "https://sts.googleapis.com/v1/token"
}
EOF
)
- gcloud config set project "$(gcloud projects list --format='value(projectId)' --filter="name:${CI_PROJECT_NAMESPACE}" | head -n1)" || true
script:
- /bin/gitlab-mcp-server || true
- >
CLOUD_ML_REGION="${CLOUD_ML_REGION:-us-east5}"
claude
-p "${AI_FLOW_INPUT:-'Review and update code as requested'}"
--permission-mode acceptEdits
--allowedTools "Bash Read Edit Write mcp__gitlab"
--debug
variables:
CLOUD_ML_REGION: "us-east5"
Note
With Workload Identity Federation, you do not need to store service account keys. Use repository-specific trust conditions and least-privilege service accounts.
Create a CLAUDE.md file at the repository root to define coding standards, review criteria, and project-specific rules. Claude reads this file during runs and follows your conventions when proposing changes.
Never commit API keys or cloud credentials to your repository. Always use GitLab CI/CD variables:
ANTHROPIC_API_KEY as a masked variable (and protect it if needed)CLAUDE.md focused and conciseWhen using Claude Code with GitLab CI/CD, be aware of associated costs:
GitLab Runner time:
API costs:
Cost optimization tips:
@claude commands to reduce unnecessary turnsmax_turns and job timeout valuesANTHROPIC_API_KEY or cloud provider settings) are present and unmasked@claude (not /claude) and that your mention trigger is configuredCI_JOB_TOKEN has sufficient permissions for the project, or use a Project Access Token with api scopemcp__gitlab tool is enabled in --allowedToolsAI_FLOW_* variablesANTHROPIC_API_KEY is valid and unexpiredClaude Code supports these commonly used inputs:
prompt / prompt_file: Provide instructions inline (-p) or via a filemax_turns: Limit the number of back-and-forth iterationstimeout_minutes: Limit total execution timeANTHROPIC_API_KEY: Required for the Claude API (not used for Bedrock/Vertex)AWS_REGION, project/region vars for VertexNote
Exact flags and parameters may vary by version of @anthropic-ai/claude-code. Run claude --help in your job to see supported options.
You can guide Claude in two primary ways:
prompt/prompt_file in the job. Use different prompts for different jobs (for example, review, implement, refactor).